diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/findbugs-exclude.xml b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/findbugs-exclude.xml deleted file mode 100644 index cd226386..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/findbugs-exclude.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/pom.xml b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/pom.xml deleted file mode 100644 index 8003b149..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/pom.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.account.metadata.service - WSO2 Open Banking - Account Metadata Service Module - bundle - - - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - - - org.apache.commons - commons-lang3 - provided - - - commons-logging - commons-logging - provided - - - org.testng - testng - test - - - com.h2database - h2 - test - - - org.mockito - mockito-all - - - org.powermock - powermock-module-testng - - - org.powermock - powermock-api-mockito - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - **/*Constants.class - **/*Component.class - **/*DataHolder.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.73 - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/findbugs-exclude.xml - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.event.notifications.service.internal - - - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - org.apache.commons.lang3;version="${commons-lang.version}" - - - !com.wso2.openbanking.accelerator.account.metadata.service.internal, - com.wso2.openbanking.accelerator.account.metadata.service.service.*;version="${project.version}", - com.wso2.openbanking.accelerator.account.metadata.service.dao.*;version="${project.version}", -\ - - javax.ws.rs-api;scope=compile;inline=false, - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAO.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAO.java deleted file mode 100644 index 3bf5ea3b..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAO.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.dao; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -import java.sql.Connection; -import java.util.Map; - -/** - * AccountMetadataDAO - *

- * Contains the methods to store, retrieve and delete account - * metadata in the database. - */ -public interface AccountMetadataDAO { - - /** - * Store account metadata. - * - * @param accountId - Account ID - * @param userId - User ID - * @param metadataKey - Metadata key - * @param metadataValue - Metadata value - * @return number of rows affected - * @throws OpenBankingException - OpenBankingException - */ - int storeAccountMetadata(Connection dbConnection, String accountId, String userId, String metadataKey, - String metadataValue) throws OpenBankingException; - - /** - * Store or update account metadata. - * If the key already exists for the account-id and user-id combination, the value be updated. - * - * @param accountId - Account ID - * @param userId - User ID - * @param metadataKey - Metadata key - * @param metadataValue - Metadata value - * @return number of rows affected - * @throws OpenBankingException - OpenBankingException - */ - int updateAccountMetadata(Connection dbConnection, String accountId, String userId, String metadataKey, - String metadataValue) throws OpenBankingException; - - /** - * Retrieve account metadata for a given user-id and account-id combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @return Map of account metadata - * @throws OpenBankingException - OpenBankingException - */ - Map getAccountMetadataMap(Connection dbConnection, String accountId, String userId) - throws OpenBankingException; - - /** - * Retrieve account metadata for a given account-id and key combination. - * - * @param accountId - Account ID - * @param key - Attribute key - * @return Map of user-id and attribute value - * @throws OpenBankingException - OpenBankingException - */ - Map getMetadataForAccountIdAndKey(Connection dbConnection, String accountId, String key) - throws OpenBankingException; - - /** - * Retrieve the value for the given account-id, user-id and key combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @param key - Key - * @return Attribute value - * @throws OpenBankingException - OpenBankingException - */ - String getAccountMetadataByKey(Connection dbConnection, String accountId, String userId, String key) - throws OpenBankingException; - - /** - * Delete all account metadata for a given user-id and account-id combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @return number of rows affected - * @throws OpenBankingException - OpenBankingException - */ - int deleteAccountMetadata(Connection dbConnection, String accountId, String userId) throws OpenBankingException; - - /** - * Delete account metadata for a given user-id, account-id and key combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @param key - Key - * @return number of rows affected - * @throws OpenBankingException - OpenBankingException - */ - int deleteAccountMetadataByKey(Connection dbConnection, String accountId, String userId, String key) throws - OpenBankingException; - - /** - * Delete all account metadata for a given account-id and key combination. - * - * @param accountId - Account ID - * @param key - Key - * @return number of rows affected - * @throws OpenBankingException - OpenBankingException - */ - int deleteAccountMetadataByKeyForAllUsers(Connection dbConnection, String accountId, String key) throws - OpenBankingException; - -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAOImpl.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAOImpl.java deleted file mode 100644 index 1fe8c4e8..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAOImpl.java +++ /dev/null @@ -1,493 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.dao; - -import com.wso2.openbanking.accelerator.account.metadata.service.dao.queries.AccountMetadataDBQueries; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Savepoint; -import java.sql.Timestamp; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * Implementation of AccountMetadataDAO. - */ -public class AccountMetadataDAOImpl implements AccountMetadataDAO { - - private static final Log log = LogFactory.getLog(AccountMetadataDAOImpl.class); - private static final String KEY = "METADATA_KEY"; - private static final String VALUE = "METADATA_VALUE"; - private static final String USER_ID = "USER_ID"; - - //Error messages - private static final String DB_CONNECTION_NULL_ERROR = "Database connection is null."; - private static final String ACCOUNT_ID_USER_ID_MISSING_ERROR = "Account Id or User Id is not provided"; - private static final String ACCOUNT_METADATA_MISSING_ERROR = "Metadata key or Metadata value is not provided"; - private static final String ERROR_WHILE_DELETING_METADATA = "Error occurred while deleting account metadata."; - - - AccountMetadataDBQueries sqlStatements; - - public AccountMetadataDAOImpl(AccountMetadataDBQueries sqlStatements) { - this.sqlStatements = sqlStatements; - } - - /** - * {@inheritDoc} - */ - @Override - public int storeAccountMetadata(Connection dbConnection, String accountId, String userId, - String metadataKey, String metadataValue) throws OpenBankingException { - - int noOfRows; - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error(ACCOUNT_ID_USER_ID_MISSING_ERROR); - throw new OpenBankingException(ACCOUNT_ID_USER_ID_MISSING_ERROR); - } - if (StringUtils.isBlank(metadataKey) || StringUtils.isBlank(metadataValue)) { - log.error(ACCOUNT_METADATA_MISSING_ERROR); - throw new OpenBankingException(ACCOUNT_METADATA_MISSING_ERROR); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - - try { - String storeAttributeSqlStatement = sqlStatements.getStoreAccountMetadataPreparedStatement(); - Savepoint savepoint = dbConnection.setSavepoint(); - log.debug("Storing account metadata data in the database for account-id " + accountId + " and " + - "user-id " + userId); - try (PreparedStatement prepStmt = dbConnection.prepareStatement(storeAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, userId); - prepStmt.setString(3, metadataKey); - prepStmt.setString(4, metadataValue); - prepStmt.setTimestamp(5, new Timestamp(new Date().getTime())); - - if (log.isDebugEnabled()) { - log.debug("Added data for the key " + metadataKey + " and value " + metadataValue + - " to be inserted to the database."); - } - noOfRows = prepStmt.executeUpdate(); - if (noOfRows > 0) { - if (log.isDebugEnabled()) { - log.debug("The query affected " + noOfRows + " rows."); - log.debug("Stored attributes for account-id" + accountId + " and user-id " + userId + - " in the database."); - } - dbConnection.commit(); - } else { - dbConnection.rollback(savepoint); - log.error("Error occurred while inserting account metadata data. Any changes occurred " + - "during the failed transaction are rolled back."); - throw new OpenBankingException("Error occurred while inserting account metadata " + - "data."); - } - } catch (SQLException e) { - dbConnection.rollback(savepoint); - log.error("Error occurred while inserting account metadata data.", e); - throw new OpenBankingException("Error occurred while inserting account metadata " + - "data.", e); - } - } catch (SQLException e) { - log.error("Error occurred while interacting with the database connection.", e); - throw new OpenBankingException("Error occurred while interacting with the database connection", e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return noOfRows; - } - - /** - * {@inheritDoc} - */ - @Override - public int updateAccountMetadata(Connection dbConnection, String accountId, String userId, - String metadataKey, String metadataValue) throws OpenBankingException { - - int noOfRows; - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error(ACCOUNT_ID_USER_ID_MISSING_ERROR); - throw new OpenBankingException(ACCOUNT_ID_USER_ID_MISSING_ERROR); - } - if (StringUtils.isBlank(metadataKey) || StringUtils.isBlank(metadataValue)) { - log.error(ACCOUNT_METADATA_MISSING_ERROR); - throw new OpenBankingException(ACCOUNT_METADATA_MISSING_ERROR); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - - try { - String storeAttributeSqlStatement = sqlStatements.getUpdateAccountMetadataPreparedStatement(); - Savepoint savepoint = dbConnection.setSavepoint(); - log.debug("Storing account metadata data in the database for account-id " + accountId + " and " + - "user-id " + userId); - try (PreparedStatement prepStmt = dbConnection.prepareStatement(storeAttributeSqlStatement)) { - prepStmt.setString(1, metadataValue); - prepStmt.setTimestamp(2, new Timestamp(new Date().getTime())); - prepStmt.setString(3, accountId); - prepStmt.setString(4, userId); - prepStmt.setString(5, metadataKey); - prepStmt.executeUpdate(); - if (log.isDebugEnabled()) { - log.debug("Added data for the key " + metadataKey + " and value" + metadataValue + - " to be updated in the database."); - } - noOfRows = prepStmt.executeUpdate(); - if (noOfRows > 0) { - if (log.isDebugEnabled()) { - log.debug("The query affected " + noOfRows + " rows."); - log.debug("Updated attributes for account-id" + accountId + " and user-id " + userId + - " in the database."); - } - } else { - log.info("No rows were affected in the transaction. No change was made to existing account " + - "metadata."); - } - dbConnection.commit(); - } catch (SQLException e) { - dbConnection.rollback(savepoint); - log.error("Error occurred while updating account metadata.", e); - throw new OpenBankingException("Error occurred while inserting account metadata.", e); - } - } catch (SQLException e) { - log.error("Error occurred while interacting with the database connection.", e); - throw new OpenBankingException("Error occurred while interacting with the database connection", e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return noOfRows; - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAccountMetadataMap(Connection dbConnection, String accountId, String userId) throws - OpenBankingException { - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error(ACCOUNT_ID_USER_ID_MISSING_ERROR); - throw new OpenBankingException(ACCOUNT_ID_USER_ID_MISSING_ERROR); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - HashMap attributesMap = new HashMap<>(); - final String retrieveAttributeSqlStatement = sqlStatements.getRetrieveAccountMetadataPreparedStatement(); - - if (log.isDebugEnabled()) { - log.debug("Retrieving account metadata for account-id " + accountId + " and user-id " + - userId); - } - try (PreparedStatement prepStmt = dbConnection.prepareStatement(retrieveAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, userId); - try (ResultSet rs = prepStmt.executeQuery()) { - while (rs.next()) { - attributesMap.put(rs.getString(KEY), rs.getString(VALUE)); - if (log.isDebugEnabled()) { - log.debug("Added attribute with key " + rs.getString(KEY) + " and value " + - rs.getString(VALUE) + "to the map."); - } - } - } catch (SQLException e) { - log.error("Error occurred while reading retrieved result set for account-id " + accountId + - "and user-id " + userId, e); - throw new OpenBankingException("Error occurred while reading retrieved result set for " + - "account-id " + accountId + " and user-id " + userId, e); - } - } catch (SQLException e) { - log.error("Error occurred while retrieving account metadata from database for account-id " + - accountId + " and user-id " + userId, e); - throw new OpenBankingException("Error occurred while retrieving account metadata " + - "from database for account-id " + accountId + " and user-id " + userId, e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return attributesMap; - } - - @Override - public Map getMetadataForAccountIdAndKey(Connection dbConnection, String accountId, String key) - throws OpenBankingException { - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(key)) { - log.error("AccountId or Key not found in the request"); - throw new OpenBankingException("AccountId and Key should be submitted in order to proceed."); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - HashMap attributesMap = new HashMap<>(); - final String retrieveAttributeSqlStatement = sqlStatements. - getRetrieveMetadataByAccountIdAndKeyPreparedStatement(); - - if (log.isDebugEnabled()) { - log.debug("Retrieving account metadata for account-id " + accountId + " and metadata-key " + - key); - } - try (PreparedStatement prepStmt = dbConnection.prepareStatement(retrieveAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, key); - try (ResultSet rs = prepStmt.executeQuery()) { - while (rs.next()) { - attributesMap.put(rs.getString(USER_ID), rs.getString(VALUE)); - if (log.isDebugEnabled()) { - log.debug("Added attribute with user-id " + rs.getString(USER_ID) + " and value " + - rs.getString(VALUE) + "to the map."); - } - } - } catch (SQLException e) { - log.error("Error occurred while reading retrieved result set for account-id " + accountId + - "and key " + key, e); - throw new OpenBankingException("Error occurred while reading retrieved result set for " + - "account-id " + accountId + " and key " + key, e); - } - } catch (SQLException e) { - log.error("Error occurred while retrieving account metadata from database for account-id " + - accountId + " and key " + key, e); - throw new OpenBankingException("Error occurred while retrieving account metadata " + - "from database for account-id " + accountId + " and key " + key, e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return attributesMap; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAccountMetadataByKey(Connection dbConnection, String accountId, String userId, String key) throws - OpenBankingException { - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId) || StringUtils.isBlank(key)) { - log.error("AccountId, UserId or Key not found in the request"); - throw new OpenBankingException("AccountId, UserId and Key should be submitted in order to " + - "proceed."); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - String attributeValue = null; - final String retrieveAttributeSqlStatement = sqlStatements. - getRetrieveAccountMetadataByKeyPreparedStatement(); - - if (log.isDebugEnabled()) { - log.debug("Retrieving account metadata for account-id " + accountId + " and user-id " + userId); - } - try (PreparedStatement prepStmt = dbConnection.prepareStatement(retrieveAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, userId); - prepStmt.setString(3, key); - try (ResultSet rs = prepStmt.executeQuery()) { - if (rs.next()) { - attributeValue = rs.getString(VALUE); - if (log.isDebugEnabled()) { - log.debug("Retrieved attribute with key " + key + " and value " + attributeValue); - } - } - dbConnection.commit(); - } catch (SQLException e) { - log.error("Error occurred while reading retrieved result set for account-id " + accountId + - " and user-id " + userId, e); - throw new OpenBankingException("Error occurred while reading retrieved result set for " + - "account-id " + accountId + " and user-id " + userId, e); - } - } catch (SQLException e) { - log.error("Error occurred while retrieving account metadata from database for account-id " + - accountId + " and user-id " + userId, e); - throw new OpenBankingException("Error occurred while retrieving account metadata " + - "from database for account-id " + accountId + " and user-id " + userId, e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return attributeValue; - } - - /** - * {@inheritDoc} - */ - @Override - public int deleteAccountMetadata(Connection dbConnection, String accountId, String userId) - throws OpenBankingException { - - int noOfRows; - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error(ACCOUNT_ID_USER_ID_MISSING_ERROR); - throw new OpenBankingException(ACCOUNT_ID_USER_ID_MISSING_ERROR); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - try { - String deleteAttributeSqlStatement = sqlStatements.getDeleteAccountMetadataPreparedStatement(); - dbConnection.setAutoCommit(false); - Savepoint savepoint = dbConnection.setSavepoint(); - - try (PreparedStatement prepStmt = dbConnection.prepareStatement(deleteAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, userId); - noOfRows = prepStmt.executeUpdate(); - if (noOfRows >= 0) { - dbConnection.commit(); - if (log.isDebugEnabled()) { - log.debug("Deleted " + noOfRows + " account metadata for account-id " + accountId + - "and user-id " + userId); - } - } else { - dbConnection.rollback(savepoint); - log.error(ERROR_WHILE_DELETING_METADATA + "Any changes occurred " + - "during the failed transaction are rolled back."); - throw new OpenBankingException(ERROR_WHILE_DELETING_METADATA); - } - } catch (SQLException e) { - dbConnection.rollback(savepoint); - log.error(ERROR_WHILE_DELETING_METADATA, e); - throw new OpenBankingException(ERROR_WHILE_DELETING_METADATA, e); - } - } catch (SQLException e) { - log.error("Error occurred while interacting with the database connection.", e); - throw new OpenBankingException("Error occurred while interacting with the database connection", e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return noOfRows; - } - - /** - * {@inheritDoc} - */ - @Override - public int deleteAccountMetadataByKey(Connection dbConnection, String accountId, String userId, String key) throws - OpenBankingException { - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId) || StringUtils.isBlank(key)) { - log.error("AccountId, UserId or Key not found in the request"); - throw new OpenBankingException("AccountId, UserId and Key should be submitted in order to " + - "proceed."); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - int noOfRows; - try { - String deleteAttributeSqlStatement = sqlStatements.getDeleteAccountMetadataByKeyPreparedStatement(); - Savepoint savepoint = dbConnection.setSavepoint(); - - try (PreparedStatement prepStmt = dbConnection.prepareStatement(deleteAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, userId); - prepStmt.setString(3, key); - noOfRows = prepStmt.executeUpdate(); - if (noOfRows >= 0) { - dbConnection.commit(); - if (log.isDebugEnabled()) { - log.debug("Deleted account metadata for account-id " + accountId + "and user-id " + - userId + "for the key " + key); - } - } else { - dbConnection.rollback(savepoint); - log.error(ERROR_WHILE_DELETING_METADATA + "Any changes occurred " + - "during the failed transaction are rolled back."); - throw new OpenBankingException(ERROR_WHILE_DELETING_METADATA); - } - } catch (SQLException e) { - dbConnection.rollback(savepoint); - log.error("Error occurred while deleting account metadata data.", e); - throw new OpenBankingException("Error occurred while deleting account metadata data.", e); - } - } catch (SQLException e) { - log.error("Error occurred while interacting with the database connection.", e); - throw new OpenBankingException("Error occurred while interacting with the database connection", e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return noOfRows; - } - - @Override - public int deleteAccountMetadataByKeyForAllUsers(Connection dbConnection, String accountId, String key) throws - OpenBankingException { - - int noOfRows; - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(key)) { - log.error("AccountId or Key not found in the request"); - throw new OpenBankingException("AccountId and Key should be submitted in order to " + - "proceed."); - } - if (dbConnection == null) { - log.error(DB_CONNECTION_NULL_ERROR); - throw new OpenBankingException(DB_CONNECTION_NULL_ERROR); - } - try { - String deleteAttributeSqlStatement = sqlStatements. - getDeleteAccountMetadataByKeyForAllUsersPreparedStatement(); - Savepoint savepoint = dbConnection.setSavepoint(); - - try (PreparedStatement prepStmt = dbConnection.prepareStatement(deleteAttributeSqlStatement)) { - prepStmt.setString(1, accountId); - prepStmt.setString(2, key); - noOfRows = prepStmt.executeUpdate(); - if (noOfRows >= 0) { - dbConnection.commit(); - if (log.isDebugEnabled()) { - log.debug("Deleted account metadata for account-id " + accountId + "for the key " + key); - } - } else { - dbConnection.rollback(savepoint); - log.error(ERROR_WHILE_DELETING_METADATA + "Any changes occurred " + - "during the failed transaction are rolled back."); - throw new OpenBankingException(ERROR_WHILE_DELETING_METADATA); - } - } catch (SQLException e) { - dbConnection.rollback(savepoint); - log.error("Error occurred while deleting account metadata data.", e); - throw new OpenBankingException("Error occurred while deleting account metadata data.", e); - } - } catch (SQLException e) { - log.error("Error occurred while interacting with the database connection.", e); - throw new OpenBankingException("Error occurred while interacting with the database connection", e); - } finally { - DatabaseUtil.closeConnection(dbConnection); - } - return noOfRows; - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/queries/AccountMetadataDBQueries.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/queries/AccountMetadataDBQueries.java deleted file mode 100644 index 56cde3ac..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/queries/AccountMetadataDBQueries.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.dao.queries; - -/** - * AccountMetadataDBQueries - * Contains the queries used by the AccountMetadataDAOImpl. - */ -public interface AccountMetadataDBQueries { - - /** - * Returns the query to store account metadata. - * - * @return String - */ - String getStoreAccountMetadataPreparedStatement(); - - /** - * Returns the query to update account metadata. - * - * @return String - */ - String getUpdateAccountMetadataPreparedStatement(); - - /** - * Returns the query to retrieve account metadata. - * - * @return String - */ - String getRetrieveAccountMetadataPreparedStatement(); - - /** - * Returns the query to retrieve user-ids and metadata values when - * account-id and metadata-key is given. - * - * @return String - */ - String getRetrieveMetadataByAccountIdAndKeyPreparedStatement(); - - /** - * Returns the query to retrieve the account metadata by key. - * - * @return String - */ - String getRetrieveAccountMetadataByKeyPreparedStatement(); - - /** - * Returns the query to delete the account metadata. - * - * @return String - */ - String getDeleteAccountMetadataPreparedStatement(); - - /** - * Returns the query to delete the account metadata by key. - * - * @return String - */ - String getDeleteAccountMetadataByKeyPreparedStatement(); - - /** - * Returns the query to delete the account metadata by key for al users. - * - * @return String - */ - String getDeleteAccountMetadataByKeyForAllUsersPreparedStatement(); -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/queries/AccountMetadataDBQueriesMySQLImpl.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/queries/AccountMetadataDBQueriesMySQLImpl.java deleted file mode 100644 index e82bef48..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/queries/AccountMetadataDBQueriesMySQLImpl.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.dao.queries; - -/** - * AccountMetadataDBQueriesMySQLImpl - * Contains the MySQL queries used by the AccountMetadataDAOImpl. - */ -public class AccountMetadataDBQueriesMySQLImpl implements AccountMetadataDBQueries { - - /** - * {@inheritDoc} - */ - public String getStoreAccountMetadataPreparedStatement() { - - return "INSERT INTO OB_ACCOUNT_METADATA (ACCOUNT_ID, USER_ID, METADATA_KEY, METADATA_VALUE, " + - "LAST_UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?)"; - } - - /** - * {@inheritDoc} - */ - public String getUpdateAccountMetadataPreparedStatement() { - - return "UPDATE OB_ACCOUNT_METADATA SET METADATA_VALUE = ?, LAST_UPDATED_TIMESTAMP = ? WHERE ACCOUNT_ID = ? " + - "AND USER_ID = ? AND METADATA_KEY = ?"; - } - - /** - * {@inheritDoc} - */ - public String getRetrieveAccountMetadataPreparedStatement() { - - return "SELECT METADATA_KEY, METADATA_VALUE FROM OB_ACCOUNT_METADATA WHERE ACCOUNT_ID = ? AND USER_ID = ?"; - - } - - /** - * {@inheritDoc} - */ - public String getRetrieveMetadataByAccountIdAndKeyPreparedStatement() { - - return "SELECT USER_ID, METADATA_VALUE FROM OB_ACCOUNT_METADATA WHERE ACCOUNT_ID = ? AND METADATA_KEY = ?"; - - } - - /** - * {@inheritDoc} - */ - public String getRetrieveAccountMetadataByKeyPreparedStatement() { - - return "SELECT METADATA_VALUE FROM OB_ACCOUNT_METADATA WHERE ACCOUNT_ID = ? AND USER_ID = ? AND " + - "METADATA_KEY = ?"; - - } - - /** - * {@inheritDoc} - */ - public String getDeleteAccountMetadataPreparedStatement() { - - return "DELETE FROM OB_ACCOUNT_METADATA WHERE ACCOUNT_ID = ? AND USER_ID = ?"; - - } - - /** - * {@inheritDoc} - */ - public String getDeleteAccountMetadataByKeyPreparedStatement() { - - return "DELETE FROM OB_ACCOUNT_METADATA WHERE ACCOUNT_ID = ? AND USER_ID = ? AND METADATA_KEY = ?"; - - } - - /** - * {@inheritDoc} - */ - public String getDeleteAccountMetadataByKeyForAllUsersPreparedStatement() { - - return "DELETE FROM OB_ACCOUNT_METADATA WHERE ACCOUNT_ID = ? AND METADATA_KEY = ?"; - - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/internal/AccountMetadataDataHolder.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/internal/AccountMetadataDataHolder.java deleted file mode 100644 index 5d25bd7a..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/internal/AccountMetadataDataHolder.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.account.metadata.service.internal; - -import org.wso2.carbon.user.core.service.RealmService; - -/** - * AccountMetadata Data Holder. - */ -public class AccountMetadataDataHolder { - - private static AccountMetadataDataHolder instance = new AccountMetadataDataHolder(); - - private RealmService realmService; - - private AccountMetadataDataHolder() { - - } - - public static AccountMetadataDataHolder getInstance() { - - return instance; - } - - public RealmService getRealmService() { - - if (realmService == null) { - throw new RuntimeException("Realm Service is not available. Component did not start correctly."); - } - return realmService; - } - - void setRealmService(RealmService realmService) { - - this.realmService = realmService; - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/internal/AccountMetadataServiceComponent.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/internal/AccountMetadataServiceComponent.java deleted file mode 100644 index 9fe71917..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/internal/AccountMetadataServiceComponent.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.account.metadata.service.internal; - -import com.wso2.openbanking.accelerator.account.metadata.service.service.AccountMetadataService; -import com.wso2.openbanking.accelerator.account.metadata.service.service.AccountMetadataServiceImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.user.core.service.RealmService; - -/** - * AccountMetadataService component. - */ -@Component( - name = "open.banking.account.metadata.service.component", - immediate = true -) -public class AccountMetadataServiceComponent { - - private static final Log log = LogFactory.getLog(AccountMetadataServiceComponent.class); - - public static RealmService getRealmService() { - return (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(RealmService.class); - } - - @Reference( - name = "realm.service", - service = RealmService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRealmService" - ) - protected void setRealmService(RealmService realmService) { - - log.debug("Setting the Realm Service"); - AccountMetadataDataHolder.getInstance().setRealmService(realmService); - } - - @Activate - protected void activate(ComponentContext ctxt) { - - try { - AccountMetadataService accountMetadataService = AccountMetadataServiceImpl.getInstance(); - ctxt.getBundleContext().registerService(AccountMetadataServiceImpl.class.getName(), - accountMetadataService, null); - log.debug("AccountMetadataService bundle is activated"); - - } catch (Throwable e) { - log.error("AccountMetadataService bundle activation Failed", e); - } - } - - @Deactivate - protected void deactivate(ComponentContext ctxt) { - - log.debug("AccountMetadataService bundle is deactivated"); - } - - protected void unsetRealmService(RealmService realmService) { - - log.debug("UnSetting the Realm Service"); - AccountMetadataDataHolder.getInstance().setRealmService(null); - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataService.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataService.java deleted file mode 100644 index 2350e26b..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataService.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.service; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -import java.util.Map; - -/** - * Account Metadata Service. - *

- * Handles the calls for persisting and retrieving metadata related to accounts. - */ -public interface AccountMetadataService { - - - /** - * Add or update multiple account metadata. - * If the key already exists for the account-id and user-id combination, the value be updated. - * - * @param accountId - Account ID - * @param userId - User ID - * @param accountMetadataMap - Map containing metadata key and value pairs - * @return number of records inserted/updated - * @throws OpenBankingException - OpenBankingException - */ - int addOrUpdateAccountMetadata(String accountId, String userId, Map accountMetadataMap) throws - OpenBankingException; - - /** - * Add or update multiple account metadata for account-id where the user id is N/A. - * If the key already exists for the account-id, the value be updated. - * - * @param accountId - Account ID - * @param accountMetadataMap - Map containing metadata key and value pairs - * @return number of records inserted/updated - * @throws OpenBankingException - OpenBankingException - */ - int addOrUpdateAccountMetadata(String accountId, Map accountMetadataMap) throws - OpenBankingException; - - /** - * Add or update account metadata. - * If the key already exists for the account-id and user-id combination, the value be updated. - * - * @param accountId - Account ID - * @param userId - User ID - * @param metadataKey - Metadata Key - * @param metadataValue - Metadata Value - * @return number of records inserted/updated - * @throws OpenBankingException - OpenBankingException - */ - int addOrUpdateAccountMetadata(String accountId, String userId, String metadataKey, String metadataValue) throws - OpenBankingException; - - /** - * Add or update metadata for account-id where the user id is N/A. - * If the key already exists for the account-id, the value be updated. - * - * @param accountId - Account ID - * @param metadataKey - Metadata Key - * @param metadataValue - Metadata Value - * @return number of records updated - * @throws OpenBankingException - OpenBankingException - */ - int addOrUpdateAccountMetadata(String accountId, String metadataKey, String metadataValue) throws - OpenBankingException; - - /** - * Get all metadata for an account-id user-id combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @return Map of account metadata - * @throws OpenBankingException - OpenBankingException - */ - Map getAccountMetadataMap(String accountId, String userId) throws - OpenBankingException; - - /** - * Get all metadata affecting the account-id regardless of the user-id. - * - * @param accountId - Account ID - * @return Map of account metadata - * @throws OpenBankingException - OpenBankingException - */ - Map getAccountMetadataMap(String accountId) throws OpenBankingException; - - /** - * Get users and metadata values for an account-id and key combination. - * - * @param accountId - Account ID - * @param key - Metadata key - * @return Map of users and metadata values - * @throws OpenBankingException - OpenBankingException - */ - Map getUserMetadataForAccountIdAndKey(String accountId, String key) throws - OpenBankingException; - - /** - * Get metadata value for an account-id user-id and key combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @param key - Metadata key - * @return Metadata value - * @throws OpenBankingException - OpenBankingException - */ - String getAccountMetadataByKey(String accountId, String userId, String key) throws - OpenBankingException; - - /** - * Given the key, get metadata value of the account-id where the user-id is N/A. - * - * @param accountId - Account ID - * @param key - Metadata key - * @return Metadata value - * @throws OpenBankingException - OpenBankingException - */ - String getAccountMetadataByKey(String accountId, String key) throws OpenBankingException; - - /** - * Remove all metadata for an account-id user-id combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @return number of affected rows - * @throws OpenBankingException - OpenBankingException - */ - int removeAccountMetadata(String accountId, String userId) throws OpenBankingException; - - /** - * Remove all metadata for an account-id where the user-id is N/A. - * - * @param accountId - Account ID - * @return number of affected rows - * @throws OpenBankingException - OpenBankingException - */ - int removeAccountMetadata(String accountId) throws OpenBankingException; - - /** - * Remove metadata for an account-id user-id and key combination. - * - * @param accountId - Account ID - * @param userId - User ID - * @param key - Metadata key - * @return number of affected rows - * @throws OpenBankingException - OpenBankingException - */ - int removeAccountMetadataByKey(String accountId, String userId, String key) throws - OpenBankingException; - - /** - * Remove metadata for an account-id and key combination for all user-ids. - * - * @param accountId - Account ID - * @param key - Metadata key - * @return number of affected rows - * @throws OpenBankingException - OpenBankingException - */ - int removeAccountMetadataByKeyForAllUsers(String accountId, String key) throws - OpenBankingException; - - /** - * Given the key, remove metadata affecting the account-id where the user-id is N/A. - * - * @param accountId - Account ID - * @param key - Metadata key - * @return number of affected rows - * @throws OpenBankingException - OpenBankingException - */ - int removeAccountMetadataByKey(String accountId, String key) throws OpenBankingException; - -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataServiceImpl.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataServiceImpl.java deleted file mode 100644 index 72db3fe5..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/main/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataServiceImpl.java +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.service; - -import com.wso2.openbanking.accelerator.account.metadata.service.dao.AccountMetadataDAO; -import com.wso2.openbanking.accelerator.account.metadata.service.dao.AccountMetadataDAOImpl; -import com.wso2.openbanking.accelerator.account.metadata.service.dao.queries.AccountMetadataDBQueriesMySQLImpl; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.util.Map; - -/** - * Implementation of AccountMetadataService. - */ -public class AccountMetadataServiceImpl implements AccountMetadataService { - - private static final Log log = LogFactory.getLog(AccountMetadataServiceImpl.class); - private static final String NOT_APPLICABLE = "N/A"; - private static AccountMetadataServiceImpl instance = null; - AccountMetadataDAO accountMetadataDAO = new AccountMetadataDAOImpl( - new AccountMetadataDBQueriesMySQLImpl()); - - // private constructor - private AccountMetadataServiceImpl() { - } - - /** - * @return AccountMetadataServiceImpl instance - */ - public static synchronized AccountMetadataServiceImpl getInstance() { - - if (instance == null) { - instance = new AccountMetadataServiceImpl(); - } - return instance; - } - - /** - * {@inheritDoc} - */ - @Override - public int addOrUpdateAccountMetadata(String accountId, String userId, Map accountMetadataMap) - throws OpenBankingException { - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error("Account Id or User Id is not provided."); - throw new OpenBankingException("Account Id or User Id is not provided."); - } - if (accountMetadataMap == null || accountMetadataMap.isEmpty()) { - log.error("Account metadata is not present."); - throw new OpenBankingException("Account metadata is not present"); - } - int noOfRecords = 0; - // Add all entries in the accountMetadataMap to the database - for (Map.Entry accountMetadata : accountMetadataMap.entrySet()) { - addOrUpdateAccountMetadata(accountId, userId, accountMetadata.getKey(), accountMetadata.getValue()); - noOfRecords++; - } - return noOfRecords; - } - - @Override - public int addOrUpdateAccountMetadata(String accountId, Map accountMetadataMap) - throws OpenBankingException { - return addOrUpdateAccountMetadata(accountId, NOT_APPLICABLE, accountMetadataMap); - } - - /** - * {@inheritDoc} - */ - @Override - public int addOrUpdateAccountMetadata(String accountId, String userId, String metadataKey, String metadataValue) - throws OpenBankingException { - - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error("Account Id or User Id is not provided."); - throw new OpenBankingException("Account Id or User Id is not provided."); - } - if (StringUtils.isBlank(metadataKey) || StringUtils.isBlank(metadataValue)) { - log.error("Account metadata is not present."); - throw new OpenBankingException("Account metadata is not present"); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - // Check if the record is already present in the database. - if (getAccountMetadataByKey(accountId, userId, metadataKey) == null) { - // Add the record - return accountMetadataDAO.storeAccountMetadata(dbConnection, accountId, userId, metadataKey, metadataValue); - } else { - // Update the record - return accountMetadataDAO.updateAccountMetadata(dbConnection, accountId, userId, metadataKey, - metadataValue); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int addOrUpdateAccountMetadata(String accountId, String metadataKey, String metadataValue) - throws OpenBankingException { - return addOrUpdateAccountMetadata(accountId, NOT_APPLICABLE, metadataKey, metadataValue); - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAccountMetadataMap(String accountId, String userId) - throws OpenBankingException { - if (StringUtils.isBlank(userId) || StringUtils.isBlank(accountId)) { - log.error("Account Id or User Id is not provided."); - throw new OpenBankingException("Account Id or User Id is not provided."); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - return accountMetadataDAO.getAccountMetadataMap(dbConnection, accountId, userId); - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAccountMetadataMap(String accountId) throws OpenBankingException { - return getAccountMetadataMap(accountId, NOT_APPLICABLE); - } - - /** - * {@inheritDoc} - */ - @Override - public Map getUserMetadataForAccountIdAndKey(String accountId, String key) - throws OpenBankingException { - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(key)) { - log.error("Account Id or Key is not provided."); - throw new OpenBankingException("Account Id or Key is not provided."); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - return accountMetadataDAO.getMetadataForAccountIdAndKey(dbConnection, accountId, key); - } - - /** - * {@inheritDoc} - */ - @Override - public String getAccountMetadataByKey(String accountId, String userId, String key) - throws OpenBankingException { - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId) || StringUtils.isBlank(key)) { - log.error("Account Id, User Id or Key is not provided."); - throw new OpenBankingException("Account Id, User Id or Key is not provided."); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - return accountMetadataDAO.getAccountMetadataByKey(dbConnection, accountId, userId, key); - } - - /** - * {@inheritDoc} - */ - @Override - public String getAccountMetadataByKey(String accountId, String key) throws OpenBankingException { - return getAccountMetadataByKey(accountId, NOT_APPLICABLE, key); - } - - /** - * {@inheritDoc} - */ - @Override - public int removeAccountMetadata(String accountId, String userId) throws OpenBankingException { - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId)) { - log.error("Account Id or User Id is not provided."); - throw new OpenBankingException("Account Id or User Id is not provided."); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - return accountMetadataDAO.deleteAccountMetadata(dbConnection, accountId, userId); - } - - /** - * {@inheritDoc} - */ - @Override - public int removeAccountMetadata(String accountId) throws OpenBankingException { - return removeAccountMetadata(accountId, NOT_APPLICABLE); - } - - /** - * {@inheritDoc} - */ - @Override - public int removeAccountMetadataByKey(String accountId, String userId, String key) throws - OpenBankingException { - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(userId) || StringUtils.isBlank(key)) { - log.error("Account Id, User Id or Key is not provided."); - throw new OpenBankingException("Account Id, User Id or Key is not provided."); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - return accountMetadataDAO.deleteAccountMetadataByKey(dbConnection, accountId, userId, key); - } - - /** - * {@inheritDoc} - */ - @Override - public int removeAccountMetadataByKeyForAllUsers(String accountId, String key) throws - OpenBankingException { - if (StringUtils.isBlank(accountId) || StringUtils.isBlank(key)) { - log.error("Account Id or Key is not provided."); - throw new OpenBankingException("Account Id or Key is not provided."); - } - Connection dbConnection = DatabaseUtil.getDBConnection(); - return accountMetadataDAO.deleteAccountMetadataByKeyForAllUsers(dbConnection, accountId, key); - } - - /** - * {@inheritDoc} - */ - @Override - public int removeAccountMetadataByKey(String accountId, String key) throws OpenBankingException { - return removeAccountMetadataByKey(accountId, NOT_APPLICABLE, key); - } - -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAOTests.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAOTests.java deleted file mode 100644 index a4a0d2e8..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/dao/AccountMetadataDAOTests.java +++ /dev/null @@ -1,315 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.dao; - -import com.wso2.openbanking.accelerator.account.metadata.service.dao.queries.AccountMetadataDBQueriesMySQLImpl; -import com.wso2.openbanking.accelerator.account.metadata.service.util.AccountMetadataDAOTestData; -import com.wso2.openbanking.accelerator.account.metadata.service.util.DAOUtils; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.util.Map; - -/** - * Implementation of AccountMetadataDAOTests class. - */ -public class AccountMetadataDAOTests { - - private static final String DB_NAME = "OPENBANKING_DB"; - private AccountMetadataDAO accountMetadataDAO; - - @BeforeClass - public void initTest() throws Exception { - - DAOUtils.initializeDataSource(DB_NAME, DAOUtils.getFilePath("dbScripts/h2.sql")); - accountMetadataDAO = new AccountMetadataDAOImpl(new AccountMetadataDBQueriesMySQLImpl()); - } - - @DataProvider(name = "accountMetadataDataProvider") - public Object[][] accountMetadataData() { - return AccountMetadataDAOTestData.DataProviders.METADATA_DATA_HOLDER; - } - - @DataProvider(name = "getAccountMetadataDataProvider") - public Object[][] getAccountMetadataData() { - return AccountMetadataDAOTestData.DataProviders.GET_METADATA_DATA_HOLDER; - } - - @Test - public void testStoreAccountMetadata() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - Map metadataMap = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ATTRIBUTES_MAP; - int affectedRows = 0; - - for (Map.Entry entry : metadataMap.entrySet()) { - String metadataKey = entry.getKey(); - String metadataValue = entry.getValue(); - Connection dbConnection = DAOUtils.getConnection(DB_NAME); - affectedRows += accountMetadataDAO.storeAccountMetadata(dbConnection, accountId, userId, metadataKey, - metadataValue); - - } - Assert.assertEquals(affectedRows, 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testStoreAccountMetadataNullAccountIdAndUserIdError() throws Exception { - - String key = AccountMetadataDAOTestData.SAMPLE_KEY; - String value = AccountMetadataDAOTestData.SAMPLE_VALUE; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.storeAccountMetadata(dbConnection, null, null, key, value); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testStoreAccountMetadataEmptyMetadataMapError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.storeAccountMetadata(dbConnection, accountId, userId, "", ""); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testStoreAccountMetadataNullMetadataMapError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.storeAccountMetadata(dbConnection, accountId, userId, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testStoreAccountMetadataNullDBConnectionError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - String key = AccountMetadataDAOTestData.SAMPLE_KEY; - String value = AccountMetadataDAOTestData.SAMPLE_VALUE; - accountMetadataDAO.storeAccountMetadata(null, accountId, userId, key, value); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testUpdateAccountMetadataNullAccountIdAndUserIdError() throws Exception { - - String key = AccountMetadataDAOTestData.SAMPLE_KEY; - String value = AccountMetadataDAOTestData.SAMPLE_VALUE; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.updateAccountMetadata(dbConnection, null, null, key, value); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testUpdateAccountMetadataEmptyMetadataMapError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.updateAccountMetadata(dbConnection, accountId, userId, "", ""); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testUpdateAccountMetadataNullMetadataMapError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.updateAccountMetadata(dbConnection, accountId, userId, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testUpdateAccountMetadataNullDBConnectionError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - String key = AccountMetadataDAOTestData.SAMPLE_KEY; - String value = AccountMetadataDAOTestData.SAMPLE_VALUE; - accountMetadataDAO.updateAccountMetadata(null, accountId, userId, key, value); - } - - @Test(dataProvider = "getAccountMetadataDataProvider", dependsOnMethods = {"testStoreAccountMetadata"}, - priority = 1) - public void testGetAccountMetadata(String accountId, String userId) throws Exception { - - Map metadataMap; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - metadataMap = accountMetadataDAO.getAccountMetadataMap(dbConnection, accountId, userId); - } - Assert.assertEquals(metadataMap.size(), 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testGetAccountMetadataNullAccountIdAndUserIdError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.getAccountMetadataMap(dbConnection, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "getAccountMetadataDataProvider", - dependsOnMethods = {"testStoreAccountMetadata"}, - priority = 1) - public void testGetAccountMetadataNullDBConnectionError(String accountId, String userId) throws Exception { - accountMetadataDAO.getAccountMetadataMap(null, accountId, userId); - } - - @Test(dataProvider = "accountMetadataDataProvider", dependsOnMethods = {"testStoreAccountMetadata"}, - priority = 1) - public void testGetAccountMetadataByKey(String accountId, String userId, String key, String value) - throws Exception { - - String metadataValue; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - metadataValue = accountMetadataDAO.getAccountMetadataByKey(dbConnection, accountId, userId, key); - } - Assert.assertEquals(metadataValue, value); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testGetAccountMetadataByKeyNullAccountIdUserIdAndKeyError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.getAccountMetadataByKey(dbConnection, null, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testGetAccountMetadataByKeyNullDBConnectionError(String accountId, String userId, String key, - String value) throws Exception { - accountMetadataDAO.getAccountMetadataByKey(null, accountId, userId, key); - } - - @Test(dataProvider = "accountMetadataDataProvider", dependsOnMethods = {"testStoreAccountMetadata"}, - priority = 2) - public void testDeleteAccountMetadataByKey(String accountId, String userId, String key, String value) - throws Exception { - - int affectedRows; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - affectedRows = accountMetadataDAO.deleteAccountMetadataByKey(dbConnection, accountId, userId, key); - } - Assert.assertEquals(affectedRows, 1); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataByKeyNullAccountIdUserIdAndKeyError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.deleteAccountMetadataByKey(dbConnection, null, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testDeleteAccountMetadataByKeyNullDBConnectionError(String accountId, String userId, String key, - String value) throws Exception { - - accountMetadataDAO.deleteAccountMetadataByKey(null, accountId, userId, key); - } - - @Test(dependsOnMethods = {"testStoreAccountMetadata", "testDeleteAccountMetadataByKey"}, priority = 2) - public void testDeleteAccountMetadata() throws Exception { - - int affectedRows; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - affectedRows = accountMetadataDAO.deleteAccountMetadata(dbConnection, accountId, userId); - } - Assert.assertEquals(affectedRows, 3); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataNullAccountIdAndUserIdError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.deleteAccountMetadata(dbConnection, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataNullDBConnection() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - accountMetadataDAO.deleteAccountMetadata(null, accountId, userId); - } - - @Test - public void testStoreAccountMetadataForSameAccount() throws Exception { - int affectedRows = 0; - Map userAttributeAMp = AccountMetadataDAOTestData.SAMPLE_USER_ID_ATTRIBUTE_VALUE_MAP; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String attributeKey = AccountMetadataDAOTestData.SAMPLE_KEY; - - for (Map.Entry entry : userAttributeAMp.entrySet()) { - Connection dbConnection = DAOUtils.getConnection(DB_NAME); - String userId = entry.getKey(); - String attributeValue = entry.getValue(); - affectedRows += accountMetadataDAO.storeAccountMetadata(dbConnection, accountId, userId, attributeKey, - attributeValue); - } - Assert.assertEquals(affectedRows, 4); - } - - @Test(dependsOnMethods = {"testStoreAccountMetadataForSameAccount"}, priority = 2) - public void testDeleteAccountMetadataByKeyForAllUsers() throws Exception { - - int affectedRows; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String key = AccountMetadataDAOTestData.SAMPLE_KEY; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - affectedRows = accountMetadataDAO.deleteAccountMetadataByKeyForAllUsers(dbConnection, accountId, key); - } - Assert.assertEquals(affectedRows, 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataByKeyForAllUsersNullAccountIdAndKeyError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - accountMetadataDAO.deleteAccountMetadataByKeyForAllUsers(dbConnection, null, null); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataByKeyForAllUsersNullDBConnection() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - accountMetadataDAO.deleteAccountMetadataByKeyForAllUsers(null, accountId, userId); - } - -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataServiceTests.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataServiceTests.java deleted file mode 100644 index 330664d7..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/service/AccountMetadataServiceTests.java +++ /dev/null @@ -1,610 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.service; - -import com.wso2.openbanking.accelerator.account.metadata.service.util.AccountMetadataDAOTestData; -import com.wso2.openbanking.accelerator.account.metadata.service.util.DAOUtils; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * Implementation of AccountMetadataServiceTests class. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({DatabaseUtil.class}) -public class AccountMetadataServiceTests extends PowerMockTestCase { - - private static final String DB_NAME = "OPENBANKING_DB"; - private AccountMetadataService accountMetadataService; - - @BeforeClass - public void initTest() throws Exception { - DAOUtils.initializeDataSource(DB_NAME, DAOUtils.getFilePath("dbScripts/h2.sql")); - accountMetadataService = AccountMetadataServiceImpl.getInstance(); - } - - @DataProvider(name = "accountMetadataDataProvider") - public Object[][] accountMetadataData() { - return AccountMetadataDAOTestData.DataProviders.METADATA_DATA_HOLDER; - } - - @DataProvider(name = "globalAccountMetadataDataProvider") - public Object[][] globalAccountMetadataData() { - return AccountMetadataDAOTestData.DataProviders.GLOBAL_METADATA_DATA_HOLDER; - } - - @DataProvider(name = "getAccountMetadataDataProvider") - public Object[][] getAccountMetadataData() { - return AccountMetadataDAOTestData.DataProviders.GET_METADATA_DATA_HOLDER; - } - - @Test - public void testAddOrUpdateAccountMetadata() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - Map metadataMap = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ATTRIBUTES_MAP; - int noOfEntries; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - noOfEntries = accountMetadataService.addOrUpdateAccountMetadata(accountId, userId, metadataMap); - - } - Assert.assertEquals(noOfEntries, 4); - } - - @Test(dependsOnMethods = {"testAddOrUpdateAccountMetadata"}, priority = 1) - public void testUpdateExistingAccountMetadata() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - String updateMetadataKey = "secondary-account-privilege"; - String updateMetadataValue = "active"; - int noOfEntries; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - noOfEntries = accountMetadataService.addOrUpdateAccountMetadata(accountId, userId, updateMetadataKey, - updateMetadataValue); - - } - Assert.assertEquals(noOfEntries, 1); - } - - @Test - public void testAddOrUpdateAccountMetadataForSameAccount() throws Exception { - int noOfEntries = 0; - Map userAttributeAMp = AccountMetadataDAOTestData.SAMPLE_USER_ID_ATTRIBUTE_VALUE_MAP; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String attributeKey = AccountMetadataDAOTestData.SAMPLE_KEY; - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - for (Map.Entry entry : userAttributeAMp.entrySet()) { - String userId = entry.getKey(); - String attributeValue = entry.getValue(); - Map metadataMap = Collections.singletonMap(attributeKey, attributeValue); - noOfEntries += accountMetadataService.addOrUpdateAccountMetadata(accountId, userId, - metadataMap); - } - } - Assert.assertEquals(noOfEntries, 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testAddOrUpdateAccountMetadataNullAccountIdError() throws Exception { - - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - Map metadataMap = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ATTRIBUTES_MAP; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.addOrUpdateAccountMetadata(null, userId, metadataMap); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testAddOrUpdateAccountMetadataNullMetadataError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.addOrUpdateAccountMetadata(accountId, userId, ""); - - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testAddOrUpdateAccountMetadataEmptyMetadataError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.addOrUpdateAccountMetadata(accountId, userId, new HashMap<>()); - - } - } - - @Test - public void testAddOrUpdateGlobalAccountMetadataMap() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - Map metadataMap = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ATTRIBUTES_MAP; - int noOfEntries; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - noOfEntries = accountMetadataService.addOrUpdateAccountMetadata(accountId, metadataMap); - - } - Assert.assertEquals(noOfEntries, 4); - } - - @Test(dependsOnMethods = {"testAddOrUpdateGlobalAccountMetadataMap"}) - public void testUpdateGlobalAccountMetadata() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String updateMetadataKey = "secondary-account-privilege"; - String updateMetadataValue = "active"; int noOfEntries; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - noOfEntries = accountMetadataService.addOrUpdateAccountMetadata(accountId, updateMetadataKey, - updateMetadataValue); - - } - Assert.assertEquals(noOfEntries, 1); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testAddOrUpdateGlobalAccountMetadataNullAccountIdError() throws Exception { - - Map metadataMap = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ATTRIBUTES_MAP; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.addOrUpdateAccountMetadata(null, metadataMap); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testAddOrUpdateGlobalAccountMetadataNullMetadataError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.addOrUpdateAccountMetadata(accountId, null); - - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testAddOrUpdateGlobalAccountMetadataEmptyMetadataError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.addOrUpdateAccountMetadata(accountId, new HashMap<>()); - - } - } - - @Test(dataProvider = "getAccountMetadataDataProvider", dependsOnMethods = {"testAddOrUpdateAccountMetadata"}, - priority = 1) - public void testGetAccountMetadataMap(String accountId, String userId) throws Exception { - - Map metadataMap; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - metadataMap = accountMetadataService.getAccountMetadataMap(accountId, userId); - - } - Assert.assertEquals(metadataMap.size(), 4); - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "getAccountMetadataDataProvider") - public void testGetAccountMetadataMapNullAccountIdError(String accountId, String userId) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataMap(null, userId); - - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "getAccountMetadataDataProvider") - public void testGetAccountMetadataMapNullUserIdError(String accountId, String userId) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataMap(accountId, null); - - } - } - - @Test(dependsOnMethods = {"testAddOrUpdateGlobalAccountMetadataMap"}, priority = 1) - public void testGetGlobalAccountMetadataMap() throws Exception { - - Map metadataMap; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - metadataMap = accountMetadataService.getAccountMetadataMap(accountId); - - } - Assert.assertEquals(metadataMap.size(), 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testGetGlobalAccountMetadataMapNullAccountIdError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataMap(null); - - } - } - - @Test(dependsOnMethods = {"testAddOrUpdateAccountMetadataForSameAccount"}, priority = 1) - public void testGetUserAttributesForAccountIdAndKey() throws Exception { - - Map metadataMap; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String attributeKey = AccountMetadataDAOTestData.SAMPLE_KEY; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - metadataMap = accountMetadataService.getUserMetadataForAccountIdAndKey(accountId, attributeKey); - - } - Assert.assertEquals(metadataMap.size(), 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testGetUserAttributesForAccountIdAndKeyNullAccountIdError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getUserMetadataForAccountIdAndKey(null, - AccountMetadataDAOTestData.SAMPLE_KEY); - - } - } - - @Test(dataProvider = "accountMetadataDataProvider", dependsOnMethods = {"testAddOrUpdateAccountMetadata"}, - priority = 1) - public void testGetAccountMetadataByKey(String accountId, String userId, String key, String value) - throws Exception { - - String metadataValue; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - metadataValue = accountMetadataService.getAccountMetadataByKey(accountId, userId, key); - } - Assert.assertEquals(metadataValue, value); - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testGetAccountMetadataByKeyNullAccountIdError(String accountId, String userId, String key, String value) - throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataByKey(null, userId, key); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testGetAccountMetadataByKeyNullUserIdError(String accountId, String userId, String key, String value) - throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataByKey(accountId, null, key); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testGetAccountMetadataByKeyNullKeyError(String accountId, String userId, String key, String value) - throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataByKey(accountId, userId, null); - } - } - - @Test(dataProvider = "globalAccountMetadataDataProvider", dependsOnMethods = - {"testAddOrUpdateGlobalAccountMetadataMap"}, - priority = 1) - public void testGetGlobalAccountMetadataByKey(String accountId, String userId, String key, String value) - throws Exception { - - String metadataValue; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - metadataValue = accountMetadataService.getAccountMetadataByKey(accountId, key); - } - Assert.assertEquals(metadataValue, value); - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "globalAccountMetadataDataProvider") - public void testGetGlobalAccountMetadataByKeyNullAccountIdError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataByKey(null, key); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "globalAccountMetadataDataProvider") - public void testGetGlobalAccountMetadataByKeyNullKeyError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.getAccountMetadataByKey(accountId, null); - } - } - - @Test(dataProvider = "accountMetadataDataProvider", dependsOnMethods = {"testAddOrUpdateAccountMetadata"}, - priority = 2) - public void testDeleteAccountMetadataByKey(String accountId, String userId, String key, String value) - throws Exception { - - int affectedRows; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - affectedRows = accountMetadataService.removeAccountMetadataByKey(accountId, userId, key); - } - Assert.assertEquals(affectedRows, 1); - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testDeleteAccountMetadataByKeyNullAccountIdError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadataByKey(null, userId, key); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testDeleteAccountMetadataByKeyNullUserIdError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadataByKey(accountId, null, key); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "accountMetadataDataProvider") - public void testDeleteAccountMetadataByKeyNullKeyError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadataByKey(accountId, userId, null); - } - } - - @Test(dependsOnMethods = {"testAddOrUpdateAccountMetadata", "testDeleteAccountMetadataByKey"}, priority = 2) - public void testDeleteAccountMetadata() - throws Exception { - - int affectedRows; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - affectedRows = accountMetadataService.removeAccountMetadata(accountId, userId); - } - Assert.assertEquals(affectedRows, 3); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataNullAccountIdError() throws Exception { - - String userId = AccountMetadataDAOTestData.SAMPLE_USER_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadata(null, userId); - } - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataNullUserIdError() throws Exception { - - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadata(accountId, null); - } - } - - @Test(dataProvider = "globalAccountMetadataDataProvider", dependsOnMethods = - {"testAddOrUpdateGlobalAccountMetadataMap"}, - priority = 2) - public void testDeleteGlobalAccountMetadataByKey(String accountId, String userId, String key, String value) - throws Exception { - - int affectedRows; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - affectedRows = accountMetadataService.removeAccountMetadataByKey(accountId, key); - } - Assert.assertEquals(affectedRows, 1); - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "globalAccountMetadataDataProvider") - public void testDeleteGlobalAccountMetadataByKeyNullAccountIdError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadataByKey(null, key); - } - } - - @Test(expectedExceptions = OpenBankingException.class, dataProvider = "globalAccountMetadataDataProvider") - public void testDeleteGlobalAccountMetadataByKeyNullKeyError(String accountId, String userId, String key, - String value) throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadataByKey(accountId, null); - } - } - - @Test(dependsOnMethods = {"testAddOrUpdateGlobalAccountMetadataMap", "testDeleteGlobalAccountMetadataByKey"}, - priority = 2) - public void testDeleteGlobalAccountMetadata() - throws Exception { - - int affectedRows; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - affectedRows = accountMetadataService.removeAccountMetadata(accountId); - } - Assert.assertEquals(affectedRows, 3); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteGlobalAccountMetadataNullAccountIdError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadata(null); - } - } - - @Test(dependsOnMethods = {"testAddOrUpdateAccountMetadataForSameAccount"}, priority = 2) - public void testDeleteAccountMetadataByKeyForAllUsers() throws Exception { - - int affectedRows; - String accountId = AccountMetadataDAOTestData.SAMPLE_ACCOUNT_ID; - String attributeKey = AccountMetadataDAOTestData.SAMPLE_KEY; - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - affectedRows = accountMetadataService.removeAccountMetadataByKeyForAllUsers(accountId, attributeKey); - } - Assert.assertEquals(affectedRows, 4); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testDeleteAccountMetadataByKeyForAllUsersNullUserIdError() throws Exception { - - try (Connection dbConnection = DAOUtils.getConnection(DB_NAME)) { - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()) - .thenReturn(dbConnection); - accountMetadataService.removeAccountMetadataByKeyForAllUsers(null, - AccountMetadataDAOTestData.SAMPLE_KEY); - } - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/util/AccountMetadataDAOTestData.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/util/AccountMetadataDAOTestData.java deleted file mode 100644 index fa79385e..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/util/AccountMetadataDAOTestData.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.account.metadata.service.util; - - -import java.util.HashMap; -import java.util.Map; - -/** - * Implementation of AccountMetadataDAOTestData class. - */ -public class AccountMetadataDAOTestData { - - public static final String SAMPLE_ACCOUNT_ID = "account-1"; - public static final String SAMPLE_USER_ID = "ann@gold.com"; - public static final String SAMPLE_KEY = "bnr-permission"; - public static final String SAMPLE_VALUE = "active"; - public static final String GLOBAL = "GLOBAL"; - - public static final Map SAMPLE_ACCOUNT_ATTRIBUTES_MAP = new HashMap() { - { - put("disclosure-option", "pre-approved"); - put("other-accounts-availability", "true"); - put("secondary-account-instruction", "active"); - put("secondary-account-privilege", "inactive"); - } - }; - - public static final Map SAMPLE_USER_ID_ATTRIBUTE_VALUE_MAP = new HashMap() { - { - put("sample_user_id_1", "active"); - put("sample_user_id_2", "inactive"); - put("sample_user_id_3", "active"); - put("sample_user_id_4", "inactive"); - } - }; - - /** - * Implementation of AccountMetadataServiceTests class. - */ - public static final class DataProviders { - - public static final Object[][] METADATA_DATA_HOLDER = new Object[][]{ - - { - SAMPLE_ACCOUNT_ID, - SAMPLE_USER_ID, - "disclosure-option", - "pre-approved", - } - }; - - public static final Object[][] GLOBAL_METADATA_DATA_HOLDER = new Object[][]{ - - { - SAMPLE_ACCOUNT_ID, - GLOBAL, - "disclosure-option", - "pre-approved", - } - }; - - public static final Object[][] GET_METADATA_DATA_HOLDER = new Object[][]{ - - { - SAMPLE_ACCOUNT_ID, - SAMPLE_USER_ID, - } - }; - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/util/DAOUtils.java b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/util/DAOUtils.java deleted file mode 100644 index 83ae7020..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/java/com/wso2/openbanking/accelerator/account/metadata/service/util/DAOUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.account.metadata.service.util; - -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.commons.lang3.StringUtils; - -import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - -/** - * Implementation of DAOUtils class. - */ -public class DAOUtils { - - private static Map dataSourceMap = new HashMap<>(); - - public static void initializeDataSource(String databaseName, String scriptPath) throws Exception { - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName("org.h2.Driver"); - dataSource.setUsername("username"); - dataSource.setPassword("password"); - dataSource.setUrl("jdbc:h2:mem:" + databaseName); - - try (Connection connection = dataSource.getConnection()) { - connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'"); - } - dataSourceMap.put(databaseName, dataSource); - } - - public static Connection getConnection(String database) throws SQLException { - if (dataSourceMap.get(database) != null) { - return dataSourceMap.get(database).getConnection(); - } - throw new RuntimeException("Invalid datasource."); - } - - public static String getFilePath(String fileName) { - if (StringUtils.isNotBlank(fileName)) { - return Paths.get(System.getProperty("user.dir"), "src", "test", "resources", fileName) - .toString(); - } - return null; - } -} diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/resources/dbScripts/h2.sql b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/resources/dbScripts/h2.sql deleted file mode 100644 index e79fb9a7..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/resources/dbScripts/h2.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE TABLE IF NOT EXISTS OB_ACCOUNT_METADATA ( - ACCOUNT_ID VARCHAR(100) NOT NULL, - USER_ID VARCHAR(100) NOT NULL, - METADATA_KEY VARCHAR(100) NOT NULL, - METADATA_VALUE VARCHAR(100) NOT NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - PRIMARY KEY (USER_ID,ACCOUNT_ID,METADATA_KEY) -); diff --git a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/resources/testng.xml b/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/resources/testng.xml deleted file mode 100644 index af4222bb..00000000 --- a/open-banking-accelerator/components/account-metadata/com.wso2.openbanking.accelerator.account.metadata.service/src/test/resources/testng.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/pom.xml deleted file mode 100644 index 3e35d80f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/pom.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.0-SNAPSHOT - ../../pom.xml - - com.wso2.openbanking.accelerator.ciba - bundle - WSO2 Open Banking - Common component - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - provided - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth - ${identity.inbound.auth.oauth.ciba.updated.version} - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.ciba - ${identity.inbound.auth.oauth.ciba.updated.version} - - - org.powermock - powermock-module-testng - - - org.powermock - powermock-api-mockito - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.service - - - org.springframework - spring-test - - - org.springframework - spring-core - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.jacoco - jacoco-maven-plugin - - - - **/*GrantHandler.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.86 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - false - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.identity.internal - - - com.nimbusds.jwt; version="${nimbusds.osgi.version.range}", - com.wso2.openbanking.accelerator.common.exception; version="${project.version}", - com.wso2.openbanking.accelerator.common.util; version="${project.version}", - com.wso2.openbanking.accelerator.consent.mgt.service.impl; version="${project.version}", - net.minidev.json; version="${json-smart}", - org.apache.commons.logging; version="${commons.logging.version}", - org.wso2.carbon.identity.oauth.ciba.grant; version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2; version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2.dto; version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2.model; version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2.token; version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.openidconnect; version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.openidconnect.model; version="${identity.inbound.auth.oauth.version.range}", - - - !com.wso2.openbanking.accelerator.identity.internal, - com.wso2.openbanking.accelerator.ciba - - * - <_dsannotations>* - - - - - - - 6.4.111.52 - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/CIBAConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/CIBAConstants.java deleted file mode 100644 index 62c25ffc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/CIBAConstants.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba; - -/** - * CIBA Test Constants class. - */ -public class CIBAConstants { - - public static final String INVALID_REQUEST = "invalid_request"; - public static final String INTENT_CLAIM = "openbanking_intent_id"; - public static final String VALUE_TAG = "value"; - public static final String CONSENT_ID_PREFIX = "OB_CONSENT_ID_"; - - //Error Messages - public static final String PARSE_ERROR_MESSAGE = - "Request object invalid: Unable to parse the request object as json"; - public static final String EMPTY_CONTENT_ERROR = "Request object invalid: Empty value for intent"; - public static final String MESSAGE_CONTEXT_EMPTY_ERROR = "OAuth Token Request Message Context is empty"; - public static final String SCOPE_ADDING_ERROR = "Error while adding consent ID to scopes"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCIBARequestObjectValidationExtension.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCIBARequestObjectValidationExtension.java deleted file mode 100644 index 7b0251dc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCIBARequestObjectValidationExtension.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.openidconnect.CIBARequestObjectValidatorImpl; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import java.text.ParseException; - -/** - * The extension of RequestObjectValidatorImpl to enforce Open Banking specific validations of the - * request object. - */ -public class OBCIBARequestObjectValidationExtension extends CIBARequestObjectValidatorImpl { - - /** - * Validations related to clientId, response type, exp, redirect URL, mandatory params, - * issuer, audience are done. Called after signature validation. - * - * @param initialRequestObject request object - * @param oAuth2Parameters oAuth2Parameters - * @throws RequestObjectException - RequestObjectException - */ - @Override - public boolean validateRequestObject(RequestObject initialRequestObject, OAuth2Parameters oAuth2Parameters) - throws RequestObjectException { - - JSONObject intent; - try { - intent = initialRequestObject.getClaimsSet().getJSONObjectClaim(CIBAConstants.INTENT_CLAIM); - } catch (ParseException e) { - throw new RequestObjectException(CIBAConstants.INVALID_REQUEST, - CIBAConstants.PARSE_ERROR_MESSAGE, e); - } - if (StringUtils.isEmpty(intent.getAsString(CIBAConstants.VALUE_TAG))) { - throw new RequestObjectException(CIBAConstants.INVALID_REQUEST, CIBAConstants.EMPTY_CONTENT_ERROR); - } - - return validateIAMConstraints(initialRequestObject, oAuth2Parameters); - } - - /** - * Validate IAM related logic. - * @param requestObject - * @param oAuth2Parameters - * @return is IAM related constraints are validate - * @throws RequestObjectException - */ - @Generated(message = "super methods cannot be mocked") - boolean validateIAMConstraints(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws RequestObjectException { - - return super.validateRequestObject(requestObject, oAuth2Parameters); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCIBASignatureAlgorithmEnforcementValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCIBASignatureAlgorithmEnforcementValidator.java deleted file mode 100644 index b01a769e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCIBASignatureAlgorithmEnforcementValidator.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba; - -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; -import com.wso2.openbanking.accelerator.identity.token.validators.SignatureAlgorithmEnforcementValidator; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; - -import javax.servlet.http.HttpServletResponse; - -/** - * CIBA Signature Algorithm Enforcer class - */ -public class OBCIBASignatureAlgorithmEnforcementValidator extends SignatureAlgorithmEnforcementValidator { - - /** - * CIBA and FAPI related validations for Signature Algorithm. - * @param requestSigningAlgorithm the algorithm of signed message - * @param registeredSigningAlgorithm the algorithm registered during client authentication - * @throws TokenFilterException - */ - @Override - public void validateInboundSignatureAlgorithm(String requestSigningAlgorithm, String registeredSigningAlgorithm) - throws TokenFilterException { - - super.validateInboundSignatureAlgorithm(requestSigningAlgorithm, registeredSigningAlgorithm); - if (OAuthServerConfiguration.getInstance().isFapiCiba()) { - if (!(IdentityCommonConstants.ALG_ES256.equals(requestSigningAlgorithm) || - IdentityCommonConstants.ALG_PS256.equals(requestSigningAlgorithm))) { - String message = "FAPI unsupported signing algorithm " + requestSigningAlgorithm - + " used to sign the JWT"; - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_CLIENT_MESSAGE, message); - } - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCibaGrantHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCibaGrantHandler.java deleted file mode 100644 index f656bc7c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/java/com.wso2.openbanking.accelerator.ciba/OBCibaGrantHandler.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth.ciba.grant.CibaGrantHandler; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; - -import java.util.Arrays; - -/** - * OB specific CIBA grant handler. - */ -public class OBCibaGrantHandler extends CibaGrantHandler { - - private static final ConsentCoreServiceImpl consentCoreService = new ConsentCoreServiceImpl(); - private static Log log = LogFactory.getLog(CibaGrantHandler.class); - - public void setConsentIdScope(OAuthTokenReqMessageContext tokReqMsgCtx, String authReqId) - throws IdentityOAuth2Exception { - String[] scopesArray; - String[] tokenRequestMessageContextArray = tokReqMsgCtx.getScope(); - if (tokenRequestMessageContextArray != null) { - scopesArray = Arrays.copyOf(tokenRequestMessageContextArray, tokenRequestMessageContextArray.length + 1); - } else { - throw new IdentityOAuth2Exception(CIBAConstants.MESSAGE_CONTEXT_EMPTY_ERROR); - } - try { - scopesArray[scopesArray.length - 1] = CIBAConstants.CONSENT_ID_PREFIX + consentCoreService. - getConsentIdByConsentAttributeNameAndValue("auth_req_id", authReqId).get(0); - } catch (ConsentManagementException e) { - throw new IdentityOAuth2Exception(CIBAConstants.SCOPE_ADDING_ERROR, e); - } - tokReqMsgCtx.setScope(scopesArray); - - } - - @Override - public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - if (!super.validateGrant(tokReqMsgCtx)) { - log.error("Successful in validating grant.Validation failed for the token request made by client: " - + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId()); - return false; - } else { - setConsentIdScope(tokReqMsgCtx, super.getAuthReqId(tokReqMsgCtx)); - return true; - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index c4f8e532..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/resources/findbugs-include.xml deleted file mode 100644 index 649d044e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/OBCIBARequestObjectValidationExtensionTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/OBCIBARequestObjectValidationExtensionTest.java deleted file mode 100644 index 74133c1a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/OBCIBARequestObjectValidationExtensionTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba; - -import com.nimbusds.jwt.JWTClaimsSet; -import net.minidev.json.JSONObject; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -/** - * Test class for OBCIBARequestObjectValidationExtension. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({JWTClaimsSet.class, OAuth2Parameters.class, RequestObject.class, JSONObject.class}) -public class OBCIBARequestObjectValidationExtensionTest extends PowerMockTestCase { - - private final String dummyString = "dummyString"; - - @Test(expectedExceptions = RequestObjectException.class, description = "Empty intent key") - public void validateRequestObjectInvalidIntentKeyTest() throws Exception { - - OBCIBARequestObjectValidationExtensionMock obcibaRequestObjectValidationExtensionMock = - new OBCIBARequestObjectValidationExtensionMock(); - - JSONObject intent = mock(JSONObject.class); - - RequestObject requestObject = mock(RequestObject.class); - OAuth2Parameters oAuth2Parameters = mock(OAuth2Parameters.class); - JWTClaimsSet claimsSet = Mockito.mock(JWTClaimsSet.class); - - Mockito.when(requestObject.getClaimsSet()).thenReturn(claimsSet); - Mockito.when(claimsSet.getJSONObjectClaim(Mockito.anyString())).thenReturn(intent); - - when(intent.getAsString(dummyString)).thenReturn(dummyString); - - obcibaRequestObjectValidationExtensionMock.validateRequestObject(requestObject, oAuth2Parameters); - - } - - @Test(description = "success scenario") - public void validateRequestObjectValidObjectTest() throws Exception { - - OBCIBARequestObjectValidationExtensionMock obcibaRequestObjectValidationExtensionMock = - new OBCIBARequestObjectValidationExtensionMock(); - - JSONObject intent = mock(JSONObject.class); - - RequestObject requestObject = mock(RequestObject.class); - OAuth2Parameters oAuth2Parameters = mock(OAuth2Parameters.class); - JWTClaimsSet claimsSet = Mockito.mock(JWTClaimsSet.class); - - Mockito.when(requestObject.getClaimsSet()).thenReturn(claimsSet); - Mockito.when(claimsSet.getJSONObjectClaim(Mockito.anyString())).thenReturn(intent); - - when(intent.getAsString("value")).thenReturn(dummyString); - - obcibaRequestObjectValidationExtensionMock.validateRequestObject(requestObject, oAuth2Parameters); - - } -} - -class OBCIBARequestObjectValidationExtensionMock extends OBCIBARequestObjectValidationExtension { - - @Override - boolean validateIAMConstraints(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws RequestObjectException { - return Mockito.anyBoolean(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/OBCIBASignatureAlgorithmEnforcementValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/OBCIBASignatureAlgorithmEnforcementValidatorTest.java deleted file mode 100644 index 8de0c7ce..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/OBCIBASignatureAlgorithmEnforcementValidatorTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba; - -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.DefaultTokenFilter; -import com.wso2.openbanking.accelerator.identity.token.TokenFilter; -import com.wso2.openbanking.accelerator.identity.token.validators.OBIdentityFilterValidator; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.http.HttpStatus; -import org.json.JSONObject; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.ServletOutputStream; - -import static org.testng.Assert.assertEquals; - -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class, OAuthServerConfiguration.class}) -public class OBCIBASignatureAlgorithmEnforcementValidatorTest extends PowerMockTestCase { - - - - MockHttpServletResponse response; - MockHttpServletRequest request; - FilterChain filterChain; - - @BeforeMethod - public void beforeMethod() { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - - } - - //Enable this test if you are building CIBA components along with this. - @Test(description = "Test when registered algorithm and signed algorithm differ") - public void fapiUnsupportedSignatureAlgorithmValidationTest() throws Exception { - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.mockStatic(OAuthServerConfiguration.class); - - OAuthServerConfiguration oAuthServerConfiguration = Mockito.mock(OAuthServerConfiguration.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - OBCIBASignatureAlgorithmEnforcementValidator validator = - Mockito.spy(OBCIBASignatureAlgorithmEnforcementValidator.class); - - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - Mockito.doReturn("RS256").when(validator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("RS256").when(validator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("iYpRm64b2vmvmKDhdL6KZD9z6fca")) - .thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration); - Mockito.when(oAuthServerConfiguration.isFapiCiba()).thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_UNAUTHORIZED); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_client"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "FAPI unsupported signing algorithm RS256 used to sign the JWT"); - } - - public static Map getResponse(ServletOutputStream outputStream) { - - Map response = new HashMap<>(); - JSONObject outputStreamMap = new JSONObject(outputStream); - JSONObject targetStream = new JSONObject(outputStreamMap.get(TestConstants.TARGET_STREAM).toString()); - response.put(IdentityCommonConstants.OAUTH_ERROR, - targetStream.get(IdentityCommonConstants.OAUTH_ERROR).toString()); - response.put(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION, - targetStream.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION).toString()); - return response; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/TestConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/TestConstants.java deleted file mode 100644 index adbe8927..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/java/com/wso2/openbanking/accelerator/ciba/TestConstants.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package com.wso2.openbanking.accelerator.ciba; - -public class TestConstants { - - public static final String CLIENT_ASSERTION = "eyJraWQiOiJqeVJVY3l0MWtWQ2xjSXZsVWxjRHVrVlozdFUiLCJhbGciOiJQUzI1" + - "NiJ9.eyJzdWIiOiJpWXBSbTY0YjJ2bXZtS0RoZEw2S1pEOXo2ZmNhIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6OTQ0My9vYXV0a" + - "DIvdG9rZW4iLCJpc3MiOiJpWXBSbTY0YjJ2bXZtS0RoZEw2S1pEOXo2ZmNhIiwiZXhwIjoxNjEwNjMxNDEyLCJpYXQiOjE2MTA2MDE" + - "0MTIsImp0aSI6IjE2MTA2MDE0MTI5MDAifQ.tmMTlCL-VABhFTA6QQ6UPvUydKuzynidepAa8oZGEBfVyAsiW5IF01NKYD0ynpXXJC" + - "Q6hcbWK0FEGity67p6DeI9LT-xAnaKwZY7H8rbuxWye2vhanM0jVa1vggsmwWYyOR4k55ety9lP1MkcGZpaK48qoaqsX_X7GCSGXzq" + - "BncTEPYfCpVUQtS4ctwoCl06TFbY2Lfm9E24z1rfmU9xPc7au6LpKRLMMHQ8QXuc-FhnWdgEFv_3tAai2ovVmrqEfwj6Z6Ew5bFeI9" + - "jtCR4TSol47hzDwldx5rH7m2OPUx66yEtGrM7UU62fC-4nxplZ69fjlHN4KQ62PxEaCQs0_A"; - - public static final String CERTIFICATE_HEADER = "x-wso2-mutual-auth-cert"; - public static final String CERTIFICATE_CONTENT = "-----BEGIN CERTIFICATE-----" + - "MIIFODCCBCCgAwIBAgIEWcWGxDANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJH" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNVBAMTJU9wZW5CYW5raW5nIFBy" + - "ZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwHhcNMTkwNTE2MDg0NDQ2WhcNMjAwNjE2" + - "MDkxNDQ2WjBhMQswCQYDVQQGEwJHQjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxGzAZ" + - "BgNVBAsTEjAwMTU4MDAwMDFIUVFyWkFBWDEfMB0GA1UEAxMWc0Zna2k3Mk9pcXda" + - "TkZPWmc2T2FqaTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANoVwx4E" + - "iWnQs89lj8vKSy/xTbZU2AHS9tFNz7wVa+rkpFyLVPtQW8AthG4hlfrBYMne7/P9" + - "c1Fi/q+n7eomWvJJo44GV44GJhegM6yyRaIcQdpxe9x9G4twWK4cY+VU3TfE6Dbd" + - "DdmAt7ai4KFbbpB33N8RwXoeGZdwxZFNPmfaoZZbz5p9+aSMQf1UyExcdlPXah77" + - "PDZDwAnyy5kYXUPS59S78+p4twqZXyZu9hd+Su5Zod5UObRJ4F5LQzZPS1+KzBje" + - "JM0o8qoRRZTZkLNnmmQw503KXp/LCLrSbFU2ZLGy3bQpKFFc5I6tZiy67ELNzLWo" + - "DzngEbApwhX+jtsCAwEAAaOCAgQwggIAMA4GA1UdDwEB/wQEAwIHgDAgBgNVHSUB" + - "Af8EFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwgeAGA1UdIASB2DCB1TCB0gYLKwYB" + - "BAGodYEGAWQwgcIwKgYIKwYBBQUHAgEWHmh0dHA6Ly9vYi50cnVzdGlzLmNvbS9w" + - "b2xpY2llczCBkwYIKwYBBQUHAgIwgYYMgYNVc2Ugb2YgdGhpcyBDZXJ0aWZpY2F0" + - "ZSBjb25zdGl0dXRlcyBhY2NlcHRhbmNlIG9mIHRoZSBPcGVuQmFua2luZyBSb290" + - "IENBIENlcnRpZmljYXRpb24gUG9saWNpZXMgYW5kIENlcnRpZmljYXRlIFByYWN0" + - "aWNlIFN0YXRlbWVudDBtBggrBgEFBQcBAQRhMF8wJgYIKwYBBQUHMAGGGmh0dHA6" + - "Ly9vYi50cnVzdGlzLmNvbS9vY3NwMDUGCCsGAQUFBzAChilodHRwOi8vb2IudHJ1" + - "c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNydDA6BgNVHR8EMzAxMC+gLaArhilo" + - "dHRwOi8vb2IudHJ1c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNybDAfBgNVHSME" + - "GDAWgBRQc5HGIXLTd/T+ABIGgVx5eW4/UDAdBgNVHQ4EFgQU5eqvEZ6ZdQS5bq/X" + - "dzP5XY/fUXUwDQYJKoZIhvcNAQELBQADggEBAIg8bd/bIh241ewS79lXU058VjCu" + - "JC+4QtcI2XiGV3dBpg10V6Kb6E/h8Gru04uVZW1JK52ivVb5NYs6r8txRsTBIaA8" + - "Cr03LJqEftclL9NbkPZnpEkUfqCBfujNQF8XWaQgXIIA+io1UzV1TG3K9XCa/w2S" + - "sTANKfF8qK5kRsy6z9OGPUE+Oi3DUt+E9p5LCq6n5Bkp9YRGmyYRPs8JMkJmq3sf" + - "wtXOy27LE4exJRuZsF1CA78ObaRytuE3DJcnIRdhOcjWieS/MxZD7bzuuAPu5ySX" + - "i2/qxT3AlWtHtxrz0mKSC3rlgYAHCzCAHoASWKpf5tnB3TodPVZ6DYOu7oI=" + - "-----END CERTIFICATE-----"; - - public static final String TARGET_STREAM = "targetStream"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/resources/testng.xml deleted file mode 100644 index 5b2f8ba3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.ciba/src/test/resources/testng.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/pom.xml deleted file mode 100644 index 870e3fdd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/pom.xml +++ /dev/null @@ -1,306 +0,0 @@ - - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - - com.wso2.openbanking.accelerator.common - bundle - WSO2 Open Banking - Common component - - - org.wso2.orbit.org.bouncycastle - bcpkix-jdk18on - - - org.wso2.orbit.org.bouncycastle - bcprov-jdk18on - - - org.apache.ws.commons.axiom.wso2 - axiom - - - commons-logging - commons-logging - - - org.wso2.securevault - org.wso2.securevault - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth - - - org.wso2.orbit.org.bouncycastle - bcprov-jdk15on - - - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.mgt - - - org.wso2.orbit.org.bouncycastle - bcprov-jdk15on - - - - - org.hibernate - hibernate-validator - - - commons-beanutils - commons-beanutils - - - - org.wso2.eclipse.osgi - org.eclipse.osgi.services - - - org.eclipse.osgi - org.eclipse.osgi - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.orbit.com.hazelcast - hazelcast - - - org.wso2.orbit.org.bouncycastle - bcprov-jdk15on - - - - - org.testng - testng - test - - - org.mockito - mockito-all - test - - - org.powermock - powermock-module-testng - - - org.powermock - powermock-api-mockito - - - io.jsonwebtoken - jjwt - - - org.wso2.orbit.com.nimbusds - nimbus-jose-jwt - - - net.minidev - json-smart - - - - - - com.github.spotbugs - spotbugs-maven-plugin - 4.2.3 - - Max - Low - false - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.jacoco - jacoco-maven-plugin - - - - **/*Constants.class - **/*Component.class - **/*DataHolder.class - **/*Enum.class - **/*Exception.class - **/*Discoverer.class - **/*AudienceValidator.class - **/*OpenBankingBaseCache.class - **/*OpenBankingBaseCacheKey.class - **/*OpenBankingIdentityBaseCache.class - **/*JWKSetCache.class - **/*JWKSetCacheKey.class - **/*ApplicationIdentityService.class - **/*JWKRetriever.class - **/*OpenBankingErrorCodes.class - **/*IdentityConstants.class - **/*ServerIdentityRetriever.class - - **/DatabaseUtil.class - **/JDBCPersistenceManager.class - **/CertValidationErrors.class - **/JDBCRetentionDataPersistenceManager.class - **/*Type*/** - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.77 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - - - - analyze-compile - compile - - check - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.common.internal - - - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}" - - - !com.wso2.openbanking.accelerator.common.internal, - com.wso2.openbanking.accelerator.common.*;version="${project.version}", - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/caching/OpenBankingBaseCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/caching/OpenBankingBaseCache.java deleted file mode 100644 index 1c41b245..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/caching/OpenBankingBaseCache.java +++ /dev/null @@ -1,212 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.caching; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.concurrent.TimeUnit; - -import javax.cache.Cache; -import javax.cache.CacheBuilder; -import javax.cache.CacheConfiguration; -import javax.cache.CacheManager; -import javax.cache.Caching; - -/** - * Abstract cache manager for Open Banking. - * - * @param Extended Cache Key - * @param Cache Value - */ -public abstract class OpenBankingBaseCache { - - private static final String BASE_CACHE_KEY = "OB_BASE_CACHE"; - private final String cacheName; - - private static final Log log = LogFactory.getLog(OpenBankingBaseCache.class); - - /** - * On Demand Retriever for caching. - */ - public interface OnDemandRetriever { - - Object get() throws OpenBankingException; - } - - /** - * Initialize With unique cache name. - * - * @param cacheName unique cache name. - */ - public OpenBankingBaseCache(String cacheName) { - - this.cacheName = cacheName; - - if (log.isDebugEnabled()) { - log.debug(String.format("Base Cache initialized for %s", cacheName.replaceAll("[\r\n]", ""))); - } - } - - /** - * Get from cache or invoke ondemand retriever and store. - * - * @param key cache key. - * @param onDemandRetriever on demand retriever. - * @return cached object. - * @throws OpenBankingException if an error occurs while retrieving the object - */ - public V getFromCacheOrRetrieve(K key, OnDemandRetriever onDemandRetriever) throws OpenBankingException { - - Cache cache = getBaseCache(); - - if (cache.containsKey(key)) { - - if (log.isDebugEnabled()) { - log.debug(String.format("Found cache entry `%s` in cache %s", - key.toString().replaceAll("[\r\n]", ""), cacheName.replaceAll("[\r\n]", ""))); - } - return cache.get(key); - } else { - - if (log.isDebugEnabled()) { - log.debug(String.format("Cache Entry `%s` not available in cache %s", - key.toString().replaceAll("[\r\n]", ""), cacheName.replaceAll("[\r\n]", ""))); - } - - V value = (V) onDemandRetriever.get(); - - if (log.isDebugEnabled()) { - log.debug(String.format("On demand retrieved `%s` for %s", - key.toString().replaceAll("[\r\n]", ""), cacheName.replaceAll("[\r\n]", ""))); - } - - removeFromCache(key); - addToCache(key, value); - return value; - } - - } - - /** - * Get from cache. - * - * @param key cache key. - * @return cached object. - */ - public V getFromCache(K key) { - - Cache cache = getBaseCache(); - - if (cache.containsKey(key)) { - - if (log.isDebugEnabled()) { - log.debug(String.format("Found cache entry `%s` in cache %s", - key.toString().replaceAll("[\r\n]", ""), cacheName.replaceAll("[\r\n]", ""))); - } - return cache.get(key); - } else { - - return null; - } - - } - - /** - * Add Object to cache. - * - * @param key cache key. - * @param value cache value. - */ - public void addToCache(K key, V value) { - - if (log.isDebugEnabled()) { - log.debug(String.format("`%s` added into cache %s", key.toString().replaceAll("[\r\n]", ""), - cacheName.replaceAll("[\r\n]", ""))); - } - - Cache cache = getBaseCache(); - cache.put(key, value); - } - - /** - * Remove Object from Cache. - * - * @param key cache key. - */ - public void removeFromCache(K key) { - - if (log.isDebugEnabled()) { - log.debug(String.format("`%s` removed from cache %s", key.toString().replaceAll("[\r\n]", ""), - cacheName.replaceAll("[\r\n]", ""))); - } - - Cache cache = getBaseCache(); - cache.remove(key); - } - - /** - * Get Cache for instance. - * - * @return - */ - private Cache getBaseCache() { - - CacheManager cacheManager = Caching.getCacheManager(BASE_CACHE_KEY); - - Iterable> availableCaches = cacheManager.getCaches(); - for (Cache cache : availableCaches) { - if (cache.getName().equalsIgnoreCase( - cache.getName().startsWith("$__local__$.") ? "$__local__$." + cacheName : cacheName)) { - return cacheManager.getCache(cacheName); - } - } - - CacheConfiguration.Duration accessExpiry = new CacheConfiguration.Duration(TimeUnit.MINUTES, - getCacheAccessExpiryMinutes()); - - CacheConfiguration.Duration modifiedExpiry = new CacheConfiguration.Duration(TimeUnit.MINUTES, - getCacheModifiedExpiryMinutes()); - - // Build Cache on OB base cache. - CacheBuilder cacheBuilder = cacheManager.createCacheBuilder(cacheName); - - return cacheBuilder.setExpiry(CacheConfiguration.ExpiryType.ACCESSED, accessExpiry) - .setExpiry(CacheConfiguration.ExpiryType.MODIFIED, modifiedExpiry) - .build(); - - } - - - /** - * Get Cache expiry time upon access in minutes. - * - * @return integer denoting number of minutes. - */ - public abstract int getCacheAccessExpiryMinutes(); - - /** - * Get Cache expiry time upon modification in minutes. - * - * @return integer denoting number of minutes. - */ - public abstract int getCacheModifiedExpiryMinutes(); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/caching/OpenBankingBaseCacheKey.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/caching/OpenBankingBaseCacheKey.java deleted file mode 100644 index b6ca634d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/caching/OpenBankingBaseCacheKey.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.caching; - -/** - * Abstract class for Open Banking Cache Key. - */ -public class OpenBankingBaseCacheKey { - - public OpenBankingBaseCacheKey() { - - } - - public OpenBankingBaseCacheKey(String cacheKey) { - - } - - public static OpenBankingBaseCacheKey of(String cacheKey) { - return new OpenBankingBaseCacheKey(cacheKey); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigParser.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigParser.java deleted file mode 100644 index 32486797..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigParser.java +++ /dev/null @@ -1,1483 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.config; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMException; -import org.apache.axiom.om.impl.builder.StAXOMBuilder; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.securevault.SecretResolver; -import org.wso2.securevault.SecretResolverFactory; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; -import java.util.stream.Collectors; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamException; - -import static java.util.Map.Entry.comparingByKey; - -/** - * Config parser for open-banking.xml. - */ -public class OpenBankingConfigParser { - - // To enable attempted thread-safety using double-check locking - private static final Object lock = new Object(); - private static final Log log = LogFactory.getLog(OpenBankingConfigParser.class); - private static final Map configuration = new HashMap<>(); - private static final Map> obExecutors = new HashMap<>(); - private static final Map> dataPublishingStreams = new HashMap<>(); - private static final Map> dataPublishingValidationMap = new HashMap<>(); - private static final Map> dcrRegistrationConfigs = new HashMap<>(); - private static final Map> authorizeSteps = new HashMap<>(); - private static final Map> allowedScopes = new HashMap<>(); - private static final Map> allowedAPIs = new HashMap<>(); - private static final Map revocationValidators = new HashMap<>(); - private static final List serviceActivatorSubscribers = new ArrayList<>(); - private static final Map> keyManagerAdditionalProperties - = new HashMap<>(); - private static Map obEventExecutors = new HashMap<>(); - private static OpenBankingConfigParser parser; - private static String configFilePath; - private static SecretResolver secretResolver; - private OMElement rootElement; - - private Map authWorkerConfig = new HashMap<>(); - - /** - * Private Constructor of config parser. - */ - private OpenBankingConfigParser() { - - buildConfiguration(); - } - - /** - * Singleton getInstance method to create only one object. - * - * @return OpenBankingConfigParser object - */ - public static OpenBankingConfigParser getInstance() { - - if (parser == null) { - synchronized (lock) { - if (parser == null) { - parser = new OpenBankingConfigParser(); - } - } - } - return parser; - } - - /** - * Method to get an instance of ConfigParser when custom file path is provided. - * - * This method is deprecated as it allows custom absolute file paths which could result in - * path traversal attacks. Do not use this method unless the custom path is trusted. - * - * @param filePath Custom file path - * @return OpenBankingConfigParser object - * @Deprecated use OpenBankingConfigParser.getInstance() - */ - @Deprecated - public static OpenBankingConfigParser getInstance(String filePath) { - - configFilePath = filePath; - return getInstance(); - } - - /** - * Method to obtain map of configs. - * - * @return Config map - */ - public Map getConfiguration() { - - return configuration; - } - - /** - * Method to read the configuration (in a recursive manner) as a model and put them in the configuration map. - */ - @SuppressFBWarnings("PATH_TRAVERSAL_IN") - // Suppressed content - new FileInputStream(configFilePath) - // Suppression reason - False Positive : Method for passing configFilePath is deprecated and is used for testing - // purposes only. Therefore, it can be assumed that configFilePath is a trusted filepath - // Suppressed warning count - 1 - private void buildConfiguration() { - - InputStream inStream = null; - StAXOMBuilder builder; - String warningMessage = ""; - try { - if (configFilePath != null) { - File openBankingConfigXml = new File(configFilePath); - if (openBankingConfigXml.exists()) { - inStream = new FileInputStream(openBankingConfigXml); - } - } else { - File openBankingConfigXml = new File(CarbonUtils.getCarbonConfigDirPath(), - OpenBankingConstants.OB_CONFIG_FILE); - if (openBankingConfigXml.exists()) { - inStream = new FileInputStream(openBankingConfigXml); - } - } - if (inStream == null) { - String message = - "open-banking configuration not found at: " + configFilePath + " . Cause - " + warningMessage; - if (log.isDebugEnabled()) { - log.debug(message.replaceAll("[\r\n]", "")); - } - throw new FileNotFoundException(message); - } - builder = new StAXOMBuilder(inStream); - builder.setDoDebug(false); - rootElement = builder.getDocumentElement(); - Stack nameStack = new Stack<>(); - secretResolver = SecretResolverFactory.create(rootElement, true); - readChildElements(rootElement, nameStack); - buildOBExecutors(); - buildDataPublishingStreams(); - buildDCRParameters(); - buildConsentAuthSteps(); - buildAllowedScopes(); - buildAllowedSubscriptions(); - buildServiceActivatorSubscribers(); - buildKeyManagerProperties(); - buildOBEventExecutors(); - buildWorkers(); - } catch (IOException | XMLStreamException | OMException e) { - throw new OpenBankingRuntimeException("Error occurred while building configuration from open-banking.xml", - e); - } finally { - try { - if (inStream != null) { - inStream.close(); - } - } catch (IOException e) { - log.error("Error closing the input stream for open-banking.xml", e); - } - } - } - - private void buildOBExecutors() { - - OMElement gatewayElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.GATEWAY_CONFIG_TAG)); - - if (gatewayElement != null) { - - OMElement openBankingGatewayExecutors = gatewayElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.GATEWAY_EXECUTOR_CONFIG_TAG)); - - if (openBankingGatewayExecutors != null) { - //obtaining each consent type element under OpenBankingGatewayExecutors tag - Iterator consentTypeElement = openBankingGatewayExecutors.getChildElements(); - while (consentTypeElement.hasNext()) { - OMElement consentType = (OMElement) consentTypeElement.next(); - String consentTypeName = consentType.getLocalName(); - Map executors = new HashMap<>(); - //obtaining each Executor element under each consent type - Iterator obExecutor = consentType.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.EXECUTOR_CONFIG_TAG)); - if (obExecutor != null) { - while (obExecutor.hasNext()) { - OMElement executorElement = obExecutor.next(); - //Retrieve class name and priority from executor config - String obExecutorClass = executorElement.getAttributeValue(new QName("class")); - String obExecutorPriority = executorElement.getAttributeValue(new QName("priority")); - - if (StringUtils.isEmpty(obExecutorClass)) { - //Throwing exceptions since we cannot proceed without invalid executor names - throw new OpenBankingRuntimeException("Executor class is not defined " + - "correctly in open-banking.xml"); - } - int priority = Integer.MAX_VALUE; - if (!StringUtils.isEmpty(obExecutorPriority)) { - priority = Integer.parseInt(obExecutorPriority); - } - executors.put(priority, obExecutorClass); - } - } - //Ordering the executors based on the priority number - LinkedHashMap priorityMap = executors.entrySet() - .stream() - .sorted(comparingByKey()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, - LinkedHashMap::new)); - obExecutors.put(consentTypeName, priorityMap); - } - } - } - } - - protected void buildKeyManagerProperties() { - - OMElement keyManagerElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.KEY_MANAGER_CONFIG_TAG)); - - if (keyManagerElement != null) { - OMElement keyManagerProperties = keyManagerElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.KEY_MANAGER_ADDITIONAL_PROPERTIES_CONFIG_TAG)); - - if (keyManagerProperties != null) { - Iterator properties = keyManagerProperties.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.PROPERTY_CONFIG_TAG)); - if (properties != null) { - while (properties.hasNext()) { - OMElement propertyElement = properties.next(); - - //Retrieve attributes from key manager config - Map property = new HashMap<>(); - property.put("priority", propertyElement.getAttributeValue(new QName("priority"))); - property.put("label", propertyElement.getAttributeValue(new QName("label"))); - property.put("type", propertyElement.getAttributeValue(new QName("type"))); - property.put("tooltip", propertyElement.getAttributeValue(new QName("tooltip"))); - property.put("default", propertyElement.getAttributeValue(new QName("default"))); - property.put("required", propertyElement.getAttributeValue(new QName("required"))); - property.put("mask", propertyElement.getAttributeValue(new QName("mask"))); - property.put("multiple", propertyElement.getAttributeValue(new QName("multiple"))); - property.put("values", propertyElement.getAttributeValue(new QName("values"))); - String propertyName = propertyElement.getAttributeValue(new QName("name")); - - if (StringUtils.isBlank(propertyName)) { - //Throwing exceptions since we cannot proceed without property names - throw new OpenBankingRuntimeException("Additional property name is not defined " + - "correctly in open-banking.xml"); - } - - keyManagerAdditionalProperties.put(propertyName, property); - } - } - } - } - } - - protected void buildDataPublishingStreams() { - - OMElement dataPublishingElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.DATA_PUBLISHING_CONFIG_TAG)); - - if (dataPublishingElement != null) { - OMElement thriftElement = dataPublishingElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.THRIFT_CONFIG_TAG)); - - if (thriftElement != null) { - OMElement streams = thriftElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.STREAMS_CONFIG_TAG)); - - if (streams != null) { - Iterator dataStreamElement = streams.getChildElements(); - while (dataStreamElement.hasNext()) { - OMElement dataStream = (OMElement) dataStreamElement.next(); - String dataStreamName = dataStream.getLocalName(); - Map attributes = new HashMap<>(); - //obtaining attributes under each stream - Iterator attribute = dataStream.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.ATTRIBUTE_CONFIG_TAG)); - if (attribute != null) { - while (attribute.hasNext()) { - OMElement attributeElement = attribute.next(); - //Retrieve attribute name and priority from config - String attributeName = attributeElement.getAttributeValue(new QName("name")); - String attributePriority = attributeElement.getAttributeValue(new QName("priority")); - String isRequired = attributeElement.getAttributeValue(new QName("required")); - String type = attributeElement.getAttributeValue(new QName("type")); - - if (StringUtils.isEmpty(attributeName)) { - //Throwing exceptions since we cannot proceed without valid attribute names - throw new OpenBankingRuntimeException( - "Data publishing attribute name is not defined " + - "correctly in open-banking.xml"); - } - int priority = Integer.MAX_VALUE; - if (!StringUtils.isEmpty(attributePriority)) { - priority = Integer.parseInt(attributePriority); - } - boolean required = false; - if (!StringUtils.isEmpty(isRequired)) { - required = Boolean.parseBoolean(isRequired); - } - - String attributeType = "string"; - if (!StringUtils.isEmpty(type)) { - attributeType = type; - } - - Map metadata = new HashMap<>(); - metadata.put(OpenBankingConstants.REQUIRED, required); - metadata.put(OpenBankingConstants.ATTRIBUTE_TYPE, attributeType); - - attributes.put(priority, attributeName); - String attributeKey = dataStreamName + "_" + attributeName; - dataPublishingValidationMap.put(attributeKey, metadata); - } - } - //Ordering the attributes based on the priority number - LinkedHashMap priorityMap = attributes.entrySet() - .stream() - .sorted(comparingByKey()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, - LinkedHashMap::new)); - dataPublishingStreams.put(dataStreamName, priorityMap); - } - } - } - } - } - - private void buildDCRParameters() { - - OMElement dcrElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.DCR_CONFIG_TAG)); - - if (dcrElement != null) { - OMElement registrationElement = dcrElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.DCR_REGISTRATION_CONFIG_TAG)); - - if (registrationElement != null) { - //obtaining each parameter type element under RegistrationRequestPrams tag - Iterator parameterTypeElement = registrationElement.getChildElements(); - while (parameterTypeElement.hasNext()) { - OMElement parameterType = (OMElement) parameterTypeElement.next(); - String parameterTypeName = parameterType.getLocalName(); - Map parameterValues = new HashMap<>(); - //obtaining each element under each parameter type - Iterator childValues = parameterType.getChildElements(); - while (childValues.hasNext()) { - OMElement child = (OMElement) childValues.next(); - if (OpenBankingConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUE_TAG - .equalsIgnoreCase(child.getLocalName())) { - - OMElement allowedValuesElement = parameterType.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUE_TAG)); - - List values = new ArrayList<>(); - if (allowedValuesElement != null) { - Iterator allowedValues = allowedValuesElement.getChildElements(); - while (allowedValues.hasNext()) { - OMElement value = (OMElement) allowedValues.next(); - values.add(value.getText()); - } - parameterValues.put(child.getLocalName(), values); - } - } else { - parameterValues.put(child.getLocalName(), child.getText()); - } - } - dcrRegistrationConfigs.put(parameterTypeName, parameterValues); - } - } - } - - } - - private void buildConsentAuthSteps() { - - OMElement consentElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.CONSENT_CONFIG_TAG)); - - if (consentElement != null) { - OMElement consentAuthorizeSteps = consentElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.AUTHORIZE_STEPS_CONFIG_TAG)); - - if (consentAuthorizeSteps != null) { - //obtaining each step type element under AuthorizeSteps tag - Iterator stepTypeElement = consentAuthorizeSteps.getChildElements(); - while (stepTypeElement.hasNext()) { - OMElement stepType = (OMElement) stepTypeElement.next(); - String consentTypeName = stepType.getLocalName(); - Map executors = new HashMap<>(); - //obtaining each step under each consent type - Iterator obExecutor = stepType.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.STEP_CONFIG_TAG)); - if (obExecutor != null) { - while (obExecutor.hasNext()) { - OMElement executorElement = obExecutor.next(); - //Retrieve class name and priority from executor config - String obExecutorClass = executorElement.getAttributeValue(new QName("class")); - String obExecutorPriority = executorElement.getAttributeValue(new QName("priority")); - - if (StringUtils.isEmpty(obExecutorClass)) { - //Throwing exceptions since we cannot proceed without invalid executor names - throw new OpenBankingRuntimeException("Executor class is not defined " + - "correctly in open-banking.xml"); - } - int priority = Integer.MAX_VALUE; - if (!StringUtils.isEmpty(obExecutorPriority)) { - priority = Integer.parseInt(obExecutorPriority); - } - executors.put(priority, obExecutorClass); - } - } - //Ordering the executors based on the priority number - LinkedHashMap priorityMap = executors.entrySet() - .stream() - .sorted(comparingByKey()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, - LinkedHashMap::new)); - authorizeSteps.put(consentTypeName, priorityMap); - } - } - } - } - - /** - * Method to read text configs from xml when root element is given. - * - * @param serverConfig XML root element object - * @param nameStack stack of config names - */ - private void readChildElements(OMElement serverConfig, Stack nameStack) { - - for (Iterator childElements = serverConfig.getChildElements(); childElements.hasNext(); ) { - OMElement element = (OMElement) childElements.next(); - nameStack.push(element.getLocalName()); - if (elementHasText(element)) { - String key = getKey(nameStack); - Object currentObject = configuration.get(key); - String value = replaceSystemProperty(element.getText()); - if (secretResolver != null && secretResolver.isInitialized() && - secretResolver.isTokenProtected(key)) { - value = secretResolver.resolve(key); - } - if (currentObject == null) { - configuration.put(key, value); - } else if (currentObject instanceof ArrayList) { - ArrayList list = (ArrayList) currentObject; - if (!list.contains(value)) { - list.add(value); - configuration.put(key, list); - } - } else { - if (!value.equals(currentObject)) { - ArrayList arrayList = new ArrayList<>(2); - arrayList.add(currentObject); - arrayList.add(value); - configuration.put(key, arrayList); - } - } - } else if (OpenBankingConstants.REVOCATION_VALIDATORS_CONFIG_TAG.equalsIgnoreCase(element.getLocalName())) { - Iterator environmentIterator = element - .getChildrenWithLocalName(OpenBankingConstants.REVOCATION_VALIDATOR_CONFIG_TAG); - - while (environmentIterator.hasNext()) { - OMElement environmentElem = (OMElement) environmentIterator.next(); - String revocationType = environmentElem.getAttributeValue(new QName("type")); - Integer priority; - try { - priority = Integer.parseInt(environmentElem.getAttributeValue(new QName("priority"))); - } catch (NumberFormatException e) { - log.warn("Consent retrieval RevocationValidator " + revocationType.replaceAll("[\r\n]", "") - + " priority invalid. Hence skipped"); - continue; - } - revocationValidators.put(priority, revocationType); - } - } - readChildElements(element, nameStack); - nameStack.pop(); - } - } - - private void buildAllowedScopes() { - OMElement gatewayElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.GATEWAY_CONFIG_TAG)); - - if (gatewayElement != null) { - OMElement tppManagementElement = gatewayElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.TPP_MANAGEMENT_CONFIG_TAG)); - - if (tppManagementElement != null) { - OMElement allowedScopesElement = tppManagementElement.getFirstChildWithName(new QName( - OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.ALLOWED_SCOPES_CONFIG_TAG)); - - //obtaining each scope under allowed scopes - Iterator environmentIterator = - allowedScopesElement.getChildrenWithLocalName(OpenBankingConstants.SCOPE_CONFIG_TAG); - - while (environmentIterator.hasNext()) { - OMElement scopeElem = (OMElement) environmentIterator.next(); - String scopeName = scopeElem.getAttributeValue(new QName("name")); - String rolesStr = scopeElem.getAttributeValue(new QName("roles")); - if (StringUtils.isNotEmpty(rolesStr)) { - List rolesList = Arrays.stream(rolesStr.split(",")) - .map(String::trim) - .collect(Collectors.toList()); - allowedScopes.put(scopeName, rolesList); - } - } - } - } - } - - private void buildAllowedSubscriptions() { - - OMElement dcrElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.DCR_CONFIG_TAG)); - - if (dcrElement != null) { - OMElement regulatoryAPIs = dcrElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.REGULATORY_API_NAMES)); - - if (regulatoryAPIs != null) { - - //obtaining each regulatory API under allowed regulatory APIs - Iterator environmentIterator = - regulatoryAPIs.getChildrenWithLocalName(OpenBankingConstants.REGULATORY_API); - - while (environmentIterator.hasNext()) { - OMElement regulatoryAPIElem = (OMElement) environmentIterator.next(); - String regulatoryAPIName = regulatoryAPIElem.getAttributeValue(new QName( - OpenBankingConstants.API_NAME)); - String rolesStr = regulatoryAPIElem.getAttributeValue(new QName( - OpenBankingConstants.API_ROLE)); - if (StringUtils.isNotEmpty(rolesStr)) { - List rolesList = Arrays.stream(rolesStr.split(",")) - .map(String::trim) - .collect(Collectors.toList()); - allowedAPIs.put(regulatoryAPIName, rolesList); - } else { - allowedAPIs.put(regulatoryAPIName, Collections.emptyList()); - } - } - } - } - } - - private void buildOBEventExecutors() { - - OMElement eventElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.EVENT_CONFIG_TAG)); - - if (eventElement != null) { - - OMElement openBankingEventExecutors = eventElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, - OpenBankingConstants.EVENT_EXECUTOR_CONFIG_TAG)); - - if (openBankingEventExecutors != null) { - //obtaining each executor element under EventExecutors tag - //Ordering the executors based on the priority number - Iterator eventExecutor = openBankingEventExecutors.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.EXECUTOR_CONFIG_TAG)); - if (eventExecutor != null) { - while (eventExecutor.hasNext()) { - OMElement executorElement = eventExecutor.next(); - //Retrieve class name and priority from executor config - String obExecutorClass = executorElement.getAttributeValue(new QName("class")); - String obExecutorPriority = executorElement.getAttributeValue(new QName("priority")); - - if (StringUtils.isEmpty(obExecutorClass)) { - //Throwing exceptions since we cannot proceed without invalid executor names - throw new OpenBankingRuntimeException("Event Executor class is not defined " + - "correctly in open-banking.xml"); - } - int priority = Integer.MAX_VALUE; - if (!StringUtils.isEmpty(obExecutorPriority)) { - priority = Integer.parseInt(obExecutorPriority); - } - obEventExecutors.put(priority, obExecutorClass); - } - } - //Ordering the executors based on the priority number - obEventExecutors = obEventExecutors.entrySet() - .stream() - .sorted(comparingByKey()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, - LinkedHashMap::new)); - } - } - } - - /** - * Method to build configurations for Authentication Worker Extension point. - */ - private void buildWorkers() { - - OMElement workersOMEList = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.AUTHENTICATION_WORKER_LIST_TAG)); - - if (workersOMEList != null) { - Iterator workerConfigs = workersOMEList.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.AUTHENTICATION_WORKER_TAG)); - if (workerConfigs != null) { - while (workerConfigs.hasNext()) { - OMElement executorElement = workerConfigs.next(); - //Retrieve class name and implementation from executor config - String workerClass = executorElement.getAttributeValue(new QName("class")); - String workerName = executorElement.getAttributeValue(new QName("name")); - - if (StringUtils.isEmpty(workerClass) || StringUtils.isEmpty(workerName)) { - //Throwing exceptions since we cannot proceed without invalid worker names - throw new OpenBankingRuntimeException("Authentication worker class is not defined " + - "correctly in open-banking.xml"); - } - authWorkerConfig.put(workerName, workerClass); - } - } - } - } - - /** - * Method to obtain config key from stack. - * - * @param nameStack Stack of strings with names. - * @return key as a String - */ - private String getKey(Stack nameStack) { - - StringBuilder key = new StringBuilder(); - for (int index = 0; index < nameStack.size(); index++) { - String name = nameStack.elementAt(index); - key.append(name).append("."); - } - key.deleteCharAt(key.lastIndexOf(".")); - return key.toString(); - } - - /** - * Method to replace system properties in configs. - * - * @param text String that may require modification - * @return modified string - */ - private String replaceSystemProperty(String text) { - - int indexOfStartingChars = -1; - int indexOfClosingBrace; - - // The following condition deals with properties. - // Properties are specified as ${system.property}, - // and are assumed to be System properties - StringBuilder textBuilder = new StringBuilder(text); - while (indexOfStartingChars < textBuilder.indexOf("${") - && (indexOfStartingChars = textBuilder.indexOf("${")) != -1 - && (indexOfClosingBrace = textBuilder.indexOf("}")) != -1) { // Is a property used? - String sysProp = textBuilder.substring(indexOfStartingChars + 2, indexOfClosingBrace); - String propValue = System.getProperty(sysProp); - if (propValue != null) { - textBuilder = new StringBuilder(textBuilder.substring(0, indexOfStartingChars) + propValue - + textBuilder.substring(indexOfClosingBrace + 1)); - } - if (sysProp.equals(OpenBankingConstants.CARBON_HOME) && - System.getProperty(OpenBankingConstants.CARBON_HOME).equals(".")) { - textBuilder.insert(0, new File(".").getAbsolutePath() + File.separator); - } - } - return textBuilder.toString(); - } - - /** - * Method to check whether config element has text value. - * - * @param element root element as a object - * @return availability of text in the config - */ - private boolean elementHasText(OMElement element) { - - String text = element.getText(); - return text != null && text.trim().length() != 0; - } - - public Map> getOpenBankingExecutors() { - - return obExecutors; - } - - public Map getOpenBankingEventExecutors() { - - return obEventExecutors; - } - - public Map> getDataPublishingStreams() { - - return dataPublishingStreams; - } - - public Map> getDataPublishingValidationMap() { - - return dataPublishingValidationMap; - } - - public Map> getConsentAuthorizeSteps() { - - return authorizeSteps; - } - - public Map> getKeyManagerAdditionalProperties() { - - return keyManagerAdditionalProperties; - } - - /** - * Returns the element with the provided key. - * - * @param key local part name - * @return Corresponding value for key - */ - public Object getConfigElementFromKey(String key) { - - return configuration.get(key); - } - - public String getDataSourceName() { - - return getConfigElementFromKey(OpenBankingConstants.JDBC_PERSISTENCE_CONFIG) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.JDBC_PERSISTENCE_CONFIG)).trim(); - } - - /** - * Returns the database connection verification timeout in seconds configured in open-banking.xml. - * - * @return 1 if nothing is configured - */ - public int getConnectionVerificationTimeout() { - - return getConfigElementFromKey(OpenBankingConstants.DB_CONNECTION_VERIFICATION_TIMEOUT) == null ? 1 : - Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.DB_CONNECTION_VERIFICATION_TIMEOUT).toString().trim()); - } - - /** - * Returns the retention datasource name configured in open-banking.xml. - * @return retention datasource name or empty string if nothing is configured - */ - public String getRetentionDataSourceName() { - - return getConfigElementFromKey(OpenBankingConstants.JDBC_RETENTION_DATA_PERSISTENCE_CONFIG) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.JDBC_RETENTION_DATA_PERSISTENCE_CONFIG)).trim(); - } - - /** - * Returns the retention database connection verification timeout in seconds configured in open-banking.xml. - * - * @return 1 if nothing is configured - */ - public int getRetentionDataSourceConnectionVerificationTimeout() { - - return getConfigElementFromKey(OpenBankingConstants.RETENTION_DATA_DB_CONNECTION_VERIFICATION_TIMEOUT) - == null ? 1 : Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.RETENTION_DATA_DB_CONNECTION_VERIFICATION_TIMEOUT).toString().trim()); - } - - /** - * Method to get isEnabled config for consent data retention feature. - * @return consent data retention is enabled - */ - public boolean isConsentDataRetentionEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.IS_CONSENT_DATA_RETENTION_ENABLED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_CONSENT_DATA_RETENTION_ENABLED).toString().trim())); - } - - - /** - * Method to get isEnabled config for consent data retention periodical job. - * @return consent data retention is enabled - */ - public boolean isRetentionDataDBSyncEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.IS_CONSENT_RETENTION_DATA_DB_SYNC_ENABLED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_CONSENT_RETENTION_DATA_DB_SYNC_ENABLED).toString().trim())); - } - - - /** - * Method to get configs for data retention db sync periodical job's cron value. - * @return data retention job's cron string - */ - public String getRetentionDataDBSyncCronExpression() { - - return getConfigElementFromKey(OpenBankingConstants.CONSENT_RETENTION_DATA_DB_SYNC_CRON) == null - ? OpenBankingConstants.DEFAULT_MIDNIGHT_CRON : - ((String) getConfigElementFromKey(OpenBankingConstants.CONSENT_RETENTION_DATA_DB_SYNC_CRON)).trim(); - } - - /** - * Truststore dynamic loading interval. - * - * @return truststore dynamic loading time in seconds - */ - public Long getTruststoreDynamicLoadingInterval() { - try { - Object truststoreDynamicLoadingInterval = - getConfigElementFromKey(OpenBankingConstants.TRUSTSTORE_DYNAMIC_LOADING_INTERVAL); - if (truststoreDynamicLoadingInterval != null) { - return Long.parseLong((String) truststoreDynamicLoadingInterval); - } else { - return Long.parseLong("86400"); - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the truststore dynamic loading interval " + - "value in open-banking.xml. " + e.getMessage()); - } - } - - /** - * Returns the revocation validators map. - *

- * The revocation validator map contains revocation type (OCSP/CRL) and its executing priority. - * The default priority value has set as 1 for OCSP type, as OCSP validation is faster than the CRL validation - * - * @return certificate revocation validators map - */ - public Map getCertificateRevocationValidators() { - return revocationValidators; - } - - public Map> getOpenBankingDCRRegistrationParams() { - return dcrRegistrationConfigs; - } - - public String getAuthServletExtension() { - return getConfigElementFromKey(OpenBankingConstants.AUTH_SERVLET_EXTENSION) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.AUTH_SERVLET_EXTENSION)).trim(); - } - - public String getCibaServletExtension() { - return getConfigElementFromKey(OpenBankingConstants.CIBA_SERVLET_EXTENSION) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.CIBA_SERVLET_EXTENSION)).trim(); - } - - public String getJWKSConnectionTimeOut() { - - return getConfigElementFromKey(OpenBankingConstants.DCR_JWKS_CONNECTION_TIMEOUT) == null ? "3000" : - ((String) getConfigElementFromKey(OpenBankingConstants.DCR_JWKS_CONNECTION_TIMEOUT)).trim(); - } - - public String getJWKSReadTimeOut() { - - return getConfigElementFromKey(OpenBankingConstants.DCR_JWKS_READ_TIMEOUT) == null ? "3000" : - ((String) getConfigElementFromKey(OpenBankingConstants.DCR_JWKS_READ_TIMEOUT)).trim(); - } - - public String getSPMetadataFilterExtension() { - return getConfigElementFromKey(OpenBankingConstants.SP_METADATA_FILTER_EXTENSION) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.SP_METADATA_FILTER_EXTENSION)).trim(); - } - - public Map> getAllowedScopes() { - return allowedScopes; - } - - public Map> getAllowedAPIs() { - return allowedAPIs; - } - - /** - * Method to get configs for periodical consent expiration job's cron value. - * @return consent expiration job's cron string - */ - public String getConsentExpiryCronExpression() { - - return getConfigElementFromKey(OpenBankingConstants.CONSENT_PERIODICAL_EXPIRATION_CRON) == null - ? OpenBankingConstants.DEFAULT_MIDNIGHT_CRON : - ((String) getConfigElementFromKey(OpenBankingConstants.CONSENT_PERIODICAL_EXPIRATION_CRON)).trim(); - } - - /** - * Method to get statue for expired consents. - * @return statue for expired consents - */ - public String getStatusWordingForExpiredConsents() { - - return getConfigElementFromKey(OpenBankingConstants.STATUS_FOR_EXPIRED_CONSENT) == null - ? OpenBankingConstants.DEFAULT_STATUS_FOR_EXPIRED_CONSENTS : - ((String) getConfigElementFromKey(OpenBankingConstants.STATUS_FOR_EXPIRED_CONSENT)).trim(); - } - - /** - * Method to get eligible statues for evaluate expiration logic. - * @return eligible statues for evaluate expiration logic - */ - public String getEligibleStatusesForConsentExpiry() { - - return getConfigElementFromKey(OpenBankingConstants.ELIGIBLE_STATUSES_FOR_CONSENT_EXPIRY) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.ELIGIBLE_STATUSES_FOR_CONSENT_EXPIRY)).trim(); - } - - /** - * Method to get isEnabled config for periodical consent expiration job. - * @return consent expiration job is enabled - */ - public boolean isConsentExpirationPeriodicalJobEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.IS_CONSENT_PERIODICAL_EXPIRATION_ENABLED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_CONSENT_PERIODICAL_EXPIRATION_ENABLED).toString().trim())); - } - - public boolean isConsentAmendmentHistoryEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.IS_CONSENT_AMENDMENT_HISTORY_ENABLED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_CONSENT_AMENDMENT_HISTORY_ENABLED).toString().trim())); - } - - public String getOBKeyManagerExtensionImpl() { - return getConfigElementFromKey(OpenBankingConstants.OB_KEYMANAGER_EXTENSION_IMPL) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.OB_KEYMANAGER_EXTENSION_IMPL)) - .trim(); - } - - /** - * ConnectionPool maximum connection count. - * - * @return maximum connections count, default value is 2000 - */ - public int getConnectionPoolMaxConnections() { - try { - Object maxConnectionsCount = - getConfigElementFromKey(OpenBankingConstants.CONNECTION_POOL_MAX_CONNECTIONS); - if (maxConnectionsCount != null) { - return Integer.parseInt(String.valueOf(maxConnectionsCount)); - } else { - return 2000; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the MaxConnections " + - "value in open-banking.xml. " + e.getMessage()); - } - } - - /** - * ConnectionPool maximum connection per route count. - * - * @return maximum connections per route value, default value is 1500 - */ - public int getConnectionPoolMaxConnectionsPerRoute() { - try { - Object maxConnectionsPerRouteCount = - getConfigElementFromKey(OpenBankingConstants.CONNECTION_POOL_MAX_CONNECTIONS_PER_ROUTE); - if (maxConnectionsPerRouteCount != null) { - return Integer.parseInt(String.valueOf(maxConnectionsPerRouteCount)); - } else { - return 1500; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the MaxConnectionsPerRoute " + - "value in open-banking.xml. " + e.getMessage()); - } - } - - private void buildServiceActivatorSubscribers() { - OMElement serviceActivatorElement = rootElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.SERVICE_ACTIVATOR_TAG)); - - if (serviceActivatorElement != null) { - OMElement subscribers = serviceActivatorElement.getFirstChildWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.SA_SUBSCRIBERS_TAG)); - - if (subscribers != null) { - Iterator subscriber = subscribers.getChildrenWithName( - new QName(OpenBankingConstants.OB_CONFIG_QNAME, OpenBankingConstants.SA_SUBSCRIBER_TAG)); - if (subscriber != null) { - while (subscriber.hasNext()) { - OMElement executorElement = subscriber.next(); - //Retrieve subscriber class name from service activator configs - final String subscriberClass = executorElement.getText(); - - if (!StringUtils.isEmpty(subscriberClass)) { - serviceActivatorSubscribers.add(subscriberClass); - } - } - } - } - } - } - - /** - * Returns a list of FQNs of the OBServiceObserver interface implementations. - * - * @return ServiceActivator subscribers FQNs. - */ - public List getServiceActivatorSubscribers() { - return serviceActivatorSubscribers; - } - - //Event notifications configurations. - public String getEventNotificationTokenIssuer() { - - return getConfigElementFromKey(OpenBankingConstants.TOKEN_ISSUER) == null ? "www.wso2.com" : - ((String) getConfigElementFromKey(OpenBankingConstants.TOKEN_ISSUER)).trim(); - } - - public int getNumberOfSetsToReturn() { - - return getConfigElementFromKey(OpenBankingConstants.MAX_SETS_TO_RETURN) == null ? 5 : - Integer.parseInt((String) getConfigElementFromKey(OpenBankingConstants.MAX_SETS_TO_RETURN)); - } - - public boolean isSubClaimIncluded() { - - return getConfigElementFromKey(OpenBankingConstants.IS_SUB_CLAIM_INCLUDED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_SUB_CLAIM_INCLUDED).toString().trim())); - } - - public boolean isToeClaimIncluded() { - return getConfigElementFromKey(OpenBankingConstants.IS_TOE_CLAIM_INCLUDED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_TOE_CLAIM_INCLUDED).toString().trim())); - } - - public boolean isTxnClaimIncluded() { - return getConfigElementFromKey(OpenBankingConstants.IS_TXN_CLAIM_INCLUDED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_TXN_CLAIM_INCLUDED).toString().trim())); - } - - /** - * Returns the expiry time for cache modification. - * - * @return String Expiry time. - */ - public String getCommonCacheModifiedExpiryTime() { - - return getConfigElementFromKey(OpenBankingConstants.COMMON_IDENTITY_CACHE_MODIFY_EXPIRY) == null ? "60" : - ((String) getConfigElementFromKey(OpenBankingConstants.COMMON_IDENTITY_CACHE_MODIFY_EXPIRY)).trim(); - } - - /** - * Returns the expiry time for cache access. - * - * @return String Expiry time. - */ - public String getCommonCacheAccessExpiryTime() { - return getConfigElementFromKey(OpenBankingConstants.COMMON_IDENTITY_CACHE_ACCESS_EXPIRY) == null ? "60" : - ((String) getConfigElementFromKey(OpenBankingConstants.COMMON_IDENTITY_CACHE_ACCESS_EXPIRY)).trim(); - } - - /** - * Alias of the signing certificate in Production Environment. - * - * @return signing certificate alias - */ - public String getOBIdnRetrieverSigningCertificateAlias() { - - return getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SIG_ALIAS) == null ? "wso2carbon" : - ((String) getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SIG_ALIAS)).trim(); - } - - /** - * Alias of the signing certificate in Sandbox Environment. - * - * @return signing certificate alias - */ - public String getOBIdnRetrieverSandboxSigningCertificateAlias() { - - return getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SANDBOX_SIG_ALIAS) == null ? "wso2carbon" : - ((String) getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SANDBOX_SIG_ALIAS)).trim(); - } - - /** - * Key ID of the public key of the corresponding private key used for signing. - * - * @return signing certificate Kid in Production environment - */ - public String getOBIdnRetrieverSigningCertificateKid() { - - return getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SIG_KID) == null ? "1234" : - ((String) getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SIG_KID)).trim(); - } - - /** - * Key ID of the public key of the corresponding private key used for signing. - * - * @return signing certificate Kid in sandbox environment - */ - public String getOBIdnRetrieverSandboxCertificateKid() { - - return getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SANDBOX_KID) == null ? "5678" : - ((String) getConfigElementFromKey(OpenBankingConstants.OB_IDN_RETRIEVER_SANDBOX_KID)).trim(); - } - - /** - * JWKS Retriever Size Limit for JWS Signature Handling. - * - * @return JWKS Retriever Size Limit - */ - public String getJwksRetrieverSizeLimit() { - - return getConfigElementFromKey(OpenBankingConstants.JWKS_RETRIEVER_SIZE_LIMIT) == null ? "51200" : - ((String) getConfigElementFromKey(OpenBankingConstants.JWKS_RETRIEVER_SIZE_LIMIT)).trim(); - } - - /** - * JWKS Retriever Connection Timeout for JWS Signature Handling. - * - * @return JWKS Retriever Connection Timeout - */ - public String getJwksRetrieverConnectionTimeout() { - - return getConfigElementFromKey(OpenBankingConstants.JWKS_RETRIEVER_CONN_TIMEOUT) == null ? "2000" : - ((String) getConfigElementFromKey(OpenBankingConstants.JWKS_RETRIEVER_CONN_TIMEOUT)).trim(); - } - - /** - * JWKS Retriever Read Timeout for JWS Signature Handling. - * - * @return JWKS Retriever Read Timeout - */ - public String getJwksRetrieverReadTimeout() { - - return getConfigElementFromKey(OpenBankingConstants.JWKS_RETRIEVER_READ_TIMEOUT) == null ? "2000" : - ((String) getConfigElementFromKey(OpenBankingConstants.JWKS_RETRIEVER_READ_TIMEOUT)).trim(); - } - - /** - * Check if Jws Signature Validation is enabled. - * - * @return if Jws Signature Validation is enabled - */ - public boolean isJwsSignatureValidationEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.JWS_SIG_VALIDATION_ENABLE) != null && - Boolean.parseBoolean(((String) getConfigElementFromKey(OpenBankingConstants.JWS_SIG_VALIDATION_ENABLE)) - .trim()); - } - - /** - * Check if Jws Response signing is enabled. - * - * @return if Jws message Response is enabled - */ - public boolean isJwsResponseSigningEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.JWS_RESP_SIGNING_ENABLE) != null && - Boolean.parseBoolean(((String) getConfigElementFromKey(OpenBankingConstants.JWS_RESP_SIGNING_ENABLE)) - .trim()); - } - - /** - * Jws Request Signing allowed algorithms. - * - * @return Jws Request Signing allowed algorithms - */ - public List getJwsRequestSigningAlgorithms() { - - Object allowedAlgorithmsElement = getConfigElementFromKey( - OpenBankingConstants.JWS_SIG_VALIDATION_ALGO) == null ? new String[] {"PS256"} : - (getConfigElementFromKey(OpenBankingConstants.JWS_SIG_VALIDATION_ALGO)); - List allowedAlgorithmsList = new ArrayList<>(); - if (allowedAlgorithmsElement instanceof ArrayList) { - allowedAlgorithmsList.addAll((ArrayList) allowedAlgorithmsElement); - } else if (allowedAlgorithmsElement instanceof String) { - allowedAlgorithmsList.add((String) allowedAlgorithmsElement); - } - return allowedAlgorithmsList.isEmpty() ? Arrays.asList("PS256") : allowedAlgorithmsList; - } - - /** - * Jws Response Signing allowed algorithm. - * - * @return Jws Response Signing allowed algorithm - */ - public String getJwsResponseSigningAlgorithm() { - - return getConfigElementFromKey(OpenBankingConstants.JWS_RESP_SIGNING_ALGO) == null ? "PS256" : - ((String) getConfigElementFromKey(OpenBankingConstants.JWS_RESP_SIGNING_ALGO)).trim(); - } - - public Map getAuthWorkerConfig() { - return authWorkerConfig; - } - - /** - * Method to check if the Dispute Resolution feature is enabled. - * @return true if Dispute Resolution is enabled. - */ - public boolean isDisputeResolutionEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.IS_DISPUTE_RESOLUTION_ENABLED) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.IS_DISPUTE_RESOLUTION_ENABLED).toString().trim())); - } - - /** - * Method to check if the Dispute Resolution feature is enabled for Non Error Scenarios. - * @return true if Dispute Resolution feature is enabled for Non Error scenarios - */ - public boolean isNonErrorDisputeDataPublishingEnabled() { - - return getConfigElementFromKey(OpenBankingConstants.PUBLISH_NON_ERROR_DISPUTE_DATA) == null ? false : - (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.PUBLISH_NON_ERROR_DISPUTE_DATA).toString().trim())); - } - - /** - * Method to get maximum length for publish response body in Dispute Resolution Feature. - * @return maximum length for response body. - */ - public int getMaxResponseBodyLength() { - - return getConfigElementFromKey(OpenBankingConstants.MAX_RESPONSE_BODY_LENGTH) - == null ? 4096 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.MAX_RESPONSE_BODY_LENGTH).toString().trim())); - } - - /** - * Method to get maximum length for publish request body in Dispute Resolution Feature. - * @return maximum length for request body. - */ - public int getMaxRequestBodyLength() { - - return getConfigElementFromKey(OpenBankingConstants.MAX_REQUEST_BODY_LENGTH) - == null ? 4096 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.MAX_REQUEST_BODY_LENGTH).toString().trim())); - } - - /** - *Method to get maximum length for publish headers in Dispute Resolution Feature. - * @return maximum length for headers. - */ - public int getMaxHeaderLength() { - - return getConfigElementFromKey(OpenBankingConstants.MAX_HEADER_LENGTH) - == null ? 2048 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.MAX_HEADER_LENGTH).toString().trim())); - } - - /** - * Method to determine real-time event notification feature is enabled or not from the configurations. - * - * @return boolean value indicating the state - */ - public boolean isRealtimeEventNotificationEnabled() { - return getConfigElementFromKey(OpenBankingConstants.REALTIME_EVENT_NOTIFICATION_ENABLED) != null - && (Boolean.parseBoolean(getConfigElementFromKey( - OpenBankingConstants.REALTIME_EVENT_NOTIFICATION_ENABLED).toString().trim())); - } - - /** - * Method to get periodic Cron expression config for realtime event notifications scheduler. - * - * @return String Cron expression to trigger the Cron job for real-time event notification - */ - public String getRealtimeEventNotificationSchedulerCronExpression() { - return getConfigElementFromKey(OpenBankingConstants.PERIODIC_CRON_EXPRESSION) - == null ? "0 0/1 0 ? * * *" : (String) getConfigElementFromKey( - OpenBankingConstants.PERIODIC_CRON_EXPRESSION); - } - - /** - * Method to get TIMEOUT_IN_SECONDS config for realtime event notifications. - * - * @return integer timeout for the HTTP Client's POST requests - */ - public int getRealtimeEventNotificationTimeoutInSeconds() { - return getConfigElementFromKey(OpenBankingConstants.TIMEOUT_IN_SECONDS) - == null ? 60 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.TIMEOUT_IN_SECONDS).toString().trim())); - } - - /** - * Method to get MAX_RETRIES config for realtime event notifications. - * - * @return integer maximum number of retries to the retry policy in real-time notification sender - */ - public int getRealtimeEventNotificationMaxRetries() { - return getConfigElementFromKey(OpenBankingConstants.MAX_RETRIES) - == null ? 5 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.MAX_RETRIES).toString().trim())); - } - - /** - * Method to get INITIAL_BACKOFF_TIME_IN_SECONDS config for realtime event notifications. - * - * @return integer start waiting time for the retry policy before the first retry - */ - public int getRealtimeEventNotificationInitialBackoffTimeInSeconds() { - return getConfigElementFromKey(OpenBankingConstants.INITIAL_BACKOFF_TIME_IN_SECONDS) - == null ? 60 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.INITIAL_BACKOFF_TIME_IN_SECONDS).toString().trim())); - } - - /** - * Method to get BACKOFF_FUNCTION config for realtime event notifications. - * Function name should be "EX", "CONSTANT" or "LINEAR". - * - * @return string indicating the retry function - */ - public String getRealtimeEventNotificationBackoffFunction() { - return getConfigElementFromKey(OpenBankingConstants.BACKOFF_FUNCTION) - == null ? "EX" : (String) getConfigElementFromKey( - OpenBankingConstants.BACKOFF_FUNCTION); - } - - /** - * Method to get CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS config for realtime event notifications. - * - * @return integer timeout to break the retrying process and make that notification as ERR - */ - public int getRealtimeEventNotificationCircuitBreakerOpenTimeoutInSeconds() { - return getConfigElementFromKey(OpenBankingConstants.CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS) - == null ? 600 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS).toString().trim())); - } - - /** - * Method to get EVENT_NOTIFICATION_THREADPOOL_SIZE config for realtime event notifications. - * - * @return integer fix size to set the Thread Pool size in the real-time event notification sender - */ - public int getEventNotificationThreadpoolSize() { - return getConfigElementFromKey(OpenBankingConstants.EVENT_NOTIFICATION_THREADPOOL_SIZE) - == null ? 20 : (Integer.parseInt(getConfigElementFromKey( - OpenBankingConstants.EVENT_NOTIFICATION_THREADPOOL_SIZE).toString().trim())); - } - - /** - * Method to get EVENT_NOTIFICATION_GENERATOR config for event notifications. - * - * @return String class name of the event notification generator to generate the event notification payload - */ - public String getEventNotificationGenerator() { - return getConfigElementFromKey(OpenBankingConstants.EVENT_NOTIFICATION_GENERATOR) == null ? - "com.wso2.openbanking.accelerator.event.notifications.service.service.DefaultEventNotificationGenerator" - : (String) getConfigElementFromKey(OpenBankingConstants.EVENT_NOTIFICATION_GENERATOR); - } - - /** - * Method to get REALTIME_EVENT_NOTIFICATION_REQUEST_GENERATOR config for realtime event notifications. - * - * @return String class path of the realtime event notification payload generator - */ - public String getRealtimeEventNotificationRequestGenerator() { - return getConfigElementFromKey(OpenBankingConstants.REALTIME_EVENT_NOTIFICATION_REQUEST_GENERATOR) == null ? - "com.wso2.openbanking.accelerator.event.notifications.service." + - "realtime.service.DefaultRealtimeEventNotificationRequestGenerator" - : (String) getConfigElementFromKey(OpenBankingConstants.REALTIME_EVENT_NOTIFICATION_REQUEST_GENERATOR); - } - - /** - * Method to get software environment identification SSA property name. - * - * @return String software environment identification SSA property name. - */ - public String getSoftwareEnvIdentificationSSAPropertyName() { - return getConfigElementFromKey(OpenBankingConstants.DCR_SOFTWARE_ENV_IDENTIFICATION_PROPERTY_NAME) == null ? - OpenBankingConstants.SOFTWARE_ENVIRONMENT : (String) getConfigElementFromKey( - OpenBankingConstants.DCR_SOFTWARE_ENV_IDENTIFICATION_PROPERTY_NAME); - } - - /** - * Method to get software environment identification value for sandbox in SSA. - * - * @return String software environment identification value for sandbox. - */ - public String getSoftwareEnvIdentificationSSAPropertyValueForSandbox() { - return getConfigElementFromKey(OpenBankingConstants.DCR_SOFTWARE_ENV_IDENTIFICATION_VALUE_FOR_SANDBOX) == null ? - "sandbox" : (String) getConfigElementFromKey( - OpenBankingConstants.DCR_SOFTWARE_ENV_IDENTIFICATION_VALUE_FOR_SANDBOX); - } - - /** - * Method to get software environment identification value for production in SSA. - * - * @return String software environment identification value for production. - */ - public String getSoftwareEnvIdentificationSSAPropertyValueForProduction() { - return getConfigElementFromKey( - OpenBankingConstants.DCR_SOFTWARE_ENV_IDENTIFICATION_VALUE_FOR_PRODUCTION) == null ? - "production" : (String) getConfigElementFromKey( - OpenBankingConstants.DCR_SOFTWARE_ENV_IDENTIFICATION_VALUE_FOR_PRODUCTION); - } - - /** - * Get config related for checking whether PSU is a federated user or not. - * - * @return Boolean value indicating whether PSU is a federated user or not - */ - public boolean isPSUFederated() { - - Object isPSUFederated = getConfigElementFromKey(OpenBankingConstants.IS_PSU_FEDERATED); - if (isPSUFederated != null) { - return Boolean.parseBoolean((String) isPSUFederated); - } else { - return false; - } - } - - /** - * Get Federated PSU IDP Name. - * - * @return String Federated IDP name - */ - public String getFederatedIDPName() { - - return getConfigElementFromKey(OpenBankingConstants.PSU_FEDERATED_IDP_NAME) == null ? "" : - ((String) getConfigElementFromKey(OpenBankingConstants.PSU_FEDERATED_IDP_NAME)).trim(); - } - - /** - * Method to get the value Idempotency enable configuration. - * @return Whether Idempotency is enabled or not - */ - public boolean isIdempotencyValidationEnabled() { - return getConfigElementFromKey(OpenBankingConstants.IDEMPOTENCY_IS_ENABLED) != null && - Boolean.parseBoolean(((String) - getConfigElementFromKey(OpenBankingConstants.IDEMPOTENCY_IS_ENABLED)).trim()); - } - - /** - * Method to get the value Idempotency allowed time configuration. - * @return Idempotency allowed time - */ - public String getIdempotencyAllowedTime() { - return getConfigElementFromKey(OpenBankingConstants.IDEMPOTENCY_ALLOWED_TIME) == null ? "1440" : - (String) getConfigElementFromKey(OpenBankingConstants.IDEMPOTENCY_ALLOWED_TIME); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigurationService.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigurationService.java deleted file mode 100644 index 0e526caa..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigurationService.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.config; - -import java.util.List; -import java.util.Map; - -/** - * Interface to expose Configurations as an OSGi Service. - */ -public interface OpenBankingConfigurationService { - - public Map getConfigurations(); - - public Map> getExecutors(); - - public Map> getDataPublishingStreams(); - - public Map> getDataPublishingValidationMap(); - - public Map> getDCRRegistrationConfigurations(); - - public Map> getAuthorizeSteps(); - - public Map> getAllowedScopes(); - - public Map> getAllowedAPIs(); - - public Map getAuthenticationWorkers(); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigurationServiceImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigurationServiceImpl.java deleted file mode 100644 index 00d0b929..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/OpenBankingConfigurationServiceImpl.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.config; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; -import java.util.Map; - -/** - * Implementation of Open Banking Configuration Service. - */ -public class OpenBankingConfigurationServiceImpl implements OpenBankingConfigurationService { - - private static final OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(); - private static final Log log = LogFactory.getLog(OpenBankingConfigurationServiceImpl.class); - - @Override - public Map getConfigurations() { - - return openBankingConfigParser.getConfiguration(); - } - - @Override - public Map> getExecutors() { - - return openBankingConfigParser.getOpenBankingExecutors(); - } - - @Override - public Map> getDataPublishingStreams() { - - return openBankingConfigParser.getDataPublishingStreams(); - } - - @Override - public Map> getDataPublishingValidationMap() { - - return openBankingConfigParser.getDataPublishingValidationMap(); - } - - @Override - public Map> getDCRRegistrationConfigurations() { - - return openBankingConfigParser.getOpenBankingDCRRegistrationParams(); - } - - @Override - public Map> getAuthorizeSteps() { - - return openBankingConfigParser.getConsentAuthorizeSteps(); - } - - @Override - public Map> getAllowedScopes() { - return openBankingConfigParser.getAllowedScopes(); - } - - @Override - public Map> getAllowedAPIs() { - return openBankingConfigParser.getAllowedAPIs(); - } - - @Override - public Map getAuthenticationWorkers() { - return openBankingConfigParser.getAuthWorkerConfig(); - } - - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/TextFileReader.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/TextFileReader.java deleted file mode 100644 index 790e3949..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/config/TextFileReader.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.config; - -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -/** - * Common class to read a text file. - */ -public class TextFileReader { - - private String directoryPath; - private Map files = new HashMap<>(); - private static volatile TextFileReader textFileReader; - private static final Log logger = LogFactory.getLog(TextFileReader.class); - private static final Object lock = new Object(); - - private TextFileReader() { - - } - - public static TextFileReader getInstance() { - - if (textFileReader == null) { - synchronized (lock) { - if (textFileReader == null) { - textFileReader = new TextFileReader(); - } - } - } - return textFileReader; - } - - public String getDirectoryPath() { - - return directoryPath; - } - - public void setDirectoryPath(String directoryPath) { - - this.directoryPath = directoryPath; - } - - /** - * To read the auth textFile from the given file path. - * - * @param fileName Path of the file. - * @return file content as a String - * @throws IOException IO Exception. - */ - @SuppressFBWarnings({"WEAK_FILENAMEUTILS", "PATH_TRAVERSAL_IN"}) - // Suppressed content - FilenameUtils.getName() - // Suppression reason - - // WEAK_FILENAMEUTILS - False positive: The vulnerability is fixed from Java 7 update 40 and Java 8+ versions - // PATH_TRAVERSAL_IN - False positive: The user input value is only filename and it is secured using - // FilenameUtils. This could be a true positive if directory path is sent - // as a user input in the future. - // Suppressed warning count - 2 - public String readFile(String fileName) throws IOException { - - String filePath; - if (files.containsKey(fileName)) { - return files.get(FilenameUtils.getName(fileName)); - } - if (StringUtils.isNotEmpty(directoryPath)) { - filePath = directoryPath + File.separator + FilenameUtils.getName(fileName); - } else { - filePath = CarbonUtils.getCarbonConfigDirPath() + File.separator + FilenameUtils.getName(fileName); - } - File file = new File(filePath); - if (file.exists()) { - try (InputStream resourceAsStream = new FileInputStream(filePath); - BufferedInputStream bufferedInputStream = new BufferedInputStream(resourceAsStream)) { - - StringBuilder resourceFile = new StringBuilder(); - int c; - while ((c = bufferedInputStream.read()) != -1) { - char val = (char) c; - resourceFile.append(val); - } - files.put(fileName, resourceFile.toString()); - if (logger.isDebugEnabled()) { - logger.debug("File " + fileName.replaceAll("[\r\n]", "") + "read and stored in memory"); - } - return resourceFile.toString(); - } - } - return ""; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/constant/OpenBankingConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/constant/OpenBankingConstants.java deleted file mode 100644 index f04b3229..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/constant/OpenBankingConstants.java +++ /dev/null @@ -1,272 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.constant; - - -/** - * Class containing the constants for Open Banking Common module. - */ -public class OpenBankingConstants { - - public static final String OB_CONFIG_FILE = "open-banking.xml"; - public static final String CARBON_HOME = "carbon.home"; - - public static final String OB_CONFIG_QNAME = "http://wso2.org/projects/carbon/open-banking.xml"; - public static final String GATEWAY_CONFIG_TAG = "Gateway"; - public static final String GATEWAY_EXECUTOR_CONFIG_TAG = "OpenBankingGatewayExecutors"; - public static final String EVENT_CONFIG_TAG = "Event"; - public static final String EVENT_EXECUTOR_CONFIG_TAG = "EventExecutors"; - public static final String EXECUTOR_CONFIG_TAG = "Executor"; - public static final String DCR_CONFIG_TAG = "DCR"; - public static final String DCR_REGISTRATION_CONFIG_TAG = "RegistrationRequestParams"; - public static final String DCR_REGISTRATION_PARAM_ALLOWED_VALUE_TAG = "AllowedValues"; - public static final String REGULATORY = "regulatory"; - public static final String DATA_PUBLISHING_CONFIG_TAG = "DataPublishing"; - public static final String THRIFT_CONFIG_TAG = "Thrift"; - public static final String STREAMS_CONFIG_TAG = "Streams"; - public static final String ATTRIBUTE_CONFIG_TAG = "Attribute"; - public static final String REQUIRED = "required"; - public static final String ATTRIBUTE_TYPE = "type"; - public static final String DEFAULT_MIDNIGHT_CRON = "0 0 0 * * ?"; - public static final String DEFAULT_STATUS_FOR_EXPIRED_CONSENTS = "Expired"; - public static final String DEFAULT_STATUS_FOR_REVOKED_CONSENTS = "Revoked"; - public static final String IS_CONSENT_REVOCATION_FLOW = "IS_CONSENT_REVOCATION_FLOW"; - - public static final String SIGNATURE_ALGORITHMS = "SignatureValidation.AllowedAlgorithms.Algorithm"; - public static final String AUTH_SERVLET_EXTENSION = "Identity.AuthenticationWebApp.ServletExtension"; - public static final String COMMON_IDENTITY_CACHE_ACCESS_EXPIRY = "Common.Identity.Cache.CacheAccessExpiry"; - public static final String COMMON_IDENTITY_CACHE_MODIFY_EXPIRY = "Common.Identity.Cache.CacheModifiedExpiry"; - public static final String JWKS_ENDPOINT_NAME = "DCR.JWKSEndpointName"; - public static final String SP_METADATA_FILTER_EXTENSION = - "Identity.ApplicationInformationEndpoint.SPMetadataFilterExtension"; - public static final String CIBA_SERVLET_EXTENSION = "Identity.CIBAAuthenticationEndpointWebApp.ServletExtension"; - public static final String DCR_JWKS_CONNECTION_TIMEOUT = "DCR.JWKS-Retriever.ConnectionTimeout"; - public static final String DCR_JWKS_READ_TIMEOUT = "DCR.JWKS-Retriever.ReadTimeout"; - public static final String DCR_USE_SOFTWAREID_AS_APPNAME = "DCR.UseSoftwareIdAsAppName"; - public static final String DCR_JWKS_NAME = "DCR.JWKSEndpointName"; - public static final String DCR_APPLICATION_NAME_KEY = "DCR.ApplicationName"; - public static final String OB_KM_NAME = "KeyManagerName"; - public static final String DCR_SOFTWARE_ENV_IDENTIFICATION_PROPERTY_NAME = - "DCR.RegistrationRequestParams.SoftwareEnvironmentIdentification.PropertyName"; - public static final String DCR_SOFTWARE_ENV_IDENTIFICATION_VALUE_FOR_SANDBOX = - "DCR.RegistrationRequestParams.SoftwareEnvironmentIdentification.PropertyValueForSandbox"; - public static final String DCR_SOFTWARE_ENV_IDENTIFICATION_VALUE_FOR_PRODUCTION = - "DCR.RegistrationRequestParams.SoftwareEnvironmentIdentification.PropertyValueForProduction"; - - public static final String APIM_APPCREATION = "DCR.APIMRESTEndPoints.AppCreation"; - public static final String APIM_KEYGENERATION = "DCR.APIMRESTEndPoints.KeyGeneration"; - public static final String APIM_GETAPIS = "DCR.APIMRESTEndPoints.RetrieveAPIS"; - public static final String APIM_SUBSCRIBEAPIS = "DCR.APIMRESTEndPoints.SubscribeAPIs"; - public static final String APIM_GETSUBSCRIPTIONS = "DCR.APIMRESTEndPoints.RetrieveSubscribedAPIs"; - public static final String REGULATORY_API_NAMES = "RegulatoryAPINames"; - public static final String API_NAME = "name"; - public static final String API_ROLE = "roles"; - public static final String API_ID = "id"; - public static final String API_LIST = "list"; - public static final String REGULATORY_API = "API"; - public static final String SOFTWARE_ROLES = "software_roles"; - public static final String SOFTWARE_STATEMENT = "software_statement"; - public static final String SOFTWARE_ID = "software_id"; - public static final String JWT_BODY = "body"; - public static final String SOFTWARE_ENVIRONMENT = "software_environment"; - public static final String TOKEN_ENDPOINT = "DCR.TokenEndpoint"; - public static final String STORE_HOSTNAME = "PublisherURL"; - - public static final String JDBC_PERSISTENCE_CONFIG = "JDBCPersistenceManager.DataSource.Name"; - public static final String DB_CONNECTION_VERIFICATION_TIMEOUT = - "JDBCPersistenceManager.ConnectionVerificationTimeout"; - public static final String JDBC_RETENTION_DATA_PERSISTENCE_CONFIG = - "JDBCRetentionDataPersistenceManager.DataSource.Name"; - public static final String RETENTION_DATA_DB_CONNECTION_VERIFICATION_TIMEOUT = - "JDBCRetentionDataPersistenceManager.ConnectionVerificationTimeout"; - - public static final String TRUSTSTORE_CONF_TYPE_DEFAULT = "JKS"; - public static final String CLIENT_CERT_CACHE = "ClientCertCache"; - public static final String OB_CACHE_MANAGER = "OB_CERTIFICATE_CACHE"; - public static final String CERTIFICATE_REVOCATION_VALIDATION_RETRY_COUNT = "Gateway" + - ".CertificateManagement.CertificateRevocationValidationRetryCount"; - public static final String CERTIFICATE_REVOCATION_VALIDATION_CONNECT_TIMEOUT = "Gateway" + - ".CertificateManagement.CertificateRevocationValidationConnectTimeout"; - public static final String CERTIFICATE_REVOCATION_VALIDATION_CONNECTION_REQUEST_TIMEOUT = "Gateway" + - ".CertificateManagement.CertificateRevocationValidationConnectionRequestTimeout"; - public static final String CERTIFICATE_REVOCATION_VALIDATION_SOCKET_TIMEOUT = "Gateway" + - ".CertificateManagement.CertificateRevocationValidationSocketTimeout"; - public static final String CERTIFICATE_REVOCATION_VALIDATION_ENABLED = "Gateway" + - ".CertificateManagement.CertificateRevocationValidationEnabled"; - public static final String CERTIFICATE_REVOCATION_VALIDATION_EXCLUDED_ISSUERS = "Gateway" + - ".CertificateManagement.RevocationValidationExcludedIssuers.IssuerDN"; - public static final String TPP_VALIDATION_SERVICE_IMPL_CLASS = "Gateway" + - ".TPPManagement.TPPValidation.ServiceImplClass"; - public static final String TPP_VALIDATION_ENABLED = "Gateway" + - ".TPPManagement.TPPValidation.Enabled"; - public static final String PSD2_ROLE_VALIDATION_ENABLED = "Gateway" + - ".TPPManagement.PSD2RoleValidation.Enabled"; - public static final String CERTIFICATE_REVOCATION_PROXY_ENABLED = "Gateway" + - ".CertificateManagement.CertificateRevocationProxy.Enabled"; - public static final String CERTIFICATE_REVOCATION_PROXY_HOST = "Gateway" + - ".CertificateManagement.CertificateRevocationProxy.ProxyHost"; - public static final String CERTIFICATE_REVOCATION_PROXY_PORT = "Gateway" + - ".CertificateManagement.CertificateRevocationProxy.ProxyPort"; - public static final String TRANSPORT_CERT_ISSUER_VALIDATION_ENABLED = "Gateway" + - ".CertificateManagement.TransportCertIssuerValidationEnabled"; - public static final String TRUSTSTORE_DYNAMIC_LOADING_INTERVAL = "Gateway" + - ".CertificateManagement.TrustStoreDynamicLoadingInterval"; - public static final String CLIENT_CERTIFICATE_CACHE_EXPIRY = "Gateway" + - ".CertificateManagement.ClientCertificateCacheExpiry"; - public static final String TPP_VALIDATION_CACHE_EXPIRY = "Gateway" + - ".TPPManagement.TPPValidationCacheExpiry"; - public static final String TPP_VALIDATION_SERVICE_AISP_SCOPE_REGEX = "Gateway" + - ".CertificateManagement.TPPValidationService.ScopeRegexPatterns.AISP"; - public static final String TPP_VALIDATION_SERVICE_PISP_SCOPE_REGEX = "Gateway" + - ".CertificateManagement.TPPValidationService.ScopeRegexPatterns.PISP"; - public static final String TPP_VALIDATION_SERVICE_CBPII_SCOPE_REGEX = "Gateway" + - ".CertificateManagement.TPPValidationService.ScopeRegexPatterns.CBPII"; - public static final String CLIENT_TRANSPORT_CERT_HEADER_NAME = "Gateway" + - ".CertificateManagement.ClientTransportCertHeaderName"; - public static final String URL_ENCODE_CLIENT_TRANSPORT_CERT_HEADER_ENABLED = "Gateway" + - ".CertificateManagement.UrlEncodeClientTransportCertHeaderEnabled"; - public static final int PAGINATION_LIMIT_DEFAULT = 25; - public static final int PAGINATION_OFFSET_DEFAULT = 0; - public static final String CONSENT_CONFIG_TAG = "Consent"; - public static final String AUTHORIZE_STEPS_CONFIG_TAG = "AuthorizeSteps"; - public static final String STEP_CONFIG_TAG = "Step"; - public static final String ALLOWED_SCOPES_CONFIG_TAG = "AllowedScopes"; - public static final String SCOPE_CONFIG_TAG = "Scope"; - public static final String REVOCATION_VALIDATORS_CONFIG_TAG = "RevocationValidators"; - public static final String REVOCATION_VALIDATOR_CONFIG_TAG = "RevocationValidator"; - public static final String TPP_MANAGEMENT_CONFIG_TAG = "TPPManagement"; - public static final String CONNECTION_POOL_MAX_CONNECTIONS = "HTTPConnectionPool.MaxConnections"; - public static final String CONNECTION_POOL_MAX_CONNECTIONS_PER_ROUTE = "HTTPConnectionPool.MaxConnectionsPerRoute"; - public static final String PUSH_AUTH_EXPIRY_TIME = "PushAuthorisation.ExpiryTime"; - public static final String PUSH_AUTH_REQUEST_URI_SUBSTRING = "PushAuthorisation.RequestUriSubString"; - - public static final String CONSENT_PERIODICAL_EXPIRATION_CRON = "Consent.PeriodicalExpiration.CronValue"; - public static final String STATUS_FOR_EXPIRED_CONSENT = "Consent.PeriodicalExpiration.ExpiredConsentStatusValue"; - public static final String IS_CONSENT_PERIODICAL_EXPIRATION_ENABLED = "Consent.PeriodicalExpiration.Enabled"; - public static final String IS_CONSENT_AMENDMENT_HISTORY_ENABLED = "Consent.AmendmentHistory.Enabled"; - public static final String ELIGIBLE_STATUSES_FOR_CONSENT_EXPIRY = - "Consent.PeriodicalExpiration.EligibleStatuses"; - public static final String CONSENT_ID_CLAIM_NAME = "Identity.ConsentIDClaimName"; - - public static final String EVENT_QUEUE_SIZE = "Event.QueueSize"; - public static final String EVENT_WORKER_THREAD_COUNT = "Event.WorkerThreadCount"; - public static final String EVENT_EXECUTOR = "Event.EventExecutor"; - - // Data Retention Constants - public static final String IS_CONSENT_DATA_RETENTION_ENABLED = "Consent.DataRetention.Enabled"; - public static final String IS_CONSENT_RETENTION_DATA_DB_SYNC_ENABLED = "Consent.DataRetention.DBSyncEnabled"; - public static final String CONSENT_RETENTION_DATA_DB_SYNC_CRON = "Consent.DataRetention.CronValue"; - - // Service Activator Constants - public static final String SERVICE_ACTIVATOR_TAG = "ServiceActivator"; - public static final String SA_SUBSCRIBERS_TAG = "Subscribers"; - public static final String SA_SUBSCRIBER_TAG = "Subscriber"; - - //JWS handling related constants - public static final String JWS_SIG_VALIDATION_ENABLE = "JwsSignatureConfiguration.SignatureValidation.Enable"; - public static final String JWS_SIG_VALIDATION_ALGO = - "JwsSignatureConfiguration.SignatureValidation.AllowedAlgorithms"; - public static final String JWS_RESP_SIGNING_ENABLE = "JwsSignatureConfiguration.ResponseSigning.Enable"; - public static final String JWS_RESP_SIGNING_ALGO = "JwsSignatureConfiguration.ResponseSigning.AllowedAlgorithm"; - - // Open Banking Identity Manager - public static final String OB_IDN_RETRIEVER_SIG_ALIAS = "OBIdentityRetriever.Server.SigningCertificateAlias"; - public static final String OB_IDN_RETRIEVER_SANDBOX_SIG_ALIAS = - "OBIdentityRetriever.Server.SandboxSigningCertificateAlias"; - public static final String OB_IDN_RETRIEVER_SIG_KID = "OBIdentityRetriever.Server.SigningCertificateKid"; - public static final String OB_IDN_RETRIEVER_SANDBOX_KID = "OBIdentityRetriever.Server.SandboxCertificateKid"; - public static final String JWKS_RETRIEVER_SIZE_LIMIT = "OBIdentityRetriever.JWKSRetriever.SizeLimit"; - public static final String JWKS_RETRIEVER_CONN_TIMEOUT = "OBIdentityRetriever.JWKSRetriever.ConnectionTimeout"; - public static final String JWKS_RETRIEVER_READ_TIMEOUT = "OBIdentityRetriever.JWKSRetriever.ReadTimeout"; - - // Key Manager Additional Property Configs - public static final String KEY_MANAGER_CONFIG_TAG = "KeyManager"; - public static final String KEY_MANAGER_ADDITIONAL_PROPERTIES_CONFIG_TAG = "KeyManagerAdditionalProperties"; - public static final String PROPERTY_CONFIG_TAG = "Property"; - public static final String OB_KEYMANAGER_EXTENSION_IMPL = - "KeyManager.KeyManagerExtensionImpl"; - - //OB Event Notifications Constants - public static final String TOKEN_ISSUER = "OBEventNotifications.TokenIssuer"; - public static final String MAX_SETS_TO_RETURN = "OBEventNotifications.NumberOfSetsToReturn"; - public static final String SIGNING_ALIAS = "OBEventNotifications.SigningAlias"; - public static final String IS_SUB_CLAIM_INCLUDED = "OBEventNotifications.PollingResponseParams.IsSubClaimAvailable"; - public static final String IS_TXN_CLAIM_INCLUDED = "OBEventNotifications.PollingResponseParams.IsTxnClaimAvailable"; - public static final String IS_TOE_CLAIM_INCLUDED = "OBEventNotifications.PollingResponseParams.IsToeClaimAvailable"; - public static final String EVENT_CREATION_HANDLER = "OBEventNotifications.EventCreationHandler"; - public static final String EVENT_POLLING_HANDLER = "OBEventNotifications.EventPollingHandler"; - public static final String EVENT_SUBSCRIPTION_HANDLER = "OBEventNotifications.EventSubscriptionHandler"; - public static final String EVENT_NOTIFICATION_GENERATOR = "OBEventNotifications.NotificationGenerator"; - public static final String AUTHENTICATION_WORKER_LIST_TAG = "AuthenticationWorkers"; - public static final String AUTHENTICATION_WORKER_TAG = "AuthenticationWorker"; - - // Dispute Resolution Implementation Constants - public static final String IS_DISPUTE_RESOLUTION_ENABLED = "DataPublishing.DisputeResolution.Enabled"; - public static final String PUBLISH_NON_ERROR_DISPUTE_DATA = "DataPublishing" + - ".DisputeResolution.PublishNonErrorDisputeResolutionData"; - public static final String MAX_REQUEST_BODY_LENGTH = "DataPublishing.DisputeResolution.MaxRequestBodyLength"; - public static final String MAX_RESPONSE_BODY_LENGTH = "DataPublishing.DisputeResolution.MaxResponseBodyLength"; - public static final String MAX_HEADER_LENGTH = "DataPublishing.DisputeResolution.MaxHeaderLength"; - public static final String DISPUTE_RESOLUTION_STREAM_NAME = "DisputeResolutionStream"; - public static final String DISPUTE_RESOLUTION_STREAM_VERSION = "1.0.0"; - public static final String REQUEST_BODY = "requestBody"; - public static final String HTTP_METHOD = "httpMethod"; - public static final String STATUS_CODE = "statusCode"; - public static final String RESPONSE_BODY = "responseBody"; - public static final String ELECTED_RESOURCE = "electedResource"; - public static final String HEADERS = "headers"; - public static final String TIMESTAMP = "timestamp"; - - public static final String CUTOFF_DATE_ENABLED = "ConsentManagement.PaymentRestrictions.CutOffDateTime.Enabled"; - public static final String CUTOFF_DATE_POLICY = "ConsentManagement.PaymentRestrictions.CutOffDateTime" + - ".CutOffDateTimePolicy"; - public static final String ZONE_ID = "ZoneId"; - public static final String DAILY_CUTOFF = "ConsentManagement.PaymentRestrictions.CutOffDateTime" + - ".DailyCutOffTime"; - public static final String EXPECTED_EXECUTION_TIME = "ConsentManagement.PaymentRestrictions.CutOffDateTime" + - ".ExpectedExecutionTime"; - public static final String EXPECTED_SETTLEMENT_TIME = "ConsentManagement.PaymentRestrictions.CutOffDateTime" + - ".ExpectedSettlementTime"; - - // Realtime Event Notification Constants - public static final String REALTIME_EVENT_NOTIFICATION_ENABLED = "RealtimeEventNotification.Enable"; - public static final String PERIODIC_CRON_EXPRESSION = "RealtimeEventNotification.PeriodicCronExpression"; - public static final String TIMEOUT_IN_SECONDS = "RealtimeEventNotification.TimeoutInSeconds"; - public static final String MAX_RETRIES = "RealtimeEventNotification.MaxRetries"; - public static final String INITIAL_BACKOFF_TIME_IN_SECONDS - = "RealtimeEventNotification.InitialBackoffTimeInSeconds"; - public static final String BACKOFF_FUNCTION = "RealtimeEventNotification.BackoffFunction"; - public static final String CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS - = "RealtimeEventNotification.CircuitBreakerOpenTimeoutInSeconds"; - public static final String EVENT_NOTIFICATION_THREADPOOL_SIZE - = "RealtimeEventNotification.EventNotificationThreadPoolSize"; - public static final String REALTIME_EVENT_NOTIFICATION_REQUEST_GENERATOR - = "RealtimeEventNotification.RequestGenerator"; - public static final String CONTENT_TYPE_TAG = "Content-Type"; - public static final String JSON_CONTENT_TYPE = "application/json"; - public static final String SP_API_PATH = "/stores/query"; - public static final String APP_NAME_CC = "appName"; - public static final String QUERY = "query"; - public static final String IS_PSU_FEDERATED = "PSUFederatedAuthentication.Enabled"; - public static final String PSU_FEDERATED_IDP_NAME = "PSUFederatedAuthentication.IDPName"; - public static final String IDEMPOTENCY_IS_ENABLED = "Consent.Idempotency.Enabled"; - public static final String IDEMPOTENCY_ALLOWED_TIME = "Consent.Idempotency.AllowedTimeDuration"; - public static final String DOT_SEPARATOR = "."; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/error/OpenBankingErrorCodes.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/error/OpenBankingErrorCodes.java deleted file mode 100644 index 1588349b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/error/OpenBankingErrorCodes.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.error; - -/** - * Class containing the error codes for Open Banking. - */ -public class OpenBankingErrorCodes { - - public static final String BAD_REQUEST_CODE = "400"; - public static final String UNAUTHORIZED_CODE = "401"; - public static final String FORBIDDEN_CODE = "403"; - public static final String NOT_FOUND_CODE = "404"; - public static final String NOT_ALLOWED_CODE = "405"; - public static final String NOT_ACCEPTABLE_CODE = "406"; - public static final String UNSUPPORTED_MEDIA_TYPE_CODE = "415"; - public static final String SERVER_ERROR_CODE = "500"; - - public static final String INVALID_GRANT_TYPE_CODE = "200001"; - public static final String CONSENT_VALIDATION_REQUEST_FAILURE = "200002"; - public static final String INVALID_MTLS_CERT_CODE = "200003"; - public static final String TPP_VALIDATION_FAILED_CODE = "200004"; - public static final String INVALID_SIGNATURE = "200005"; - public static final String SCP_USER_VALIDATION_FAILED_CODE = "200006"; - public static final String MISSING_MTLS_CERT_CODE = "200007"; - public static final String EXPIRED_MTLS_CERT_CODE = "200008"; - public static final String REVOKED_MTLS_CERT_CODE = "200009"; - public static final String INVALID_SIGNATURE_CODE = "200010"; - public static final String MISSING_CONTENT_TYPE = "200011"; - public static final String INVALID_CONTENT_TYPE = "200012"; - public static final String MISSING_REQUEST_PAYLOAD = "200013"; - public static final String INVALID_CHARS_IN_HEADER_ERROR = "200014"; - public static final String MISSING_HEADER_PARAM_CLIENT_ID = "200015"; - public static final String ERROR_IN_EVENT_POLLING_REQUEST = "200016"; - - // Error titles - public static final String UNSUPPORTED_MEDIA_TYPE = "Unsupported Media Type"; - - public static final String REGISTRATION_INTERNAL_ERROR = "Error occurred while registering application"; - public static final String REGISTATION_DELETE_ERROR = "Error occurred while deleting application"; - public static final String REGISTRATION_UPDATE_ERROR = "Error occurred while updating application"; - - public static final String EXECUTOR_JWS_SIGNATURE_NOT_FOUND = "Error occurred in JWS Executor"; - public static final String JWS_SIGNATURE_HANDLE_ERROR = "Error occurred while validating JWS Signature"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/DefaultOBEventExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/DefaultOBEventExecutor.java deleted file mode 100644 index 0c2540a3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/DefaultOBEventExecutor.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.event.executor; - -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; - -/** - * Open banking event executor default implementation. - */ -public class DefaultOBEventExecutor implements OBEventExecutor { - - @Override - public void processEvent(OBEvent obEvent) { - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBEventExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBEventExecutor.java deleted file mode 100644 index d2175cdb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBEventExecutor.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.event.executor; - -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; - -/** - * Open banking event executor interface. - */ -public interface OBEventExecutor { - - /** - * This method is used to process events. - * - * @param obEvent OBEvent which holds event related data - */ - public void processEvent(OBEvent obEvent); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBEventQueue.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBEventQueue.java deleted file mode 100644 index 5e45ffd8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBEventQueue.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.event.executor; - -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; - - -/** - * Open Banking event queue wrapper class wrapping the ArrayBlockingQueue. - */ -public class OBEventQueue { - - private static final Log log = LogFactory.getLog(OBEventQueue.class); - private final BlockingQueue eventQueue; - private final ExecutorService executorService; - - public OBEventQueue(int queueSize, int workerThreadCount) { - - // Note : Using a fixed worker thread pool and a bounded queue to control the load on the server - executorService = Executors.newFixedThreadPool(workerThreadCount); - eventQueue = new ArrayBlockingQueue<>(queueSize); - } - - public void put(OBEvent obEvent) { - - try { - if (eventQueue.offer(obEvent)) { - executorService.submit(new OBQueueWorker(eventQueue, executorService)); - } else { - log.error("Event queue is full. Starting to drop events."); - } - } catch (RejectedExecutionException e) { - log.warn("Task submission failed. Task queue might be full", e); - } - } - - @Override - protected void finalize() throws Throwable { - executorService.shutdown(); - super.finalize(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBQueueWorker.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBQueueWorker.java deleted file mode 100644 index 09aa7f45..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/OBQueueWorker.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.event.executor; - -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import com.wso2.openbanking.accelerator.common.internal.OpenBankingCommonDataHolder; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.stream.Collectors; - -/** - * Open Banking Queue worker implementation to execute events in queue. - */ -public class OBQueueWorker implements Runnable { - - private BlockingQueue eventQueue; - private ExecutorService executorService; - private static final Log log = LogFactory.getLog(OBQueueWorker.class); - - public OBQueueWorker(BlockingQueue queue, ExecutorService executorService) { - - this.eventQueue = queue; - this.executorService = executorService; - } - - @Override - public void run() { - - ThreadPoolExecutor threadPoolExecutor = ((ThreadPoolExecutor) executorService); - - do { - OBEvent event = eventQueue.poll(); - if (event != null) { - Map obEventExecutors = OpenBankingCommonDataHolder.getInstance().getOBEventExecutors(); - List executorList = obEventExecutors.keySet().stream() - .map(integer -> (OBEventExecutor) OpenBankingUtils - .getClassInstanceFromFQN(obEventExecutors.get(integer))).collect(Collectors.toList()); - for (OBEventExecutor obEventExecutor : executorList) { - obEventExecutor.processEvent(event); - } - } else { - log.error("OB Event is null"); - } - } while (threadPoolExecutor.getActiveCount() == 1 && eventQueue.size() != 0); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/model/OBEvent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/model/OBEvent.java deleted file mode 100644 index 30db41b0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/event/executor/model/OBEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.event.executor.model; - -import java.util.Map; - -/** - * Open Banking event model class. - */ -public class OBEvent { - - private String eventType; - private Map eventData; - - public OBEvent(String eventType, Map eventData) { - - this.eventType = eventType; - this.eventData = eventData; - } - - public String getEventType() { - - return eventType; - } - - public Map getEventData() { - - return eventData; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/CertificateValidationException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/CertificateValidationException.java deleted file mode 100644 index 4f13b630..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/CertificateValidationException.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.exception; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; - -/** - * Certificate Validation exception class. - */ -public class CertificateValidationException extends Exception { - - private String errorCode; - private String errorPayload; - - public CertificateValidationException(String message) { - - super(message); - this.errorCode = OpenBankingErrorCodes.INVALID_MTLS_CERT_CODE; - this.errorPayload = ""; - } - - public CertificateValidationException(String message, String errorCode, String errorPayload) { - - super(message); - this.errorCode = errorCode; - this.errorPayload = errorPayload; - } - - public CertificateValidationException(String message, Throwable cause) { - - super(message, cause); - } - - public CertificateValidationException(Throwable cause, String errorCode, String errorPayload) { - - super(cause); - this.errorCode = errorCode; - this.errorPayload = errorPayload; - } - - public CertificateValidationException(String message, Throwable cause, String errorCode, String errorPayload) { - - super(message, cause); - this.errorCode = errorCode; - this.errorPayload = errorPayload; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - - public String getErrorPayload() { - - return errorPayload; - } - - public void setErrorPayload(String errorPayload) { - - this.errorPayload = errorPayload; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/ConsentManagementException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/ConsentManagementException.java deleted file mode 100644 index 308b762d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/ConsentManagementException.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.exception; - -/** - * Used for handling exceptions in consent management component. - */ -public class ConsentManagementException extends OpenBankingException { - - public ConsentManagementException(String message) { - super(message); - } - - public ConsentManagementException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/ConsentManagementRuntimeException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/ConsentManagementRuntimeException.java deleted file mode 100644 index b43ba5b6..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/ConsentManagementRuntimeException.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.exception; - -/** - * Used for runtime exceptions in consent management component. - */ -public class ConsentManagementRuntimeException extends OpenBankingRuntimeException { - - public ConsentManagementRuntimeException(String errorCode, Throwable cause) { - - super(errorCode, cause); - } - - public ConsentManagementRuntimeException(String errorCode) { - - super(errorCode); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OBThrottlerException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OBThrottlerException.java deleted file mode 100644 index 78d0485e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OBThrottlerException.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.exception; - -/** - * Used for handling exceptions in ob throttler component. - */ -public class OBThrottlerException extends OpenBankingException { - - public OBThrottlerException(String message) { - - super(message); - } - - public OBThrottlerException(String message, Throwable e) { - - super(message, e); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OpenBankingException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OpenBankingException.java deleted file mode 100644 index 2dbf5362..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OpenBankingException.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.exception; - -/** - * Used for exceptions in Open Banking components. - */ -public class OpenBankingException extends Exception { - - public OpenBankingException(String message) { - super(message); - } - - public OpenBankingException(String message, Throwable e) { - super(message, e); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OpenBankingRuntimeException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OpenBankingRuntimeException.java deleted file mode 100644 index ad1effc2..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/OpenBankingRuntimeException.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.exception; - -/** - * Used for creating runtime exceptions for Open-banking modules. - */ -public class OpenBankingRuntimeException extends RuntimeException { - - private static final long serialVersionUID = -5686395831712095972L; - private String errorCode; - - public OpenBankingRuntimeException(String errorCode, Throwable cause) { - - super(cause); - this.errorCode = errorCode; - } - - public OpenBankingRuntimeException(String errorCode) { - super(); - this.errorCode = errorCode; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/TPPValidationException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/TPPValidationException.java deleted file mode 100644 index bca1a9a5..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/exception/TPPValidationException.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.exception; - -/** - * TPPValidationException class. - */ -public class TPPValidationException extends Exception { - - public TPPValidationException(String message) { - super(message); - } - - public TPPValidationException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/ApplicationIdentityService.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/ApplicationIdentityService.java deleted file mode 100644 index 8dd7171a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/ApplicationIdentityService.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity; - -import com.nimbusds.jose.jwk.JWKSet; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.identity.cache.JWKSetCache; -import com.wso2.openbanking.accelerator.common.identity.cache.JWKSetCacheKey; -import com.wso2.openbanking.accelerator.common.identity.retriever.JWKRetriever; -import org.apache.commons.lang.StringUtils; - -import java.net.URL; - -/** - * Class to handle retrieving JWKSet from jwksUri. - */ -public class ApplicationIdentityService { - - /** - * Get JWKSet for application. - * First checks to get from cache, else retrieve the JWKSet from the URL by calling - * a method in JWKRetriever - * @param applicationName Application Name - * @param jwksUrl URL of the JWKSet - * @param useCache Use cache or not - * @return JWKSet - * @throws OpenBankingException if an error occurs while retrieving the JWKSet - */ - public JWKSet getPublicJWKSet(String applicationName, URL jwksUrl, - boolean useCache) throws OpenBankingException { - - if (StringUtils.isEmpty(applicationName)) { - throw new OpenBankingException("Application Name is required"); - } - - // Get JWK Set - if (useCache) { - JWKSetCache jwkSetCache = new JWKSetCache(); - try { - return jwkSetCache.getFromCacheOrRetrieve(JWKSetCacheKey.of(applicationName), - () -> new JWKRetriever().updateJWKSetFromURL(jwksUrl)); - } catch (OpenBankingException e) { - throw new OpenBankingException(String.format("Unable to retrieve JWKSet for %s", - applicationName), e); - } - } else { - return new JWKRetriever().updateJWKSetFromURL(jwksUrl); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/IdentityConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/IdentityConstants.java deleted file mode 100644 index 5f06d6c0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/IdentityConstants.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.Optional; - -/** - * Constants required for Server Identity Retriever. - */ -public class IdentityConstants { - - public static final String PRODUCTION = "PRODUCTION"; - public static final String SANDBOX = "SANDBOX"; - - public static final String KEYSTORE_LOCATION_CONF_KEY = "Security.KeyStore.Location"; - public static final String KEYSTORE_PASS_CONF_KEY = "Security.KeyStore.Password"; - - /** - * CertificateType enum. - */ - public enum CertificateType { - TRANSPORT, SIGNING - } - - /** - * EnvironmentType enum. - */ - public enum EnvironmentType { - SANDBOX, PRODUCTION, DEFAULT - } - - /** - * Use values for JWKS key set retrieval. - * - * Default values defined by specification - * @see RFC7517 Key Use Values - */ - public static final Map USE_TYPE_VALUE_MAP; - - static { - Map useMap = new EnumMap<>(CertificateType.class); - - useMap.put(CertificateType.SIGNING, new String[]{"sig"}); - useMap.put(CertificateType.TRANSPORT, new String[]{"enc", "tls"}); - - USE_TYPE_VALUE_MAP = Collections.unmodifiableMap(useMap); - } - - /** - * Custom Configurations. - * defines and loads custom configurations from xml. - */ - public static final Optional PRIMARY_SIGNING_CERT_ALIAS; - public static final Optional SANDBOX_SIGNING_CERT_ALIAS; - public static final Optional PRIMARY_SIGNING_CERT_KID; - public static final Optional SANDBOX_SIGNING_CERT_KID; - - static { - - PRIMARY_SIGNING_CERT_ALIAS = Optional - .ofNullable(OpenBankingConfigParser.getInstance().getOBIdnRetrieverSigningCertificateAlias()); - SANDBOX_SIGNING_CERT_ALIAS = Optional - .ofNullable(OpenBankingConfigParser.getInstance().getOBIdnRetrieverSandboxSigningCertificateAlias()); - PRIMARY_SIGNING_CERT_KID = Optional - .ofNullable(OpenBankingConfigParser.getInstance().getOBIdnRetrieverSigningCertificateKid()); - SANDBOX_SIGNING_CERT_KID = Optional - .ofNullable(OpenBankingConfigParser.getInstance().getOBIdnRetrieverSandboxCertificateKid()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/JWKSetCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/JWKSetCache.java deleted file mode 100644 index 0be4a853..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/JWKSetCache.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity.cache; - -import com.nimbusds.jose.jwk.JWKSet; -import com.wso2.openbanking.accelerator.common.identity.cache.base.OpenBankingIdentityBaseCache; - -/** - * Cache Manager for Public Certificates. - */ -public class JWKSetCache extends OpenBankingIdentityBaseCache { - - private static final String DEFAULT_CACHE_NAME = "OB_IDN_JWKS_CACHE"; - - public JWKSetCache() { - - super(DEFAULT_CACHE_NAME); - } - - public JWKSetCache(String cacheName) { - - super(cacheName); - } - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/JWKSetCacheKey.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/JWKSetCacheKey.java deleted file mode 100644 index 87d18af7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/JWKSetCacheKey.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCacheKey; - -import java.io.Serializable; -import java.util.Objects; - -/** - * Cache Key for JWKSet cache. - */ -public class JWKSetCacheKey extends OpenBankingBaseCacheKey implements Serializable { - - static final long serialVersionUID = 42L; - private String applicationName; - - public JWKSetCacheKey(String applicationName) { - - this.applicationName = applicationName; - } - - public static JWKSetCacheKey of(String applicationName) { - - return new JWKSetCacheKey(applicationName); - } - - @Override - public boolean equals(Object o) { - - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - JWKSetCacheKey that = (JWKSetCacheKey) o; - return Objects.equals(applicationName, that.applicationName); - } - - @Override - public int hashCode() { - - return Objects.hash(applicationName); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/base/OpenBankingIdentityBaseCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/base/OpenBankingIdentityBaseCache.java deleted file mode 100644 index 2f8776da..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/cache/base/OpenBankingIdentityBaseCache.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity.cache.base; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCache; -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCacheKey; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.internal.OpenBankingCommonDataHolder; - -/** - * Cache definition to store objects in open banking iam component implementations. - * @param Extended Cache key - * @param Cache value - */ -public class OpenBankingIdentityBaseCache extends OpenBankingBaseCache { - - private static final String cacheName = "OPEN_BANKING_IDENTITY_CACHE"; - - private Integer accessExpiryMinutes; - private Integer modifiedExpiryMinutes; - - /** - * Initialize with unique cache name. - * @param cacheName Unique cache name - */ - public OpenBankingIdentityBaseCache(String cacheName) { - - super(cacheName); - this.accessExpiryMinutes = setAccessExpiryMinutes(); - this.modifiedExpiryMinutes = setModifiedExpiryMinutes(); - } - - @Override - public int getCacheAccessExpiryMinutes() { - return accessExpiryMinutes; - } - - @Override - public int getCacheModifiedExpiryMinutes() { - return modifiedExpiryMinutes; - } - - public int setAccessExpiryMinutes() { - - return OpenBankingCommonDataHolder.getInstance().getCommonCacheAccessExpiry(); - } - - public int setModifiedExpiryMinutes() { - - return OpenBankingCommonDataHolder.getInstance().getCommonCacheModifiedExpiry(); - } - - public V getFromCacheOrRetrieve(K key, OnDemandRetriever onDemandRetriever) throws OpenBankingException { - - try { - return super.getFromCacheOrRetrieve(key, onDemandRetriever); - } catch (OpenBankingException e) { - throw new OpenBankingException("Unable to retrieve from cache", e); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/JWKRetriever.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/JWKRetriever.java deleted file mode 100644 index f0eff1db..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/JWKRetriever.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity.retriever; - -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.util.DefaultResourceRetriever; -import com.nimbusds.jose.util.Resource; -import com.nimbusds.jose.util.ResourceRetriever; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.identity.ApplicationIdentityService; -import com.wso2.openbanking.accelerator.common.identity.cache.JWKSetCache; -import com.wso2.openbanking.accelerator.common.identity.cache.JWKSetCacheKey; - -import java.io.IOException; -import java.net.URL; -import java.text.ParseException; - -/** - * Retrieve JWK set using nimbus retriever. - */ -public class JWKRetriever { - - private volatile JWKRetriever instance = null; - - private static final int jwksSizeLimit; - private static final int jwksConnectionTimeout; - private static final int jwksReadTimeout; - - /** - * The JWK set retriever. - */ - private static final ResourceRetriever resourceRetriever; - - static { - - jwksSizeLimit = Integer.parseInt(OpenBankingConfigParser.getInstance().getJwksRetrieverSizeLimit()); - jwksConnectionTimeout = Integer.parseInt(OpenBankingConfigParser.getInstance() - .getJwksRetrieverConnectionTimeout()); - jwksReadTimeout = Integer.parseInt(OpenBankingConfigParser.getInstance().getJwksRetrieverReadTimeout()); - resourceRetriever = new DefaultResourceRetriever(jwksReadTimeout, jwksConnectionTimeout, jwksSizeLimit); - } - - /** - * Get instance of JWKRetriever. - * - * @return JWKRetriever instance - */ - public JWKRetriever getInstance() { - - if (instance == null) { - synchronized (this) { - if (instance == null) { - instance = new JWKRetriever(); - } - } - } - return instance; - } - - /** - * Get JWK Set from remote resource retriever. - * - * @param jwksURL jwksURL in URL format - * @return JWKSet - * @throws OpenBankingException if an error occurs while retrieving resource - */ - public JWKSet updateJWKSetFromURL(URL jwksURL) throws OpenBankingException { - - JWKSet jwkSet; - Resource res; - try { - res = resourceRetriever.retrieveResource(jwksURL); - } catch (IOException e) { - throw new OpenBankingException("Couldn't retrieve remote JWK set: " + e.getMessage(), e); - } - try { - jwkSet = JWKSet.parse(res.getContent()); - } catch (ParseException e) { - throw new OpenBankingException("Couldn't parse remote JWK set: " + e.getMessage(), e); - } - - return jwkSet; - } - - /** - * Get JWK Set from cache or retrieve from onDemand retriever. - * - * @param jwksURL jwksURL in URL format - * @param applicationName application name as a string - * @return jwkSet - * @throws OpenBankingException if an error occurs while getting JWK set - */ - public JWKSet getJWKSet(URL jwksURL , String applicationName) throws OpenBankingException { - - try { - JWKSetCache jwkSetCache = new JWKSetCache(); - ApplicationIdentityService applicationIdentityService = new ApplicationIdentityService(); - JWKSet jwkSet = jwkSetCache.getFromCacheOrRetrieve(JWKSetCacheKey.of(applicationName), () - ->applicationIdentityService.getPublicJWKSet( - applicationName, jwksURL, true)); - - if (jwkSet == null) { - jwkSet = updateJWKSetFromURL(jwksURL); - } - return jwkSet; - } catch (OpenBankingException e) { - throw new OpenBankingException("Couldn't get remote JWK set: " + e.getMessage(), e); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/ServerIdentityRetriever.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/ServerIdentityRetriever.java deleted file mode 100644 index 59d3f3b6..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/ServerIdentityRetriever.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity.retriever; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.identity.IdentityConstants; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; - -import java.security.Key; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.util.Optional; - -/** - * Utility to retrieve ASPSP certificates. - */ -public class ServerIdentityRetriever { - - private static KeyStore keyStore = null; - // Internal KeyStore Password. - private static char[] keyStorePassword; - - private static final Log log = LogFactory.getLog(ServerIdentityRetriever.class); - - static { - // Static Initialize Internal Keystore. - String keyStoreLocation = ServerConfiguration.getInstance() - .getFirstProperty(IdentityConstants.KEYSTORE_LOCATION_CONF_KEY); - String keyStorePassword = ServerConfiguration.getInstance() - .getFirstProperty(IdentityConstants.KEYSTORE_PASS_CONF_KEY); - - try { - ServerIdentityRetriever.keyStore = HTTPClientUtils.loadKeyStore(keyStoreLocation, keyStorePassword); - ServerIdentityRetriever.keyStorePassword = keyStorePassword.toCharArray(); - } catch (OpenBankingException e) { - log.error("Unable to load InternalKeyStore", e); - } - } - - /** - * Returns the signing key using the signing Certificate. - * @param certificateType Signing certificate - * @param environmentType Sandbox or Production environment - * @return Key The signing key - * @throws OpenBankingException throws at KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException - */ - public static Optional getPrimaryCertificate(IdentityConstants.CertificateType certificateType, - IdentityConstants.EnvironmentType environmentType) - throws OpenBankingException { - Optional certAlias; - - if (certificateType.equals(IdentityConstants.CertificateType.SIGNING)) { - - certAlias = getCertAlias(certificateType, environmentType); - - if (certAlias.isPresent()) { - try { - // The requested key, or - // null if the given alias does not exist or does not identify a key-related entry. - return Optional.of(keyStore.getKey(certAlias.get(), keyStorePassword)); - } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { - throw new OpenBankingException("Unable to retrieve certificate", e); - } - } - - } - return Optional.empty(); - } - - /** - * Returns signing key used at production environment. - * @param certificateType signing certificate - * @return Key signing key - * @throws OpenBankingException throws OpenBankingException - */ - public static Optional getPrimaryCertificate(IdentityConstants.CertificateType certificateType) - throws OpenBankingException { - - return getPrimaryCertificate(certificateType, IdentityConstants.EnvironmentType.PRODUCTION); - } - - /** - * Get certificate from keystore with the given alias. - * Used in toolkits to get public signing certificate from keystore to retrieve the issuer. - * - * @param alias alias of the signing certificate of the bank - * @return signing certificate - * @throws KeyStoreException throw a generic KeyStore exception - */ - public static Certificate getCertificate(String alias) throws KeyStoreException { - - return keyStore.getCertificate(alias); - } - - /** - * Returns Signing certificate alias at Production environment. - * @param certificateType Signing - * @return String Certificate alias - * @throws OpenBankingException when there is an exception while retrieving the alias - */ - public static Optional getCertAlias(IdentityConstants.CertificateType certificateType) - throws OpenBankingException { - return getCertAlias(certificateType, IdentityConstants.EnvironmentType.PRODUCTION); - } - - /** - * Returns Signing certificate alias. - * @param certificateType signing - * @param environmentType Production or Sandbox - * @return Signing certificate alias - * @throws OpenBankingException throws OpenBankingException - */ - public static Optional getCertAlias(IdentityConstants.CertificateType certificateType, - IdentityConstants.EnvironmentType environmentType) - throws OpenBankingException { - Optional certAlias = Optional.empty(); - - if (certificateType.equals(IdentityConstants.CertificateType.SIGNING)) { - if (keyStore == null) { - throw new OpenBankingException("Internal Key Store not initialized"); - } - - if (environmentType == IdentityConstants.EnvironmentType.SANDBOX) { - certAlias = IdentityConstants.SANDBOX_SIGNING_CERT_ALIAS; - } else { - certAlias = IdentityConstants.PRIMARY_SIGNING_CERT_ALIAS; - } - } - return certAlias; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/sp/CommonServiceProviderRetriever.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/sp/CommonServiceProviderRetriever.java deleted file mode 100644 index 0281130d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/identity/retriever/sp/CommonServiceProviderRetriever.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.identity.retriever.sp; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.internal.OpenBankingCommonDataHolder; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; - -import java.util.Arrays; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * Class to retrieve Service Provider Data. - */ -public class CommonServiceProviderRetriever { - - private static final Log log = LogFactory.getLog(CommonServiceProviderRetriever.class); - - /** - * Utility method get the application property from SP Meta Data. - * - * @param clientId ClientId of the application - * @param property Property of the application - * @return the property value from SP metadata - * @throws OpenBankingException if an error occurs while retrieving the property - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public String getAppPropertyFromSPMetaData(String clientId, String property) throws OpenBankingException { - - String spProperty = null; - - if (StringUtils.isNotEmpty(clientId)) { - Optional serviceProvider; - try { - serviceProvider = Optional.ofNullable(OpenBankingCommonDataHolder.getInstance() - .getApplicationManagementService().getServiceProviderByClientId(clientId, - IdentityApplicationConstants.OAuth2.NAME, - ServiceProviderUtils.getSpTenantDomain(clientId))); - if (serviceProvider.isPresent()) { - spProperty = Arrays.stream(serviceProvider.get().getSpProperties()) - .collect(Collectors.toMap(ServiceProviderProperty::getName, - ServiceProviderProperty::getValue)).get(property); - } - } catch (IdentityApplicationManagementException e) { - log.error(String.format("Error occurred while retrieving OAuth2 application data for clientId %s", - clientId.replaceAll("[\r\n]" , "")) , e); - throw new OpenBankingException("Error occurred while retrieving OAuth2 application data for clientId" - , e); - } - } else { - log.error("Client id not found"); - throw new OpenBankingException("Client id not found"); - } - - return spProperty; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/internal/OpenBankingCommonDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/internal/OpenBankingCommonDataHolder.java deleted file mode 100644 index 44dfd82f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/internal/OpenBankingCommonDataHolder.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; - -import java.util.Map; - -/** - * Data holder for Open Banking Common module. - */ -public class OpenBankingCommonDataHolder { - - private static volatile OpenBankingCommonDataHolder instance; - private OBEventQueue obEventQueue; - private Map obEventExecutors; - private ApplicationManagementService applicationManagementService; - private int commonCacheAccessExpiry; - private int commonCacheModifiedExpiry; - - private OpenBankingCommonDataHolder() { - - int queueSize = Integer.parseInt((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.EVENT_QUEUE_SIZE)); - int workerThreadCount = - Integer.parseInt((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.EVENT_WORKER_THREAD_COUNT)); - obEventQueue = new OBEventQueue(queueSize, workerThreadCount); - obEventExecutors = OpenBankingConfigParser.getInstance().getOpenBankingEventExecutors(); - setCommonCacheAccessExpiry((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.COMMON_IDENTITY_CACHE_ACCESS_EXPIRY)); - setCommonCacheModifiedExpiry((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.COMMON_IDENTITY_CACHE_MODIFY_EXPIRY)); - } - - public static OpenBankingCommonDataHolder getInstance() { - - if (instance == null) { - synchronized (OpenBankingCommonDataHolder.class) { - if (instance == null) { - instance = new OpenBankingCommonDataHolder(); - } - } - } - return instance; - } - - public Map getOBEventExecutors() { - - return obEventExecutors; - } - - public void setOBEventExecutor(Map obEventExecutors) { - - this.obEventExecutors = obEventExecutors; - } - - public OBEventQueue getOBEventQueue() { - - return obEventQueue; - } - - public void setOBEventQueue(OBEventQueue obEventQueue) { - - this.obEventQueue = obEventQueue; - } - - /** - * To get the instance of {@link ApplicationManagementService}. - * - * @return applicationManagementService - */ - public ApplicationManagementService getApplicationManagementService() { - - return applicationManagementService; - } - - /** - * To set the ApplicationManagementService. - * - * @param applicationManagementService instance of {@link ApplicationManagementService} - */ - public void setApplicationManagementService(ApplicationManagementService applicationManagementService) { - - this.applicationManagementService = applicationManagementService; - } - - public int getCommonCacheAccessExpiry() { - - return commonCacheAccessExpiry; - } - - public void setCommonCacheAccessExpiry(String expTime) { - - this.commonCacheAccessExpiry = expTime == null ? 60 : Integer.parseInt(expTime); - } - - public int getCommonCacheModifiedExpiry() { - - return commonCacheModifiedExpiry; - } - - public void setCommonCacheModifiedExpiry(String expTime) { - - this.commonCacheModifiedExpiry = expTime == null ? 60 : Integer.parseInt(expTime); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/internal/OpenBankingCommonServiceComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/internal/OpenBankingCommonServiceComponent.java deleted file mode 100644 index d34bc661..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/internal/OpenBankingCommonServiceComponent.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationServiceImpl; -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; - -/** - * Method to register Open Banking common OSGi Services. - */ -@Component( - name = "com.wso2.open.banking.common", - immediate = true -) -public class OpenBankingCommonServiceComponent { - - private static final Log log = LogFactory.getLog(OpenBankingCommonServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - OpenBankingConfigurationService openBankingConfigurationService - = new OpenBankingConfigurationServiceImpl(); - OpenBankingCommonDataHolder openBankingCommonDataHolder = OpenBankingCommonDataHolder.getInstance(); - context.getBundleContext().registerService(OpenBankingConfigurationService.class.getName(), - openBankingConfigurationService, null); - context.getBundleContext().registerService(OBEventQueue.class.getName(), - openBankingCommonDataHolder.getOBEventQueue(), null); - context.getBundleContext().registerService(ApplicationManagementService.class, - ApplicationManagementService.getInstance(), null); - - log.debug("Open banking common component is activated successfully"); - } - - @Reference( - name = "ApplicationManagementService", - service = ApplicationManagementService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetApplicationManagementService" - ) - protected void setApplicationManagementService(ApplicationManagementService mgtService) { - - OpenBankingCommonDataHolder.getInstance().setApplicationManagementService(mgtService); - } - - protected void unsetApplicationManagementService(ApplicationManagementService mgtService) { - - OpenBankingCommonDataHolder.getInstance().setApplicationManagementService(null); - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - log.debug("Open banking common component is deactivated"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/model/PSD2RoleEnum.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/model/PSD2RoleEnum.java deleted file mode 100644 index 441dacef..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/model/PSD2RoleEnum.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.model; - -/** - * PSD2 role enum class. - */ -public enum PSD2RoleEnum { - - AISP("aisp"), PISP("pisp"), CBPII("cbpii"), ASPSP("aspsp"); - - private String value; - - PSD2RoleEnum(String value) { - - this.value = value; - } - - public String toString() { - - return value; - } - - public static PSD2RoleEnum fromValue(String text) { - - for (PSD2RoleEnum apiTypeEnum : PSD2RoleEnum.values()) { - if (String.valueOf(apiTypeEnum.value).equalsIgnoreCase(text)) { - return apiTypeEnum; - } - } - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/persistence/JDBCPersistenceManager.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/persistence/JDBCPersistenceManager.java deleted file mode 100644 index 2f947f0c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/persistence/JDBCPersistenceManager.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.persistence; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementRuntimeException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -/** - * This class is used for handling Open banking consent data persistence in the JDBC Store. During the server - * start-up, it checks whether the database is created, if not it creates one. It reads the data source properties - * from the open-banking.xml. This is implemented as a singleton. An instance of this class can be obtained through - * JDBCPersistenceManager.getInstance() method. - */ -public class JDBCPersistenceManager { - - private static volatile JDBCPersistenceManager instance; - private static volatile DataSource dataSource; - private static Log log = LogFactory.getLog(JDBCPersistenceManager.class); - - private JDBCPersistenceManager() { - - initDataSource(); - } - - /** - * Get an instance of the JDBCPersistenceManager. It implements a double checked locking initialization. - * - * @return JDBCPersistenceManager instance - */ - public static synchronized JDBCPersistenceManager getInstance() { - if (instance == null) { - synchronized (JDBCPersistenceManager.class) { - if (instance == null) { - instance = new JDBCPersistenceManager(); - } - } - } - return instance; - } - - /** - * Initialize the data source. - */ - @SuppressFBWarnings("LDAP_INJECTION") - // Suppressed content - context.lookup(dataSourceName) - // Suppression reason - False Positive : Since the dataSourceName is taken from the deployment.toml, it can be - // trusted - // Suppressed warning count - 1 - private void initDataSource() { - - if (dataSource != null) { - return; - } - synchronized (JDBCPersistenceManager.class) { - try { - String dataSourceName = OpenBankingConfigParser.getInstance().getDataSourceName(); - if (StringUtils.isNotBlank(dataSourceName)) { - Context context = new InitialContext(); - dataSource = (DataSource) context.lookup(dataSourceName); - } else { - throw new ConsentManagementRuntimeException("Persistence Manager configuration for Open Banking " + - "is not available in open-banking.xml file. Terminating the JDBC persistence manager " + - "initialization."); - } - } catch (NamingException e) { - throw new ConsentManagementRuntimeException("Error when looking up the Consent Management Data Source.", - e); - } - } - } - - /** - * Returns an database connection for Consent Management data source. - * - * @return Database connection. - * @throws ConsentManagementRuntimeException Exception occurred when getting the data source. - */ - public Connection getDBConnection() throws ConsentManagementRuntimeException { - - try { - Connection dbConnection = dataSource.getConnection(); - dbConnection.setAutoCommit(false); - log.debug("Returning database connection for Consent Management data source"); - return dbConnection; - } catch (SQLException e) { - throw new ConsentManagementRuntimeException("Error when getting a database connection object from the " + - "consent management data source.", e); - } - } - - /** - * Returns Consent Management data source. - * - * @return Data source. - */ - public DataSource getDataSource() { - - return dataSource; - } - - /** - * Revoke the transaction when catch then sql transaction errors. - * - * @param dbConnection database connection. - */ - public void rollbackTransaction(Connection dbConnection) { - - try { - if (dbConnection != null) { - dbConnection.rollback(); - } - } catch (SQLException e) { - log.error("An error occurred while rolling back transactions. ", e); - } - } - - /** - * Commit the transaction. - * - * @param dbConnection database connection. - */ - public void commitTransaction(Connection dbConnection) { - - try { - if (dbConnection != null) { - dbConnection.commit(); - } - } catch (SQLException e) { - log.error("An error occurred while commit transactions. ", e); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/persistence/JDBCRetentionDataPersistenceManager.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/persistence/JDBCRetentionDataPersistenceManager.java deleted file mode 100644 index 22060fc1..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/persistence/JDBCRetentionDataPersistenceManager.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.persistence; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementRuntimeException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -/** - * This class is used for handling open banking retention data (if enabled) persistence in the JDBC Store. - * During the server start-up, it checks whether the database is created, It reads the data source properties - * from the open-banking.xml. This is implemented as a singleton. An instance of this class can be obtained through - * JDBCRetentionDataPersistenceManager.getInstance() method. - */ -public class JDBCRetentionDataPersistenceManager { - - private static volatile JDBCRetentionDataPersistenceManager instance; - private static volatile DataSource dataSource; - private static Log log = LogFactory.getLog(JDBCRetentionDataPersistenceManager.class); - - private JDBCRetentionDataPersistenceManager() { - - initDataSource(); - } - - /** - * Get an instance of the JDBCRetentionDataPersistenceManager. It implements a double checked locking initialization - * - * @return JDBCRetentionDataPersistenceManager instance - */ - public static synchronized JDBCRetentionDataPersistenceManager getInstance() { - - if (instance == null) { - synchronized (JDBCRetentionDataPersistenceManager.class) { - if (instance == null) { - instance = new JDBCRetentionDataPersistenceManager(); - } - } - } - return instance; - } - - /** - * Initialize the data source. - */ - @SuppressFBWarnings("LDAP_INJECTION") - // Suppressed content - context.lookup(dataSourceName) - // Suppression reason - False Positive : Since the dataSourceName is taken from the deployment.toml, it can be - // trusted - // Suppressed warning count - 1 - private void initDataSource() { - - if (dataSource != null) { - return; - } - synchronized (JDBCRetentionDataPersistenceManager.class) { - try { - String dataSourceName = OpenBankingConfigParser.getInstance().getRetentionDataSourceName(); - if (StringUtils.isNotBlank(dataSourceName)) { - Context context = new InitialContext(); - dataSource = (DataSource) context.lookup(dataSourceName); - } else { - throw new ConsentManagementRuntimeException("Persistence Manager configuration for " + - "retention datasource is not available in open-banking.xml file. Terminating the " + - "JDBC retention data persistence manager initialization."); - } - } catch (NamingException e) { - throw new ConsentManagementRuntimeException("Error when looking up the Consent Retention " + - "Data Source.", e); - } - } - } - - /** - * Returns an database connection for retention data source. - * - * @return Database connection. - * @throws ConsentManagementRuntimeException Exception occurred when getting the data source. - */ - public Connection getDBConnection() throws ConsentManagementRuntimeException { - - try { - Connection dbConnection = dataSource.getConnection(); - dbConnection.setAutoCommit(false); - log.debug("Returning database connection for retention data source"); - return dbConnection; - } catch (SQLException e) { - throw new ConsentManagementRuntimeException("Error when getting a database connection object from the " + - "retention data source.", e); - } - } - - /** - * Returns retention data source. - * - * @return Data source. - */ - public DataSource getDataSource() { - - return dataSource; - } - - /** - * Revoke the transaction when catch then sql transaction errors. - * - * @param dbConnection database connection. - */ - public void rollbackTransaction(Connection dbConnection) { - - try { - if (dbConnection != null) { - dbConnection.rollback(); - } - } catch (SQLException e) { - log.error("An error occurred while rolling back transactions. ", e); - } - } - - /** - * Commit the transaction. - * - * @param dbConnection database connection. - */ - public void commitTransaction(Connection dbConnection) { - - try { - if (dbConnection != null) { - dbConnection.commit(); - } - } catch (SQLException e) { - log.error("An error occurred while commit transactions. ", e); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/AnalyticsLogsUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/AnalyticsLogsUtils.java deleted file mode 100644 index 8a8c64de..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/AnalyticsLogsUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Map; - -/** - * Open Banking common utility class to publish analytics logs. - */ -public class AnalyticsLogsUtils { - - private static final Log log = LogFactory.getLog(AnalyticsLogsUtils.class); - private static final String LOG_FORMAT = "Data Stream : %s , Data Stream Version : %s , Data : {\"payload\":%s}"; - private static final String DATA_PROCESSING_ERROR = "Error occurred while processing the analytics dataset"; - - /** - * Method to add analytics logs to the OB analytics log file. - * - * @param logFile Name of the logger which is used to log analytics data to the log file - * @param dataStream Name of the data stream to which the data belongs - * @param dataVersion Version of the data stream to which the data belongs - * @param analyticsData Data which belongs to the given data stream that needs to be logged via the given logger - * @throws OpenBankingException if an error occurs while processing the analytics data - */ - public static void addAnalyticsLogs(String logFile, String dataStream, String dataVersion, Map analyticsData) throws OpenBankingException { - Log customLog = LogFactory.getLog(logFile); - try { - customLog.info(String.format(LOG_FORMAT, dataStream, - dataVersion, new ObjectMapper().writeValueAsString(analyticsData))); - } catch (JsonProcessingException e) { - log.error(DATA_PROCESSING_ERROR); - throw new OpenBankingException(DATA_PROCESSING_ERROR, e); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/CarbonUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/CarbonUtils.java deleted file mode 100644 index d25f6461..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/CarbonUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import org.wso2.carbon.base.ServerConfiguration; - -import java.io.File; - -/** - * Utility Class for WSO2 Carbon related functions. - */ -public class CarbonUtils { - - private static final String HTTPS = "https://"; - private static final String COLON = ":"; - - /** - * Method to obtain config directory of any carbon product. - * - * @return String indicating the location of conf directory. - */ - public static String getCarbonConfigDirPath() { - - String carbonConfigDirPath = System.getProperty("carbon.config.dir.path"); - if (carbonConfigDirPath == null) { - carbonConfigDirPath = System.getenv("CARBON_CONFIG_DIR_PATH"); - if (carbonConfigDirPath == null) { - return getCarbonHome() + File.separator + "repository" + File.separator + "conf"; - } - } - return carbonConfigDirPath; - } - - /** - * Method to obtain home location of the carbon product. - * - * @return String indicating the home location of conf directory. - */ - public static String getCarbonHome() { - - String carbonHome = System.getProperty(OpenBankingConstants.CARBON_HOME); - if (carbonHome == null) { - carbonHome = System.getenv("CARBON_HOME"); - System.setProperty(OpenBankingConstants.CARBON_HOME, carbonHome); - } - return carbonHome; - } - - /** - * Method to obtain hostname of the carbon product. - * - * @return String indicating the hostname of the server. - */ - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - public static String getCarbonPort() { - - int offset = Integer.parseInt(ServerConfiguration.getInstance().getFirstProperty("Offset")); - return String.valueOf(9443 + offset); - } - - /** - * Method to obtain port of the carbon product. - * - * @return String indicating the port of the server. - */ - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - public static String getCarbonHostname() { - return ServerConfiguration.getInstance().getFirstProperty("HostName"); - } - - /** - * Method to obtain server url of the carbon product. - * - * @return String indicating the url of the server. - */ - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - public static String getCarbonServerUrl() { - return HTTPS + getCarbonHostname() + COLON + getCarbonPort(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/CertificateUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/CertificateUtils.java deleted file mode 100644 index 65906695..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/CertificateUtils.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.ByteArrayInputStream; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Base64; - -/** - * Common utilities related to Certificates. - */ -public class CertificateUtils { - - private static final Log log = LogFactory.getLog(CertificateUtils.class); - - private static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; - private static final String END_CERT = "-----END CERTIFICATE-----"; - private static final String X509_CERT_INSTANCE_NAME = "X.509"; - - /** - * Parse the certificate content. - * - * @param content the content to be passed - * @return the parsed certificate - * @throws OpenBankingException if an error occurs while parsing the certificate - */ - public static X509Certificate parseCertificate(String content) throws OpenBankingException { - - try { - if (StringUtils.isNotBlank(content)) { - // removing illegal base64 characters before decoding - content = removeIllegalBase64Characters(content); - byte[] bytes = Base64.getDecoder().decode(content); - - return (java.security.cert.X509Certificate) CertificateFactory.getInstance(X509_CERT_INSTANCE_NAME) - .generateCertificate(new ByteArrayInputStream(bytes)); - } - log.error("Certificate passed through the request is empty"); - return null; - } catch (CertificateException | IllegalArgumentException e) { - throw new OpenBankingException("Certificate passed through the request not valid", e); - } - } - - /** - * Remove illegal base64 characters from input string. - * - * @param value certificate as a string - * @return certificate without illegal base64 characters - */ - private static String removeIllegalBase64Characters(String value) { - if (value.contains(BEGIN_CERT) - && value.contains(END_CERT)) { - - // extracting certificate content - value = value.substring(value.indexOf(BEGIN_CERT) - + BEGIN_CERT.length(), - value.indexOf(END_CERT)); - } - // remove spaces, \r, \\r, \n, \\n, ], [ characters from certificate string - return value.replaceAll("\\\\r|\\\\n|\\r|\\n|\\[|]| ", StringUtils.EMPTY); - } - - /** - * Check whether the certificate is expired. - * - * @param peerCertificate the certificate to be checked - * @return true if the certificate is expired - */ - public static boolean isExpired(X509Certificate peerCertificate) { - try { - peerCertificate.checkValidity(); - } catch (CertificateException e) { - log.error("Certificate with the serial number " + - peerCertificate.getSerialNumber() + " issued by the CA " + - peerCertificate.getIssuerDN().toString() + " is expired. Caused by, " + e.getMessage()); - return true; - } - return false; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/DatabaseUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/DatabaseUtil.java deleted file mode 100644 index 727f9f6c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/DatabaseUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.common.persistence.JDBCRetentionDataPersistenceManager; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Utility class for database operations. - */ -public class DatabaseUtil { - - private static final Log log = LogFactory.getLog(DatabaseUtil.class); - - /** - * Get a database connection instance from the Consent Management Persistence Manager. - * - * @return Database Connection - * @throws OpenBankingRuntimeException Error when getting a database connection to Consent Management database - */ - public static Connection getDBConnection() throws OpenBankingRuntimeException { - - return JDBCPersistenceManager.getInstance().getDBConnection(); - } - - /** - * Get a database connection instance from the Retention Data Persistence Manager. - * - * @return Database Connection - * @throws OpenBankingRuntimeException Error when getting a database connection to retention database - */ - public static Connection getRetentionDBConnection() throws OpenBankingRuntimeException { - - return JDBCRetentionDataPersistenceManager.getInstance().getDBConnection(); - } - - public static void closeConnection(Connection dbConnection) { - - if (dbConnection != null) { - try { - dbConnection.close(); - } catch (SQLException e) { - log.error("Database error. Could not close statement. Continuing with others. - " - + e.getMessage().replaceAll("[\r\n]", ""), e); - } - } - } - - public static void rollbackTransaction(Connection dbConnection) { - - JDBCPersistenceManager.getInstance().rollbackTransaction(dbConnection); - } - - public static void commitTransaction(Connection dbConnection) { - - JDBCPersistenceManager.getInstance().commitTransaction(dbConnection); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/ErrorConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/ErrorConstants.java deleted file mode 100644 index 81106f21..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/ErrorConstants.java +++ /dev/null @@ -1,344 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -/** - * Error Constant Class. - */ -public class ErrorConstants { - - //Error Response Structure constants - public static final String CODE = "Code"; - public static final String ID = "Id"; - public static final String ERRORS = "Errors"; - public static final String PATH = "Path"; - public static final String URL = "Url"; - public static final String ERROR = "error"; - - //Low level textual error code - public static final String FIELD_INVALID = "OB.Field.Invalid"; - public static final String FIELD_MISSING = "OB.Field.Missing"; - public static final String RESOURCE_INVALID_FORMAT = "OB.Resource.InvalidFormat"; - public static final String UNSUPPORTED_LOCAL_INSTRUMENTS = "OB.Unsupported.LocalInstrument"; - public static final String PATH_REQUEST_BODY = "Payload.Body"; - public static final String PATH_INSTRUCTED_AMOUNT = "Data.Initiation.InstructedAmount"; - public static final String PATH_CREDIT_ACCOUNT = "Data.Initiation.CreditorAccount"; - public static final String PATH_LOCAL_INSTRUMENT = "Data.Initiation.LocalInstrument"; - public static final String PATH_DEBTOR_ACCOUNT_NAME = "Data.Initiation.DebtorAccount.Name"; - public static final String PATH_DEBTOR_ACCOUNT_IDENTIFICATION = "Data.Initiation.DebtorAccount.Identification"; - public static final String PATH_DEBTOR_ACCOUNT_SCHEME = "Data.Initiation.DebtorAccount.SchemeName"; - public static final String PATH_CREDIT_ACCOUNT_SEC_IDENTIFICATION = "Data.Initiation.CreditorAccount" + - ".SecondaryIdentification"; - public static final String PATH_CREDIT_ACCOUNT_NAME = "Data.Initiation.CreditorAccount.Name"; - - public static final String PATH_CREDIT_ACCOUNT_IDENTIFICATION = "Data.Initiation.CreditorAccount.Identification"; - public static final String PATH_CREDIT_ACCOUNT_SCHEME = "Data.Initiation.CreditorAccount.SchemeName"; - public static final String PATH_INVALID = "Request path invalid"; - public static final String PAYLOAD_INVALID = "Consent validation failed due to invalid initiation payload"; - public static final String NOT_JSON_OBJECT_ERROR = "Payload is not a JSON object"; - public static final String PAYLOAD_FORMAT_ERROR = "Request Payload is not in correct JSON format"; - public static final String PAYLOAD_FORMAT_ERROR_VALID_TO_DATE = "Invalid valid_to_date parameter in the payload" + - "for valid to date"; - public static final String PAYLOAD_FORMAT_ERROR_DEBTOR_ACC = "Parameter Debtor Account does not exists "; - public static final String PAYLOAD_FORMAT_ERROR_CREDITOR_ACC = "Parameter Creditor Account " + - "does not exists "; - public static final String INVALID_REQ_PAYLOAD = "Invalid request payload"; - public static final String INVALID_REQ_PAYLOAD_INITIATION = "Invalid request payload in initiation key"; - public static final String INVALID_REQ_PAYLOAD_CONTROL_PARAMETERS = "Invalid request payload in " + - "control parameter key"; - public static final String MISSING_DEBTOR_ACC_SCHEME_NAME = "Mandatory parameter Debtor Account Scheme Name does " + - "not exists"; - public static final String MISSING_DEBTOR_ACC_IDENTIFICATION = "Mandatory parameter Debtor Account Identification" + - " does not exists"; - public static final String INVALID_DEBTOR_ACC_SCHEME_NAME = "Debtor Account Scheme Name does not match with the" + - " Scheme Names defined in the specification"; - public static final String INVALID_DEBTOR_ACC_IDENTIFICATION = "Debtor Account Identification should not exceed" + - " the max length of 256 characters defined in the specification"; - public static final String INVALID_DEBTOR_ACC_NAME = "Debtor Account Name should not exceed the max length of 70" + - " character defined in the specification"; - public static final String INVALID_DEBTOR_ACC_SEC_IDENTIFICATION = "Debtor Account Secondary Identification" + - " should not exceed the max length of 34 characters defined in the specification"; - public static final String NO_CONSENT_FOR_CLIENT_ERROR = "No valid consent found for given information"; - public static final String PAYMENT_INITIATION_HANDLE_ERROR = "Error occurred while handling the payment " + - "initiation request"; - public static final String MSG_ELAPSED_CUT_OFF_DATE_TIME = "{payment-order} consent / resource received after " + - "CutOffDateTime."; - public static final String MAX_INSTRUCTED_AMOUNT = "Instructed Amount specified exceed the Maximum Instructed " + - "Amount of the bank"; - public static final String INVALID_INSTRUCTED_AMOUNT = "Instructed Amount specified should be grater than zero"; - public static final String MSG_MISSING_CREDITOR_ACC = "Mandatory parameter CreditorAccount is missing in the" + - " payload."; - public static final String MISSING_CREDITOR_ACC_SCHEME_NAME = "Mandatory parameter Creditor Account Scheme Name" + - " does not exists"; - public static final String MISSING_CREDITOR_ACC_IDENTIFICATION = "Mandatory parameter Creditor Account " + - "Identification does not exists"; - public static final String INVALID_CREDITOR_ACC_SCHEME_NAME = "Creditor Account Scheme Name does not match with" + - " the Scheme Names defined in the specification"; - public static final String INVALID_CREDITOR_ACC_IDENTIFICATION = "Creditor Account Identification should not " + - "exceed the max length of 256 characters defined in the specification"; - public static final String INVALID_CREDITOR_ACC_NAME = "Creditor Account Name should not exceed the max length" + - " of 350 character defined in the specification"; - public static final String INVALID_CREDITOR_ACC_SEC_IDENTIFICATION = "Creditor Account Secondary Identification" + - " should not exceed the max length of 34 characters defined in the specification"; - public static final String INVALID_IDENTIFICATION = "Identification validation for SortCodeNumber Scheme failed."; - public static final String INVALID_LOCAL_INSTRUMENT = "The given local instrument value is not supported"; - public static final String INVALID_DEBTOR_ACC_SCHEME_NAME_LENGTH = "Debtor Account Scheme Name length does not " + - "match with the length defined in the specification"; - public static final String INVALID_CREDITOR_ACC_SCHEME_NAME_LENGTH = "Creditor Account Scheme Name length does" + - " not match with the length defined in the specification"; - public static final String IDEMPOTENCY_KEY_NOT_FOUND = "Idempotency related details should be submitted" + - " in order to proceed."; - public static final String MSG_INVALID_DEBTOR_ACC = "Mandatory parameter DebtorAccount object is invalid."; - public static final String PATH_DEBTOR_ACCOUNT = "Data.Initiation.DebtorAccount"; - public static final String COF_PATH_DEBTOR_ACCOUNT_SCHEME = "Data.DebtorAccount.SchemeName"; - public static final String COF_PATH_DEBTOR_ACCOUNT_IDENTIFICATION = "Data.DebtorAccount.Identification"; - public static final String COF_PATH_DEBTOR_ACCOUNT_NAME = "Data.DebtorAccount.Name"; - public static final String COF_PATH_DEBTOR_ACCOUNT_SECOND_IDENTIFICATION = - "Data.DebtorAccount.SecondaryIdentification"; - public static final String PATH_CUTOFF_DATE = "Data.CutOffDateTime"; - public static final String RULES_CUTOFF = "OB.Rules.AfterCutOffDateTime"; - public static final String PATH_CONSENT_ID = "Data.Initiation.Consent-id"; - public static final String PATH_DATA = "Data"; - public static final String PATH_INITIATION = "Data.Initiation"; - public static final String PATH_CONTROL_PARAMETERS = "Data.ControlParameters"; - public static final String PATH_RISK = "Data.Risk"; - public static final String PATH_URL = "Data.Url"; - public static final String PATH_EXPIRATION_DATE = "Data.Expiration-Date"; - public static final String MSG_MISSING_DEBTOR_ACC = "Mandatory parameter DebtorAccount is missing in the payload."; - public static final String REQUEST_OBJ_EXTRACT_ERROR = "Request object cannot be extracted"; - public static final String REQUEST_OBJ_NOT_SIGNED = "request object is not signed JWT"; - public static final String NOT_JSON_PAYLOAD = "Payload is not a JSON object"; - public static final String INTENT_ID_NOT_FOUND = "intent_id not found in request object"; - public static final String REQUEST_OBJ_PARSE_ERROR = "Error while parsing the request object."; - public static final String STATE_INVALID_ERROR = "Consent not in authorizable state"; - public static final String DATE_PARSE_MSG = "Parsed OffsetDateTime: %s, current OffsetDateTime: %s"; - public static final String EXP_DATE_PARSE_ERROR = "Error occurred while parsing the expiration date. "; - public static final String ACC_CONSENT_RETRIEVAL_ERROR = "Error occurred while retrieving the account initiation" + - " request details"; - public static final String CONSENT_EXPIRED = "Provided consent is expired"; - public static final String CONSENT_RETRIEVAL_ERROR = "Exception occurred while getting consent data"; - public static final String AUTH_CUT_OFF_DATE_ELAPSED = "Cut off time has elapsed"; - public static final String AUTH_TOKEN_REVOKE_ERROR = "Cutoff date time elapsed. Error while revoking the consent."; - public static final String ACCOUNT_ID_NOT_FOUND_ERROR = "Account IDs not available in persist request"; - public static final String ACCOUNT_ID_FORMAT_ERROR = "Account IDs format error in persist request"; - public static final String RESOURCE_CONSENT_MISMATCH = "OB.Resource.ConsentMismatch"; - public static final String INVALID_USER_ID = "Token received does not bound to the authorized user.:" - + ErrorConstants.PATH_ACCESS_TOKEN; - public static final String PATH_ACCESS_TOKEN = "Header.AccessToken"; - public static final String MSG_INVALID_CLIENT_ID = "The client Id related the consent does not match with the " + - "client id bound to token"; - public static final String PATH_CLIENT_ID = "Header.Client-id"; - public static final String UNEXPECTED_ERROR = "OB.UnexpectedError"; - public static final String INVALID_CONSENT_TYPE = "Invalid Consent Type found in the request"; - public static final String ACCOUNT_CONSENT_STATE_INVALID = "Account validation failed due to invalid consent" + - " state. :" + ErrorConstants.PATH_STATUS; - public static final String PATH_STATUS = "Payload.Status"; - public static final String RESOURCE_INVALID_CONSENT_STATUS = "OB.Resource.InvalidConsentStatus"; - public static final String INSTRUCTION_IDENTIFICATION_MISMATCH = "Instruction Identification does not match:" - + ErrorConstants.PATH_INSTRUCTION_IDENTIFICATION; - public static final String PATH_INSTRUCTION_IDENTIFICATION = "Data.Initiation.InstructionIdentification"; - public static final String END_TO_END_IDENTIFICATION_MISMATCH = "End to End Identification does not match:" - + ErrorConstants.PATH_ENDTOEND_IDENTIFICATION; - public static final String PATH_ENDTOEND_IDENTIFICATION = "Data.Initiation.EndToEndIdentification"; - public static final String END_TO_END_IDENTIFICATION_NOT_FOUND = "End to End Identification isn't present in " + - "the request or in the consent:" + ErrorConstants.PATH_ENDTOEND_IDENTIFICATION; - public static final String INSTRUCTED_AMOUNT_AMOUNT_MISMATCH = "Instructed Amount Amount does not match the " + - "initiated amount:" + ErrorConstants.PATH_INSTRUCTED_AMOUNT_AMOUNT; - public static final String PATH_INSTRUCTED_AMOUNT_AMOUNT = "Data.Initiation.InstructedAmount.Amount"; - public static final String INSTRUCTED_AMOUNT_AMOUNT_NOT_FOUND = "Instructed Amount Amount isn't present in the " + - "payload:"; - public static final String INSTRUCTED_AMOUNT_CURRENCY_MISMATCH = "Instructed Amount currency does not match the " + - "initiated amount or currency:" + ErrorConstants.PATH_INSTRUCTED_AMOUNT_CURRENCY; - public static final String PATH_INSTRUCTED_AMOUNT_CURRENCY = "Data.Initiation.InstructedAmount.Currency"; - public static final String INSTRUCTED_AMOUNT_CURRENCY_NOT_FOUND = "Instructed Amount Currency isn't present in " + - "the payload:"; - public static final String INSTRUCTED_AMOUNT_NOT_FOUND = "Instructed Amount isn't present in the payload"; - public static final String CREDITOR_ACC_SCHEME_NAME_MISMATCH = "Creditor Accounts Scheme does not match"; - public static final String CREDITOR_ACC_SCHEME_NAME_NOT_FOUND = "Creditor Accounts Scheme isn't present in the" + - " request or in the consent."; - public static final String CREDITOR_ACC_IDENTIFICATION_MISMATCH = "Creditor Account Identification does not match"; - public static final String CREDITOR_ACC_IDENTIFICATION_NOT_FOUND = "Creditor Account Identification isn't " + - "present in the request or in the consent."; - public static final String CREDITOR_ACC_NAME_MISMATCH = "Creditor Account Name does not match"; - public static final String CREDITOR_ACC_SEC_IDENTIFICATION_MISMATCH = "Creditor Account Secondary Identification" + - " does not match"; - - public static final String DEBTOR_ACC_SCHEME_NAME_MISMATCH = "Debtor Account Scheme name does not "; - public static final String DEBTOR_ACC_SCHEME_NAME_NOT_FOUND = "Debtor Account Scheme name isn't present in the " + - "request or in the consent"; - public static final String DEBTOR_ACC_IDENTIFICATION_MISMATCH = "Debtor Account Identification does " + - "not match:"; - public static final String DEBTOR_ACC_IDENTIFICATION_NOT_FOUND = "Debtor Account Identification isn't present " + - "in the request or in the consent"; - public static final String DEBTOR_ACC_NAME_MISMATCH = "Debtor Account Name does not match"; - public static final String DEBTOR_ACC_SEC_IDENTIFICATION_MISMATCH = "Debtor Account Secondary Identification" + - " does not match"; - public static final String PATH_DEBTOR_ACCOUNT_SECOND_IDENTIFICATION = - "Data.Initiation.DebtorAccount.SecondaryIdentification"; - public static final String CREDITOR_ACC_NOT_FOUND = "Creditor Account isn't present in the request."; - public static final String DEBTOR_ACC_MISMATCH = "Debtor Account mismatch"; - public static final String LOCAL_INSTRUMENT_MISMATCH = "Local Instrument Does Not Match" + - ErrorConstants.PATH_LOCAL_INSTRUMENT; - public static final String TOKEN_REVOKE_ERROR = "Token revocation unsuccessful. :" + - ErrorConstants.PATH_CUTOFF_DATE; - public static final String CUT_OFF_DATE_ELAPSED = "Cut off time has elapsed :" + - ErrorConstants.PATH_CUTOFF_DATE; - public static final String MSG_INVALID_CONSENT_ID = "The requested consent-Id does not match with the consent-Id" + - " bound to token"; - public static final String PAYMENT_CONSENT_STATE_INVALID = "Payment validation failed due to invalid consent" + - " state."; - public static final String VRP_CONSENT_STATUS_INVALID = "Validation failed due to invalid consent status."; - public static final String DATA_NOT_FOUND = "Data is not found or empty in the request."; - public static final String INITIATION_NOT_FOUND = "Initiation is not found or is empty in the request."; - public static final String RISK_MISMATCH = "RISK Does Not Match."; - public static final String INVALID_URI_ERROR = "Path requested is invalid. :" + ErrorConstants.PATH_URL; - public static final String COF_CONSENT_STATE_INVALID = "Confirmation of Funds validation failed due to invalid" + - " consent state.:" + ErrorConstants.PATH_STATUS; - public static final String CONSENT_EXPIRED_ERROR = "Provided consent is expired. :" - + ErrorConstants.PATH_EXPIRATION_DATE; - public static final String MSG_MISSING_CLIENT_ID = "Missing mandatory parameter x-wso2-client-id."; - public static final String RESOURCE_NOT_FOUND = "OB.Resource.NotFound"; - public static final String ACC_INITIATION_RETRIEVAL_ERROR = "Error occurred while handling the account initiation" + - " retrieval request"; - public static final String INVALID_CONSENT_ID = "Invalid Consent Id found in the request"; - public static final String CONSENT_ID_NOT_FOUND = "Consent ID not available in consent data"; - public static final String FIELD_INVALID_DATE = "OB.Field.InvalidDate"; - public static final String EXPIRED_DATE_ERROR = "The ExpirationDateTime value has to be a future date."; - public static final String CONSENT_ATTRIBUTE_RETRIEVAL_ERROR = "Error occurred while retrieving the consent " + - "attributes"; - - // VRP error constants - - public static final String VRP_INITIATION_HANDLE_ERROR = "Error occurred while handling the VRP " + - "initiation request"; - public static final String VRP_INITIATION_RETRIEVAL_ERROR = "Error occurred while handling the VRP initiation" + - " retrieval request"; - public static final String PAYLOAD_FORMAT_ERROR_VALID_FROM_DATE = "Request Payload is not in correct JSON format" + - " for valid from date"; - public static final String INVALID_VALID_TO_DATE_TIME = "Invalid date time format in validToDateTime"; - public static final String INVALID_VALID_FROM_DATE_TIME = "Invalid date time format in validFromDateTime"; - public static final String PAYLOAD_FORMAT_ERROR_CONTROL_PARAMETER = "Request Payload is not in correct JSON " + - "format for control parameter key"; - public static final String PAYLOAD_FORMAT_ERROR_MAXIMUM_INDIVIDUAL_AMOUNT = "Invalid maximum individual amount"; - public static final String MISSING_MAXIMUM_INDIVIDUAL_AMOUNT = "Missing mandatory parameter Maximum Individual" + - " Amount"; - public static final String PAYLOAD_FORMAT_ERROR_MAXIMUM_INDIVIDUAL_CURRENCY = "Invalid maximum individual amount" + - "currency"; - public static final String PAYLOAD_FORMAT_ERROR_INITIATION = "Missing mandatory parameter Initiation" + - " in the payload"; - public static final String PAYLOAD_FORMAT_ERROR_RISK = "Mandatory parameter Risk does not exists" + - " in the payload"; - public static final String INVALID_PERIOD_TYPE = "Invalid value for period type in PeriodicLimits"; - public static final String INVALID_PARAMETER = "Parameter passed in is null "; - public static final String INVALID_CLIENT_ID_MATCH = "Consent validation failed due to client ID mismatch"; - public static final String INVALID_DATE_TIME_FORMAT = "Date and Time is not in correct JSON " + - "ISO-8601 date-time format"; - public static final String MISSING_DATE_TIME_FORMAT = "The value is empty or the value is not a string"; - public static final String MISSING_VALID_TO_DATE_TIME = "Missing parameter ValidToDateTime"; - public static final String MISSING_VALID_FROM_DATE_TIME = "Missing parameter ValidFromDateTime"; - public static final String INVALID_PARAMETER_PERIODIC_LIMITS = "Parameter passed in is null , " + - "empty or not a JSONArray"; - public static final String MISSING_PERIOD_LIMITS = "Mandatory parameter " + - "periodic limits is missing in the payload"; - public static final String MISSING_PERIOD_TYPE = "Missing required parameter Period type"; - public static final String PAYLOAD_FORMAT_ERROR_PERIODIC_LIMITS_PERIOD_TYPE = "Value of period type is empty or " + - "the value passed in is not a string"; - public static final String PAYLOAD_FORMAT_ERROR_PERIODIC_LIMITS_ALIGNMENT = "Value of periodic alignment is empty" + - " or the value passed in is not a string"; - public static final String MISSING_PERIOD_ALIGNMENT = "Missing periodic alignment in periodic limits"; - public static final String INVALID_PERIOD_ALIGNMENT = "Invalid value for period alignment in PeriodicLimits"; - public static final String INVALID_PARAMETER_MESSAGE = "Parameter '%s' passed in is null, empty, or not a %s"; - public static final String DATE_INVALID_PARAMETER_MESSAGE = "Invalid date-time range for ValidToDateTime "; - public static final String INVALID_PERIODIC_LIMIT_SIZE = "Periodic limits exceed the allowed limits"; - public static final String DUPLICATE_PERIOD_TYPE = "Duplicate Period Types found in the request"; - public static final String CURRENCY_MISMATCH = "Currency does not match with the currency of the periodic limits"; - public static final int MAXIMUM_PERIODIC_LIMITS = 6; - public static final String INVALID_MAXIMUM_INDIVIDUAL_CURRENCY = "Invalid value for Currency in " + - "MaximumIndividualAmount"; - public static final String INVALID_PERIODIC_LIMIT_AMOUNT = "Invalid value for in Amount in Periodic Limits"; - public static final String INVALID_PERIODIC_LIMIT_CURRENCY = "Invalid value for Currency in Periodic Limits"; - - - // vrp path parameters - public static final String PATH_VALID_TO_DATE = "Data.ControlParameters.ValidToDateTime"; - public static final String PATH_VALID_FROM_DATE = "Data.ControlParameters.ValidFromDateTime"; - public static final String PATH_MAXIMUM_INDIVIDUAL_AMOUNT = "Data.ControlParameters.MaximumIndividualAmount"; - public static final String PATH_PERIOD_LIMIT = "Data.ControlParameters.PeriodicLimits"; - public static final String PATH_PERIOD_LIMIT_AMOUNT = "Data.ControlParameters.PeriodicLimits.Amount"; - public static final String PATH_PERIOD_LIMIT_CURRENCY = "Data.ControlParameters.PeriodicLimits.Currency"; - public static final String PATH_PERIOD_TYPE = "Data.ControlParameters.PeriodicLimits.PeriodType"; - public static final String PATH_PERIOD_ALIGNMENT = "Data.ControlParameters.PeriodicLimits.PeriodAlignment"; - - // VRP Authorization flow - public static final String CONTROL_PARAMETERS_MISSING_ERROR = "Missing mandatory parameter the ControlParameters"; - public static final String DATA_OBJECT_MISSING_ERROR = "Missing mandatory parameter the Data"; - public static final String MAX_AMOUNT_NOT_JSON_OBJECT_ERROR = "Parameter Maximum Individual Amount is" + - "not of type JSONObject"; - public static final String NOT_JSON_ARRAY_ERROR = "Parameter PeriodicLimits is not a JSON Array"; - public static final String PERIOD_ALIGNMENT_NOT_STRING_ERROR = "Parameter Period Alignment is not a String"; - public static final String PERIOD_TYPE_NOT_STRING_ERROR = "Parameter Period Type is not a String"; - public static final String NOT_STRING_ERROR = "Parameter amount or currency is not a String"; - - // VRP Submission flow - public static final String REMITTANCE_INFO_NOT_FOUND = "Remittance info is not present in the request."; - public static final String INSTRUCTION_IDENTIFICATION_NOT_FOUND = "Instruction Identification isn't present" + - " in the request"; - public static final String END_TO_END_IDENTIFICATION_PARAMETER_NOT_FOUND = "End to End Identification isn't" + - " present in the request"; - public static final String RISK_PARAMETER_MISMATCH = "RISK does not match"; - public static final String INSTRUCTED_AMOUNT_PARAMETER_NOT_FOUND = "Instructed Amount isn't present in the payload"; - public static final String INITIATION_REMITTANCE_INFO_PARAMETER_NOT_FOUND = "Remittance ifo present under" + - " initiation isn't present in the request"; - public static final String INSTRUCTION_REMITTANCE_INFO_PARAMETER_NOT_FOUND = "Remittance ifo present under" + - " instruction isn't present in the request"; - public static final String REMITTANCE_INFO_MISMATCH = "Remittance info does not match"; - public static final String REMITTANCE_UNSTRUCTURED_MISMATCH = "Remittance Information Unstructured does not " + - "match"; - public static final String INVALID_SUBMISSION_TYPE = "Value associated with INSTRUCTION_IDENTIFICATION key is " + - "not a String instance"; - public static final String INVALID_END_TO_END_IDENTIFICATION_TYPE = "Value associated with" + - " END_TO_END_IDENTIFICATION key is not a String instance"; - public static final String RISK_NOT_FOUND = "Risk is not found or empty in the request."; - public static final String RISK_NOT_JSON_ERROR = "Risk parameter is not in the correct JSON format"; - public static final String INSTRUCTION_NOT_FOUND = "Instruction is not found or empty in the request."; - public static final String INVALID_REQUEST_CONSENT_ID = "The consent-Id is not present in the request" + - " or it is not a String instance or there is a consentId mismatch"; - public static final String INSTRUCTION_CREDITOR_ACC_NOT_JSON_ERROR = "Creditor Account present under instruction" + - " isn't present in the correct JSON format in the request."; - public static final String INITIATION_CREDITOR_ACC_NOT_JSON_ERROR = "Creditor Account present under initiation" + - " isn't present in the correct JSON format in the request."; - public static final String DEBTOR_ACC_NOT_JSON_ERROR = "Debtor Account isn't present in the correct JSON format " + - "in the request."; - public static final String INITIATION_REMITTANCE_INFO_NOT_JSON_ERROR = "Remittance info of initiation is not " + - "present in the correct JSON format in the request."; - public static final String INSTRUCTION_REMITTANCE_INFO_NOT_JSON_ERROR = "Remittance info of instruction is not" + - " present in the correct JSON format in the request."; - public static final String DEBTOR_ACC_NOT_FOUND = "Debtor Account isn't present in the request."; - public static final String DATA_NOT_JSON_ERROR = "Data parameter is not in the correct JSON format in the request"; - public static final String INSTRUCTED_AMOUNT_NOT_STRING = "Value associated with Amount key is " + - "not a String instance"; - public static final String INSTRUCTED_AMOUNT_CURRENCY_NOT_STRING = "Value associated with Currency key is " + - "not a String instance"; - public static final String INSTRUCTED_AMOUNT_NOT_JSON_ERROR = "Instructed Amount is not in the correct JSON " + - "format in the request"; - public static final String INITIATION_NOT_JSON = "Initiation is not in the correct JSON " + - "format in the request"; - public static final String INSTRUCTION_NOT_JSON = "Instruction is not in the correct JSON format in the request"; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/Generated.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/Generated.java deleted file mode 100644 index a3718e09..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/Generated.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -/** - * An annotation to make methods skip code coverage. Use only with a valid reason to skip - * code coverage. - */ -@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) -public @interface Generated { - String message(); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/HTTPClientUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/HTTPClientUtils.java deleted file mode 100644 index 5e84500f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/HTTPClientUtils.java +++ /dev/null @@ -1,205 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.ssl.SSLContexts; -import org.wso2.carbon.base.ServerConfiguration; - -import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -import javax.net.ssl.SSLContext; - -/** - * HTTP Client Utility methods. - */ -public class HTTPClientUtils { - - public static final String ALLOW_ALL = "AllowAll"; - public static final String STRICT = "Strict"; - public static final String HOST_NAME_VERIFIER = "httpclient.hostnameVerifier"; - public static final String HTTP_PROTOCOL = "http"; - public static final String HTTPS_PROTOCOL = "https"; - private static final String[] SUPPORTED_HTTP_PROTOCOLS = {"TLSv1.2"}; - private static final Log log = LogFactory.getLog(DatabaseUtil.class); - - /** - * Get closeable https client. - * - * @return Closeable https client - * @throws OpenBankingException OpenBankingException exception - */ - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - public static CloseableHttpClient getHttpsClient() throws OpenBankingException { - - SSLConnectionSocketFactory sslsf = createSSLConnectionSocketFactory(); - - Registry socketFactoryRegistry = RegistryBuilder.create() - .register(HTTP_PROTOCOL, new PlainConnectionSocketFactory()) - .register(HTTPS_PROTOCOL, sslsf) - .build(); - - final PoolingHttpClientConnectionManager connectionManager = (socketFactoryRegistry != null) ? - new PoolingHttpClientConnectionManager(socketFactoryRegistry) : - new PoolingHttpClientConnectionManager(); - - // configuring default maximum connections - connectionManager.setMaxTotal(OpenBankingConfigParser.getInstance().getConnectionPoolMaxConnections()); - connectionManager.setDefaultMaxPerRoute(OpenBankingConfigParser.getInstance() - .getConnectionPoolMaxConnectionsPerRoute()); - - return HttpClients.custom().setConnectionManager(connectionManager).build(); - } - - /** - * Get closeable https client to send realtime event notifications. - * - * @return Closeable https client - * @throws OpenBankingException OpenBankingException exception - */ - @Generated(message = "Ignoring since method contains no logics") - public static CloseableHttpClient getRealtimeEventNotificationHttpsClient() throws OpenBankingException { - - SSLConnectionSocketFactory sslsf = createSSLConnectionSocketFactory(); - - Registry socketFactoryRegistry = RegistryBuilder.create() - .register(HTTP_PROTOCOL, new PlainConnectionSocketFactory()) - .register(HTTPS_PROTOCOL, sslsf) - .build(); - - final PoolingHttpClientConnectionManager connectionManager = (socketFactoryRegistry != null) ? - new PoolingHttpClientConnectionManager(socketFactoryRegistry) : - new PoolingHttpClientConnectionManager(); - - // configuring default maximum connections - connectionManager.setMaxTotal(OpenBankingConfigParser.getInstance() - .getRealtimeEventNotificationMaxRetries() + 1); - connectionManager.setDefaultMaxPerRoute(OpenBankingConfigParser.getInstance() - .getRealtimeEventNotificationMaxRetries() + 1); - - return HttpClients.custom().setConnectionManager(connectionManager).build(); - } - - /** - * create a SSL Connection Socket Factory. - * - * @return SSLConnectionSocketFactory - * @throws OpenBankingException - */ - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - private static SSLConnectionSocketFactory createSSLConnectionSocketFactory() - throws OpenBankingException { - - KeyStore trustStore = null; - - trustStore = loadKeyStore( - ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Location"), - ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Password")); - - // Trust own CA and all self-signed certs - SSLContext sslcontext = null; - try { - sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); - } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { - throw new OpenBankingException("Unable to create the ssl context", e); - } - - // Allow TLSv1 protocol only - return new SSLConnectionSocketFactory(sslcontext, SUPPORTED_HTTP_PROTOCOLS, - null, getX509HostnameVerifier()); - - } - - /** - * Load the keystore when the location and password is provided. - * - * @param keyStoreLocation Location of the keystore - * @param keyStorePassword Keystore password - * @return Keystore as an object - * @throws OpenBankingException when failed to load Keystore from given details - */ - @SuppressFBWarnings("PATH_TRAVERSAL_IN") - // Suppressed content - new FileInputStream(keyStoreLocation) - // Suppression reason - False Positive : Keystore location is obtained from deployment.toml. So it can be marked - // as a trusted filepath - // Suppressed warning count - 1 - public static KeyStore loadKeyStore(String keyStoreLocation, String keyStorePassword) - throws OpenBankingException { - - KeyStore keyStore; - - try (FileInputStream inputStream = new FileInputStream(keyStoreLocation)) { - keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(inputStream, keyStorePassword.toCharArray()); - return keyStore; - } catch (KeyStoreException e) { - throw new OpenBankingException("Error while retrieving aliases from keystore", e); - } catch (IOException | CertificateException | NoSuchAlgorithmException e) { - throw new OpenBankingException("Error while loading keystore", e); - } - } - - /** - * Get the Hostname Verifier property in set in system properties. - * - * @return X509HostnameVerifier - */ - public static X509HostnameVerifier getX509HostnameVerifier() { - - String hostnameVerifierOption = System.getProperty(HOST_NAME_VERIFIER); - X509HostnameVerifier hostnameVerifier; - - if (ALLOW_ALL.equalsIgnoreCase(hostnameVerifierOption)) { - hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - } else if (STRICT.equalsIgnoreCase(hostnameVerifierOption)) { - hostnameVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; - } else { - hostnameVerifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; - } - - if (log.isDebugEnabled()) { - log.debug(String.format("Proceeding with %s : %s", HOST_NAME_VERIFIER, - hostnameVerifierOption)); - } - return hostnameVerifier; - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/JWTUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/JWTUtils.java deleted file mode 100644 index 172033df..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/JWTUtils.java +++ /dev/null @@ -1,254 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.util; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jose.jwk.source.RemoteJWKSet; -import com.nimbusds.jose.proc.BadJOSEException; -import com.nimbusds.jose.proc.JWSKeySelector; -import com.nimbusds.jose.proc.JWSVerificationKeySelector; -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jose.proc.SimpleSecurityContext; -import com.nimbusds.jose.util.DefaultResourceRetriever; -import com.nimbusds.jwt.JWT; -import com.nimbusds.jwt.JWTParser; -import com.nimbusds.jwt.SignedJWT; -import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; -import com.nimbusds.jwt.proc.DefaultJWTProcessor; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.net.MalformedURLException; -import java.net.URL; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.X509EncodedKeySpec; -import java.text.ParseException; -import java.util.Base64; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Util class for jwt related functions. - */ -public class JWTUtils { - - private static final Log log = LogFactory.getLog(JWTUtils.class); - private static final String RS = "RS"; - private static final String ALGORITHM_RSA = "RSA"; - - /** - * Decode request JWT. - * - * @param jwtToken jwt sent by the tpp - * @param jwtPart expected jwt part (header, body) - * @return json object containing requested jwt part - * @throws ParseException if an error occurs while parsing the jwt - */ - public static JSONObject decodeRequestJWT(String jwtToken, String jwtPart) throws ParseException { - - JSONObject jsonObject = new JSONObject(); - - JWSObject plainObject = JWSObject.parse(jwtToken); - - if ("head".equals(jwtPart)) { - jsonObject = plainObject.getHeader().toJSONObject(); - } else if ("body".equals(jwtPart)) { - jsonObject = plainObject.getPayload().toJSONObject(); - } - - return jsonObject; - - } - - /** - * Validate the signed JWT by querying a jwks. - * - * @param jwtString signed json web token - * @param jwksUri endpoint displaying the key set for the signing certificates - * @param algorithm the signing algorithm for jwt - * @return true if signature is valid - * @throws ParseException if an error occurs while parsing the jwt - * @throws BadJOSEException if the jwt is invalid - * @throws JOSEException if an error occurs while processing the jwt - * @throws MalformedURLException if an error occurs while creating the URL object - */ - @Generated(message = "Excluding from code coverage since can not call this method due to external https call") - public static boolean validateJWTSignature(String jwtString, String jwksUri, String algorithm) - throws ParseException, BadJOSEException, JOSEException, MalformedURLException { - - int defaultConnectionTimeout = 3000; - int defaultReadTimeout = 3000; - ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); - JWT jwt = JWTParser.parse(jwtString); - // set the Key Selector for the jwks_uri. - Map> jwkSourceMap = new ConcurrentHashMap<>(); - RemoteJWKSet jwkSet = jwkSourceMap.get(jwksUri); - if (jwkSet == null) { - int connectionTimeout = Integer.parseInt(OpenBankingConfigParser.getInstance().getJWKSConnectionTimeOut()); - int readTimeout = Integer.parseInt(OpenBankingConfigParser.getInstance().getJWKSReadTimeOut()); - int sizeLimit = RemoteJWKSet.DEFAULT_HTTP_SIZE_LIMIT; - if (connectionTimeout == 0 && readTimeout == 0) { - connectionTimeout = defaultConnectionTimeout; - readTimeout = defaultReadTimeout; - } - DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever( - connectionTimeout, - readTimeout, - sizeLimit); - jwkSet = new RemoteJWKSet<>(new URL(jwksUri), resourceRetriever); - jwkSourceMap.put(jwksUri, jwkSet); - } - // The expected JWS algorithm of the access tokens (agreed out-of-band). - JWSAlgorithm expectedJWSAlg = JWSAlgorithm.parse(algorithm); - //Configure the JWT processor with a key selector to feed matching public RSA keys sourced from the JWK set URL. - JWSKeySelector keySelector = new JWSVerificationKeySelector<>(expectedJWSAlg, jwkSet); - jwtProcessor.setJWSKeySelector(keySelector); - // Process the token, set optional context parameters. - SimpleSecurityContext securityContext = new SimpleSecurityContext(); - jwtProcessor.process((SignedJWT) jwt, securityContext); - return true; - } - - /** - * Validates the signature of a given JWT against a given public key. - * - * @param signedJWT the signed JWT to be validated - * @param publicKey the public key that is used for validation - * @return true if signature is valid else false - * @throws NoSuchAlgorithmException if the given algorithm doesn't exist - * @throws InvalidKeySpecException if the provided key is invalid - * @throws JOSEException if an error occurs during the signature validation process - */ - @Generated(message = "Excluding from code coverage as KeyFactory does not initialize in testsuite") - public static boolean isValidSignature(SignedJWT signedJWT, String publicKey) - throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException, OpenBankingException { - - byte[] publicKeyData = Base64.getDecoder().decode(publicKey); - X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyData); - // Example : RS256 - String algorithm = signedJWT.getHeader().getAlgorithm().getName(); - KeyFactory kf = getKeyFactory(algorithm); - RSAPublicKey rsapublicKey = (RSAPublicKey) kf.generatePublic(spec); - JWSVerifier verifier = new RSASSAVerifier(rsapublicKey); - return signedJWT.verify(verifier); - } - - /** - * Validate legitimacy of a JWS. - * - * @param jwsString JWT string - * @return true if a given jwsString adheres a valid JWS Format - */ - public static boolean isValidJWSFormat(String jwsString) { - - return StringUtils.isBlank(jwsString) ? false : - StringUtils.countMatches(jwsString, OpenBankingConstants.DOT_SEPARATOR) == 2; - } - - /** - * Parses the provided JWT string into a SignedJWT object. - * - * @param jwtString the JWT string to parse - * @return the parsed SignedJWT object - * @throws IllegalArgumentException if the provided token identifier is not a parsable JWT - * - */ - public static SignedJWT getSignedJWT(String jwtString) throws ParseException { - - if (isValidJWSFormat(jwtString)) { - return SignedJWT.parse(jwtString); - } else { - if (log.isDebugEnabled()) { - log.debug(String.format("Provided token identifier is not a parsable JWT: %s", jwtString)); - } - throw new IllegalArgumentException("Provided token identifier is not a parsable JWT."); - } - } - - /** - * Checks if the given expiration time is valid based on the current system time and a default time skew. - * - * @param defaultTimeSkew defaultTimeSkew to adjust latency issues. - * @param expirationTime the exp of the jwt that should be validated. - * @return True if the expiration time is valid considering the default time skew; false otherwise. - */ - public static boolean isValidExpiryTime(Date expirationTime, long defaultTimeSkew) { - - if (expirationTime != null) { - long timeStampSkewMillis = defaultTimeSkew * 1000; - long expirationTimeInMillis = expirationTime.getTime(); - long currentTimeInMillis = System.currentTimeMillis(); - return (currentTimeInMillis + timeStampSkewMillis) <= expirationTimeInMillis; - } else { - return false; - } - } - - /** - * Checks if the given "not before" time is valid based on the current system time and a default time skew. - * - * @param defaultTimeSkew defaultTimeSkew to adjust latency issues. - * @param notBeforeTime nbf of the jwt that should be validated - * @return True if the "not before" time is valid considering the default time skew; false otherwise. - */ - public static boolean isValidNotValidBeforeTime(Date notBeforeTime, long defaultTimeSkew) { - - if (notBeforeTime != null) { - long timeStampSkewMillis = defaultTimeSkew * 1000; - long notBeforeTimeMillis = notBeforeTime.getTime(); - long currentTimeInMillis = System.currentTimeMillis(); - return currentTimeInMillis + timeStampSkewMillis >= notBeforeTimeMillis; - } else { - return false; - } - } - - /** - * Returns a KeyFactory instance for the specified algorithm. - * - * @param algorithm the algorithm name, such as "RS256". - * @return the KeyFactory instance. - * @throws OpenBankingException if the provided algorithm is not supported. - * @throws NoSuchAlgorithmException if the specified algorithm is invalid. - */ - @Generated(message = "Excluding from code coverage as KeyFactory does not initialize in testsuite") - private static KeyFactory getKeyFactory(String algorithm) throws OpenBankingException, NoSuchAlgorithmException { - - // In here if the algorithm is directly passes (like RS256) it will generate exceptions - // hence Base algorithm should be passed (Example: RSA) - if (algorithm.indexOf(RS) == 0) { - return KeyFactory.getInstance(ALGORITHM_RSA); - } else { - throw new OpenBankingException("Algorithm " + algorithm + " not yet supported."); - } - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/OpenBankingUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/OpenBankingUtils.java deleted file mode 100644 index 98593449..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/OpenBankingUtils.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.identity.IdentityConstants; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; -import java.text.ParseException; - -/** - * Open Banking common utility class. - */ -public class OpenBankingUtils { - - private static final Log log = LogFactory.getLog(OpenBankingUtils.class); - - /** - * Method to obtain the Object when the full class path is given. - * - * @param classpath full class path - * @return new object instance - */ - @Generated(message = "Ignoring since method contains no logics") - public static Object getClassInstanceFromFQN(String classpath) { - - try { - return Class.forName(classpath).getDeclaredConstructor().newInstance(); - } catch (ClassNotFoundException e) { - log.error("Class not found: " + classpath.replaceAll("[\r\n]", "")); - throw new OpenBankingRuntimeException("Cannot find the defined class", e); - } catch (InstantiationException | InvocationTargetException | - NoSuchMethodException | IllegalAccessException e) { - //Throwing a runtime exception since we cannot proceed with invalid objects - throw new OpenBankingRuntimeException("Defined class" + classpath + "cannot be instantiated.", e); - } - } - - /** - * Extract software_environment (SANDBOX or PRODUCTION) from SSA. - * - * @param softwareStatement software statement (jwt) extracted from request payload - * @return software_environment - * @throws ParseException if an error occurs while parsing the software statement - */ - public static String getSoftwareEnvironmentFromSSA(String softwareStatement) throws ParseException { - - if (StringUtils.isEmpty(softwareStatement)) { - return IdentityConstants.PRODUCTION; - } - - final JSONObject softwareStatementBody = JWTUtils.decodeRequestJWT(softwareStatement, - OpenBankingConstants.JWT_BODY); - // Retrieve the SSA property name used for software environment identification - final String sandboxEnvIdentificationPropertyName = OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyName(); - // Retrieve the expected value for the sandbox environment - final String sandboxEnvIdentificationValue = OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyValueForSandbox(); - return sandboxEnvIdentificationValue.equalsIgnoreCase(softwareStatementBody - .getAsString(sandboxEnvIdentificationPropertyName)) - ? IdentityConstants.SANDBOX - : IdentityConstants.PRODUCTION; - } - - /** - * Method to obtain boolean value for check if the Dispute Resolution Data is publishable. - * - * @param statusCode for dispute data - * @return boolean - */ - public static boolean isPublishableDisputeData(int statusCode) { - - if (statusCode < 400 && - OpenBankingConfigParser.getInstance().isNonErrorDisputeDataPublishingEnabled()) { - return true; - } - - return statusCode >= 400; - } - - /** - * Method to reduce string length. - * - * @param input Input for dispute data - * @param maxLength Max length for dispute data - * @return String with reduced length - */ - public static String reduceStringLength(String input, int maxLength) { - if (StringUtils.isEmpty(input) || input.length() <= maxLength) { - return input; - } else { - return input.substring(0, maxLength); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/SPQueryExecutorUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/SPQueryExecutorUtil.java deleted file mode 100644 index 72c83d1c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/SPQueryExecutorUtil.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -/** - * Util class to handle communications with stream processor. - */ -public class SPQueryExecutorUtil { - - private static Log log = LogFactory.getLog(SPQueryExecutorUtil.class); - - /** - * Executes the given query in SP. - * - * @param appName Name of the siddhi app. - * @param query Name of the query - * @param spUserName Username for SP - * @param spPassword Password for SP - * @param spApiHost Hostname of the SP - * @return JSON object with result - * @throws IOException IO Exception. - * @throws ParseException Parse Exception. - * @throws OpenBankingException OpenBanking Exception. - */ - public static JSONObject executeQueryOnStreamProcessor(String appName, String query, String spUserName, - String spPassword, String spApiHost) - throws IOException, ParseException, OpenBankingException { - byte[] encodedAuth = Base64.getEncoder() - .encode((spUserName + ":" + spPassword).getBytes(StandardCharsets.ISO_8859_1)); - String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.UTF_8.toString()); - - CloseableHttpClient httpClient = HTTPClientUtils.getHttpsClient();; - HttpPost httpPost = new HttpPost(spApiHost + OpenBankingConstants.SP_API_PATH); - httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader); - JSONObject jsonObject = new JSONObject(); - jsonObject.put(OpenBankingConstants.APP_NAME_CC, appName); - jsonObject.put(OpenBankingConstants.QUERY, query); - StringEntity requestEntity = new StringEntity(jsonObject.toJSONString()); - httpPost.setHeader(OpenBankingConstants.CONTENT_TYPE_TAG, OpenBankingConstants.JSON_CONTENT_TYPE); - httpPost.setEntity(requestEntity); - HttpResponse response; - - if (log.isDebugEnabled()) { - log.debug(String.format("Executing query %s on SP", query)); - } - response = httpClient.execute(httpPost); - HttpEntity entity = response.getEntity(); - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { - String error = String.format("Error while invoking SP rest api : %s %s", - response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); - log.error(error); - return null; - } - String responseStr = EntityUtils.toString(entity); - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - return (JSONObject) parser.parse(responseStr); - } - } diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/SecurityUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/SecurityUtils.java deleted file mode 100644 index a800f2ea..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/SecurityUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.util; - -import org.apache.commons.lang3.StringUtils; - -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Common Security Utils class. - */ -public class SecurityUtils { - - private static final String specialChars = "!@#$%&*()'+,-./:;<=>?[]^_`{|}"; - - /** - * Method to remove new line characters to avoid potential CRLF injection for logs. - * Bug kind and pattern: SECCRLFLOG - CRLF_INJECTION_LOGS - * - * @param string string - * @return string without new line characters - */ - public static String sanitizeString(String string) { - return string.replaceAll("[\r\n]", ""); - } - - /** - * Method to remove new line characters from a list of strings to avoid potential CRLF injection for logs. - * Bug kind and pattern: SECCRLFLOG - CRLF_INJECTION_LOGS - * - * @param stringList String List - * @return string without new line characters - */ - public static List sanitize(List stringList) { - return stringList.stream() - .map(SecurityUtils::sanitizeString) - .collect(Collectors.toList()); - } - - /** - * Method to remove new line characters from a setmvn of strings to avoid potential CRLF injection for logs. - * Bug kind and pattern: SECCRLFLOG - CRLF_INJECTION_LOGS - * - * @param stringSet String Set - * @return string without new line characters - */ - public static Set sanitize(Set stringSet) { - return stringSet.stream() - .map(SecurityUtils::sanitizeString) - .collect(Collectors.toSet()); - } - - /** - * Method to validate a string does not contain special characters. - * - * @param string String - * @return whether the string does not contain any special characters - */ - public static boolean containSpecialChars(String string) { - return StringUtils.containsAny(string, specialChars); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/ServiceProviderUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/ServiceProviderUtils.java deleted file mode 100644 index fae34feb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/ServiceProviderUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; - -/** - * Utility Class for Service Provider related functions. - */ -public class ServiceProviderUtils { - - /** - * Get Tenant Domain String for the client id. - * @param clientId the client id of the application - * @return tenant domain of the client - * @throws OpenBankingException if an error occurs while retrieving the tenant domain - */ - @Generated(message = "Ignoring because OAuth2Util cannot be mocked with no constructors") - public static String getSpTenantDomain(String clientId) throws OpenBankingException { - - try { - return OAuth2Util.getTenantDomainOfOauthApp(clientId); - } catch (InvalidOAuthClientException | IdentityOAuth2Exception e) { - throw new OpenBankingException("Error retrieving service provider tenant domain for client_id: " - + clientId, e); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/CertificateContent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/CertificateContent.java deleted file mode 100644 index 4dbd6efe..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/CertificateContent.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor; - -import java.util.Date; -import java.util.List; - -/** - * Class That Contains Extracted PSD2 Attributes from the certificate. - */ -public class CertificateContent { - private String pspAuthorisationNumber; - private List pspRoles; - private String name; - private String ncaName; - private String ncaId; - private Date notAfter = null; - private Date notBefore = null; - - - public String getPspAuthorisationNumber() { - - return pspAuthorisationNumber; - } - - public void setPspAuthorisationNumber(String pspAuthorisationNumber) { - - this.pspAuthorisationNumber = pspAuthorisationNumber; - } - - public List getPspRoles() { - - return pspRoles; - } - - public void setPspRoles(List pspRoles) { - - this.pspRoles = pspRoles; - } - - public String getName() { - - return name; - } - - public void setName(String name) { - - this.name = name; - } - - public String getNcaName() { - - return ncaName; - } - - public void setNcaName(String ncaName) { - - this.ncaName = ncaName; - } - - public String getNcaId() { - - return ncaId; - } - - public void setNcaId(String ncaId) { - - this.ncaId = ncaId; - } - - public Date getNotAfter() { - - return new Date(notAfter.getTime()); - } - - public void setNotAfter(Date notAfter) { - - this.notAfter = new Date(notAfter.getTime()); - } - - public Date getNotBefore() { - - return new Date(notBefore.getTime()); - } - - public void setNotBefore(Date notBefore) { - - this.notBefore = new Date(notBefore.getTime()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/CertificateContentExtractor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/CertificateContentExtractor.java deleted file mode 100644 index 2f6b5093..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/CertificateContentExtractor.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common.PSD2QCStatement; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common.PSD2QCType; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common.PSPRole; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common.PSPRoles; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.error.CertValidationErrors; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x500.style.IETFUtils; -import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; - -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -/** - * Class that extracts the PSD2 attributes from v3 extensions of X509 certificates. - */ -public class CertificateContentExtractor { - - private static final Log log = LogFactory.getLog(CertificateContentExtractor.class); - - private CertificateContentExtractor() { - } - - public static CertificateContent extract(X509Certificate cert) - throws CertificateValidationException { - - if (cert == null) { - log.error("Error reading certificate "); - throw new CertificateValidationException( - CertValidationErrors.CERTIFICATE_INVALID.toString()); - } - - CertificateContent tppCertData = new CertificateContent(); - - tppCertData.setNotAfter(cert.getNotAfter()); - tppCertData.setNotBefore(cert.getNotBefore()); - - PSD2QCType psd2QcType = PSD2QCStatement.getPsd2QCType(cert); - PSPRoles pspRoles = psd2QcType.getPspRoles(); - List rolesArray = pspRoles.getRoles(); - - List roles = new ArrayList<>(); - - for (PSPRole pspRole : rolesArray) { - roles.add(pspRole.getPsd2RoleName()); - } - tppCertData.setPspRoles(roles); - - tppCertData.setNcaName(psd2QcType.getnCAName().getString()); - tppCertData.setNcaId(psd2QcType.getnCAId().getString()); - - try { - X500Name x500name = new JcaX509CertificateHolder(cert).getSubject(); - - tppCertData.setPspAuthorisationNumber(getNameValueFromX500Name(x500name, BCStyle.ORGANIZATION_IDENTIFIER)); - tppCertData.setName(getNameValueFromX500Name(x500name, BCStyle.CN)); - - if (log.isDebugEnabled()) { - log.debug("Extracted TPP eIDAS certificate data: " + "[ " + tppCertData.toString() + " ]"); - } - - } catch (CertificateEncodingException e) { - log.error("Certificate read error. caused by, ", e); - throw new CertificateValidationException(CertValidationErrors.CERTIFICATE_INVALID.toString(), e); - - } - return tppCertData; - - } - - private static String getNameValueFromX500Name(X500Name x500Name, ASN1ObjectIdentifier asn1ObjectIdentifier) { - - if (ArrayUtils.contains(x500Name.getAttributeTypes(), asn1ObjectIdentifier)) { - return IETFUtils.valueToString(x500Name.getRDNs(asn1ObjectIdentifier)[0].getFirst().getValue()); - } else { - return ""; - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/NcaId.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/NcaId.java deleted file mode 100644 index c820e28f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/NcaId.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -import org.bouncycastle.asn1.DERUTF8String; - -/** - * NcaId class. - */ -public class NcaId extends DERUTF8String { - - public NcaId(String string) { - - super(string); - } - - public static NcaId getInstance(Object obj) { - - if (obj instanceof NcaId) { - return (NcaId) obj; - } - return new NcaId(DERUTF8String.getInstance(obj).getString()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/NcaName.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/NcaName.java deleted file mode 100644 index 02436c1d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/NcaName.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -import org.bouncycastle.asn1.DERUTF8String; - -/** - * NcaName class. - */ -public class NcaName extends DERUTF8String { - - public NcaName(String string) { - - super(string); - } - - public static NcaName getInstance(Object obj) { - - if (obj instanceof NcaName) { - return (NcaName) obj; - } - return new NcaName(DERUTF8String.getInstance(obj).getString()); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2Constants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2Constants.java deleted file mode 100644 index adfee23c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2Constants.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -/** - * PSD2Constants class. - */ -public class PSD2Constants { - - //Role Names on the certificate - public static final String PSP_AS = "PSP_AS"; - public static final String PSP_PI = "PSP_PI"; - public static final String PSP_AI = "PSP_AI"; - public static final String PSP_IC = "PSP_IC"; - - //PSD2 Role OIDs in the certificate - public static final String PSP_AS_OID = "0.4.0.19495.1.1"; - public static final String PSP_PI_OID = "0.4.0.19495.1.2"; - public static final String PSP_AI_OID = "0.4.0.19495.1.3"; - public static final String PSP_IC_OID = "0.4.0.19495.1.4"; - - //PSD2 Role Names - public static final String ASPSP = "ASPSP"; - public static final String PISP = "PISP"; - public static final String AISP = "AISP"; - public static final String CBPII = "CBPII"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2QCStatement.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2QCStatement.java deleted file mode 100644 index 469048ef..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2QCStatement.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.error.CertValidationErrors; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.qualified.QCStatement; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.cert.X509Certificate; -import java.util.Iterator; -import java.util.Optional; - -/** - * PSD2QCStatement class. - */ -public class PSD2QCStatement { - - private static final ASN1ObjectIdentifier psd2QcStatementOid = new ASN1ObjectIdentifier("0.4.0.19495.2"); - private static final Log log = LogFactory.getLog(PSD2QCStatement.class); - - public static PSD2QCType getPsd2QCType(X509Certificate cert) throws CertificateValidationException { - - byte[] extensionValue = cert.getExtensionValue(Extension.qCStatements.getId()); - if (extensionValue == null) { - log.debug("Extension that contains the QCStatement not found in the certificate"); - throw new CertificateValidationException(CertValidationErrors.EXTENSION_NOT_FOUND.toString()); - } - - QCStatement qcStatement = extractQCStatement(extensionValue); - - ASN1Encodable statementInfo = qcStatement.getStatementInfo(); - - return PSD2QCType.getInstance(statementInfo); - - } - - private static QCStatement extractQCStatement(byte[] extensionValue) throws CertificateValidationException { - - ASN1Sequence qcStatements; - try { - try (ASN1InputStream derAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extensionValue))) { - DEROctetString oct = (DEROctetString) (derAsn1InputStream.readObject()); - try (ASN1InputStream asn1InputStream = new ASN1InputStream(oct.getOctets())) { - qcStatements = (ASN1Sequence) asn1InputStream.readObject(); - } - } - } catch (IOException e) { - log.error("Error reading QCStatement ", e); - throw new CertificateValidationException(CertValidationErrors.QCSTATEMENT_INVALID.toString()); - } - - if (qcStatements.size() <= 0) { - log.error("QCStatements not found in the certificate"); - throw new CertificateValidationException(CertValidationErrors.QCSTATEMENTS_NOT_FOUND.toString()); - } - - ASN1Encodable object = qcStatements.getObjectAt(0); - if (object.toASN1Primitive() instanceof ASN1ObjectIdentifier) { - return getSingleQcStatement(qcStatements); - } - - return extractPsd2QcStatement(qcStatements) - .orElseThrow(() -> new CertificateValidationException( - CertValidationErrors.PSD2_QCSTATEMENT_NOT_FOUND.toString())); - } - - private static QCStatement getSingleQcStatement(ASN1Sequence qcStatements) throws CertificateValidationException { - - QCStatement qcStatement = QCStatement.getInstance(qcStatements); - if (!psd2QcStatementOid.getId().equals(qcStatement.getStatementId().getId())) { - log.error("Invalid QC statement type in psd2 certificate. expected [" + - psd2QcStatementOid.getId().replaceAll("[\r\n]", "") + "] but found [" + - qcStatement.getStatementId().getId().replaceAll("[\r\n]", "") + "]"); - throw new CertificateValidationException(CertValidationErrors.PSD2_QCSTATEMENT_NOT_FOUND.toString()); - } - - return qcStatement; - } - - private static Optional extractPsd2QcStatement(ASN1Sequence qcStatements) { - - Iterator iterator = qcStatements.iterator(); - - while (iterator.hasNext()) { - QCStatement qcStatement = QCStatement.getInstance(iterator.next()); - if (qcStatement != null && qcStatement.getStatementId().getId().equals(psd2QcStatementOid.getId())) { - return Optional.of(qcStatement); - } - } - - return Optional.empty(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2QCType.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2QCType.java deleted file mode 100644 index ea9b0c24..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSD2QCType.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Sequence; - -/** - * PSD2QCType class. - */ -public class PSD2QCType { - - private final PSPRoles pspRoles; - private final NcaName nCAName; - private final NcaId nCAId; - - public PSD2QCType(PSPRoles pspRoles, NcaName nCAName, NcaId nCAId) { - - this.pspRoles = pspRoles; - this.nCAName = nCAName; - this.nCAId = nCAId; - } - - public static PSD2QCType getInstance(ASN1Encodable asn1Encodable) { - - ASN1Sequence sequence = ASN1Sequence.getInstance(asn1Encodable); - PSPRoles pspRoles = PSPRoles.getInstance(sequence.getObjectAt(0)); - NcaName nCAName = NcaName.getInstance(sequence.getObjectAt(1)); - NcaId nCAId = NcaId.getInstance(sequence.getObjectAt(2)); - return new PSD2QCType(pspRoles, nCAName, nCAId); - } - - - public PSPRoles getPspRoles() { - - return pspRoles; - } - - public NcaName getnCAName() { - - return nCAName; - } - - public NcaId getnCAId() { - - return nCAId; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSPRole.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSPRole.java deleted file mode 100644 index 6ec64070..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSPRole.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1UTF8String; -import org.bouncycastle.asn1.DERUTF8String; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -/** - * PSPRole enum. - */ -public enum PSPRole { - PSP_AS(PSD2Constants.PSP_AS_OID, PSD2Constants.PSP_AS, PSD2Constants.ASPSP), - PSP_PI(PSD2Constants.PSP_PI_OID, PSD2Constants.PSP_PI, PSD2Constants.PISP), - PSP_AI(PSD2Constants.PSP_AI_OID, PSD2Constants.PSP_AI, PSD2Constants.AISP), - PSP_IC(PSD2Constants.PSP_IC_OID, PSD2Constants.PSP_IC, PSD2Constants.CBPII); - - private String pspRoleOid; //Object Identifier in the Certificate - private String pspRoleName; //Role Name stated on the certificate - private String psd2RoleName; //PSD2 Actor Name related to the role in the certificate - - PSPRole(String pspRoleOid, String pspRoleName, String psd2RoleName) { - - this.pspRoleOid = pspRoleOid; - this.pspRoleName = pspRoleName; - this.psd2RoleName = psd2RoleName; - } - - public static List getInstance(ASN1Encodable asn1Encodable) { - - List pspRoleList = new ArrayList<>(); - ASN1Sequence sequence = ASN1Sequence.getInstance(asn1Encodable); - - Iterator it = sequence.iterator(); - while (it.hasNext()) { - ASN1ObjectIdentifier objectIdentifier = ASN1ObjectIdentifier.getInstance(it.next()); - ASN1UTF8String instance = DERUTF8String.getInstance(it.next()); - - pspRoleList.add(Arrays.stream(PSPRole.values()) - .filter(role -> role.getPspRoleOid().equals(objectIdentifier.getId()) - && role.getPspRoleName().equals(instance.getString())) - .findFirst().orElseThrow(() -> new IllegalArgumentException( - "unknown object in getInstance: " + asn1Encodable.getClass().getName()))); - } - - return pspRoleList; - } - - - public String getPspRoleOid() { - - return pspRoleOid; - } - - public String getPspRoleName() { - - return pspRoleName; - } - - public String getPsd2RoleName() { - - return psd2RoleName; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSPRoles.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSPRoles.java deleted file mode 100644 index 3e6f4160..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/common/PSPRoles.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.common; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.DERSequence; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Model to hold PSP roles. - */ -public class PSPRoles { - - private final List roles; - - public PSPRoles(List roles) { - - this.roles = roles; - } - - public static PSPRoles getInstance(Object obj) { - - if (obj instanceof PSPRoles) { - return (PSPRoles) obj; - } - - ASN1Encodable[] array = DERSequence.getInstance(obj).toArray(); - - List pspRoles = new ArrayList<>(); - List arrayList = Arrays.asList(array); - for (ASN1Encodable asn1Encodable : arrayList) { - pspRoles.addAll(PSPRole.getInstance(asn1Encodable)); - } - return new PSPRoles(pspRoles); - } - - - public List getRoles() { - - return roles; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/error/CertValidationErrors.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/error/CertValidationErrors.java deleted file mode 100644 index 8a1c9404..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/util/eidas/certificate/extractor/error/CertValidationErrors.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.error; - -/** - * CertValidationErrors class. - */ -public enum CertValidationErrors { - CERTIFICATE_INVALID("Content of the certificate is invalid."), - EXTENSION_NOT_FOUND("X509 V3 Extensions not found in the certificate."), - QCSTATEMENT_INVALID("Invalid QCStatement in the certificate."), - QCSTATEMENTS_NOT_FOUND("QCStatements not found in the certificate."), - PSD2_QCSTATEMENT_NOT_FOUND("No PSD2 QCStatement found in the certificate."); - - private String description; - - CertValidationErrors(String description) { - this.description = description; - } - - @Override - public String toString() { - return description; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/OpenBankingValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/OpenBankingValidator.java deleted file mode 100644 index 44c60e32..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/OpenBankingValidator.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator; - -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; - - -/** - * Common Validator to validate objects based on annotation. - */ -public class OpenBankingValidator { - - public static final Validator FAIL_FAST_VALIDATOR = Validation - .byDefaultProvider().providerResolver(new OsgiServiceDiscoverer()) - .configure().addProperty("hibernate.validator.fail_fast", "true") - .buildValidatorFactory() - .getValidator(); - - private static volatile OpenBankingValidator instance; - - private OpenBankingValidator() { - } - - public static OpenBankingValidator getInstance() { - - if (instance == null) { - synchronized (OpenBankingValidator.class) { - if (instance == null) { - instance = new OpenBankingValidator(); - } - } - } - return instance; - } - - - /** - * Check for violations on request object. Stop at the first violation and return error. - * Validations are executed based on annotation in model of the class. - * - * @param object Object to be validated - * @return Error message if there is a violation, null otherwise - */ - public String getFirstViolation(Object object) { - - Set> violations = FAIL_FAST_VALIDATOR.validate(object); - return violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - } - - public String getFirstViolation(Object object, Class validationGroup) { - - Set> violations = FAIL_FAST_VALIDATOR.validate(object, validationGroup); - return violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/OsgiServiceDiscoverer.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/OsgiServiceDiscoverer.java deleted file mode 100644 index 8ec01ecb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/OsgiServiceDiscoverer.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator; - -import org.hibernate.validator.HibernateValidator; - -import java.util.Collections; -import java.util.List; - -import javax.validation.ValidationProviderResolver; -import javax.validation.spi.ValidationProvider; - -/** - * To discover validation provider in OSGI environment. - */ -public class OsgiServiceDiscoverer implements ValidationProviderResolver { - - @Override - public List> getValidationProviders() { - return Collections.singletonList(new HibernateValidator()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/RequiredParameter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/RequiredParameter.java deleted file mode 100644 index bba01a25..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/RequiredParameter.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.annotation; - -import com.wso2.openbanking.accelerator.common.validator.impl.MandatoryParameterValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation to check required fields. - */ -@Target(ElementType.TYPE) -@Repeatable(RequiredParameters.class) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {MandatoryParameterValidator.class}) -public @interface RequiredParameter { - - String message() default "Mandatory parameter missing"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String param(); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/RequiredParameters.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/RequiredParameters.java deleted file mode 100644 index c53c64d0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/RequiredParameters.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * To enable repeated use of @RequiredParameter. - */ -@Target(ElementType.TYPE) -@Retention(RUNTIME) -@Documented -public @interface RequiredParameters { - RequiredParameter[] value(); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/ValidAudience.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/ValidAudience.java deleted file mode 100644 index 49901df9..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/ValidAudience.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.annotation; - - -import com.wso2.openbanking.accelerator.common.validator.impl.AudienceValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * An annotation to execute audience validation. - */ -@Target(ElementType.TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {AudienceValidator.class}) -public @interface ValidAudience { - - String message() default "Invalid audience given"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String audience() default "aud"; - - String clientId() default "clientId"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/ValidScopeFormat.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/ValidScopeFormat.java deleted file mode 100644 index 0f1f1820..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/annotation/ValidScopeFormat.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.annotation; - -import com.wso2.openbanking.accelerator.common.validator.impl.ScopeValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation to check scope validation. - */ -@Target(ElementType.TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {ScopeValidator.class}) -public @interface ValidScopeFormat { - - String message() default "Invalid scope given in the request"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String scope() default "scope"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/AudienceValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/AudienceValidator.java deleted file mode 100644 index 97b4048d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/AudienceValidator.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.impl; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import com.wso2.openbanking.accelerator.common.validator.annotation.ValidAudience; -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.beanutils.NestedNullException; -import org.apache.commons.beanutils.PropertyUtilsBean; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; - -import java.lang.reflect.InvocationTargetException; -import java.util.List; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - - -/** - * To validate if the audience is the same as the token issuer of the SP. - */ -public class AudienceValidator implements ConstraintValidator { - - private String audienceXpath; - private String clientIdXPath; - private static Log log = LogFactory.getLog(AudienceValidator.class); - - @Override - public void initialize(ValidAudience constraintAnnotation) { - - this.audienceXpath = constraintAnnotation.audience(); - this.clientIdXPath = constraintAnnotation.clientId(); - } - - @Override - public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { - - try { - final Object audiences = new PropertyUtilsBean().getProperty(object, audienceXpath); - final String clientId = BeanUtils.getProperty(object, clientIdXPath); - - return audienceValidate(audiences, clientId); - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | NestedNullException e) { - log.error("Error while resolving validation fields", e); - return false; - } - } - - public boolean audienceValidate(Object aud, String clientId) { - - String issuer; - - try { - issuer = OAuth2Util.getIdTokenIssuer(ServiceProviderUtils.getSpTenantDomain(clientId)); - } catch (IdentityOAuth2Exception | OpenBankingException e) { - log.error("Unable to retrieve the ID token issuer per tenant ", e); - return false; - } - - return validateAudience(issuer, aud); - } - - private boolean validateAudience(String currentAudience, Object audiencesObj) { - - if (audiencesObj instanceof List) { - List audiences = (List) audiencesObj; - for (Object a : audiences) { - if (a instanceof String) { - String aud = (String) a; - if (StringUtils.equals(currentAudience, aud)) { - return true; - } - } - } - } - - return false; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/MandatoryParameterValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/MandatoryParameterValidator.java deleted file mode 100644 index 9181e02c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/MandatoryParameterValidator.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.impl; - -import com.wso2.openbanking.accelerator.common.validator.annotation.RequiredParameter; -import org.apache.commons.beanutils.NestedNullException; -import org.apache.commons.beanutils.PropertyUtilsBean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * To validate if a mandatory parameter is in the object. - */ -public class MandatoryParameterValidator implements ConstraintValidator { - - private String paramXPath; - private static Log log = LogFactory.getLog(MandatoryParameterValidator.class); - - @Override - public void initialize(RequiredParameter constraintAnnotation) { - this.paramXPath = constraintAnnotation.param(); - } - - @Override - public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { - - try { - - final Object parameterValue = new PropertyUtilsBean().getProperty(object, paramXPath); - - if (parameterValue instanceof Integer) { - return (Integer) parameterValue != 0; - - } else if (parameterValue instanceof Boolean) { - return (Boolean) parameterValue; - - } else { - return parameterValue != null; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | NestedNullException e) { - log.error("Mandatory parameter missing", e); - return false; - } - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/ScopeValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/ScopeValidator.java deleted file mode 100644 index f3faf4b7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/java/com/wso2/openbanking/accelerator/common/validator/impl/ScopeValidator.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.validator.impl; - -import com.wso2.openbanking.accelerator.common.validator.annotation.ValidScopeFormat; -import org.apache.commons.beanutils.NestedNullException; -import org.apache.commons.beanutils.PropertyUtilsBean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * To validate if the scope is in the correct format. - */ -public class ScopeValidator implements ConstraintValidator { - - private String scopeXPath; - private static Log log = LogFactory.getLog(ScopeValidator.class); - - @Override - public void initialize(ValidScopeFormat constraintAnnotation) { - this.scopeXPath = constraintAnnotation.scope(); - } - - @Override - public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { - - try { - final Object scope = new PropertyUtilsBean().getProperty(object, scopeXPath); - - return scopeValidate(scope); - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | NestedNullException e) { - log.error("Error while resolving validation fields", e); - return false; - } - } - - boolean scopeValidate(Object scope) { - - if (scope instanceof String) { - ArrayList scopes = new ArrayList<>(Arrays.asList( - ((String) scope).replaceAll("\\s+", " ").trim().split(" "))); - - return scopes.contains("openid"); - } - - return false; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index 3a2ff1ab..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/resources/findbugs-include.xml deleted file mode 100644 index 6773a2ce..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/OBConfigParserTests.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/OBConfigParserTests.java deleted file mode 100644 index 44d6d038..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/OBConfigParserTests.java +++ /dev/null @@ -1,470 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.test.util.CommonTestUtil; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Test class for Config Parser functionality. - */ -public class OBConfigParserTests { - - String absolutePathForTestResources; - - @BeforeClass - public void beforeClass() throws ReflectiveOperationException { - - //to execute util class initialization - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - CommonTestUtil.injectEnvironmentVariable("CARBON_HOME", "."); - String path = "src/test/resources"; - File file = new File(path); - absolutePathForTestResources = file.getAbsolutePath(); - } - - //Runtime exception is thrown here because carbon home is not defined properly for an actual carbon product - @Test(expectedExceptions = OpenBankingRuntimeException.class, priority = 1) - public void testConfigParserInitiationWithoutPath() { - - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(); - - } - - @Test(expectedExceptions = OpenBankingRuntimeException.class, priority = 2) - public void testRuntimeExceptionInvalidConfigFile() { - - String path = absolutePathForTestResources + "/open-banking-empty.xml"; - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(path); - - } - - @Test(expectedExceptions = OpenBankingRuntimeException.class, priority = 3) - public void testRuntimeExceptionNonExistentFile() { - - String path = absolutePathForTestResources + "/open-banking.xml" + "/value"; - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(path); - - } - - @Test(priority = 4) - public void testConfigParserInit() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(dummyConfigFile); - Assert.assertEquals(openBankingConfigParser.getConfiguration().get("Sample.OBHandler"), "DummyValue"); - Assert.assertEquals(openBankingConfigParser.getConfiguration().get("Sample.OBHandler2"), "property.value"); - Assert.assertNotNull(openBankingConfigParser.getConfiguration().get("Sample.OBHandler4")); - Map> openBankingExecutors = - OpenBankingConfigParser.getInstance().getOpenBankingExecutors(); - - openBankingExecutors.get("CustomType1").get(1). - equals("com.wso2.openbanking.accelerator.common.test.CustomHandler2"); - openBankingExecutors.get("CustomType2").get(1). - equals("com.wso2.openbanking.accelerator.common.test.CustomHandler"); - - Map> dcrRegistrationConfigs = OpenBankingConfigParser.getInstance() - .getOpenBankingDCRRegistrationParams(); - - dcrRegistrationConfigs.get("ParameterType").get("Required").equals("true"); - Assert.assertTrue(((List) dcrRegistrationConfigs.get("ParameterType").get("AllowedValues")).contains("Sample")); - - Map> stepsConfig = - OpenBankingConfigParser.getInstance().getConsentAuthorizeSteps(); - - stepsConfig.get("Persist").get(1).equals("com.wso2.openbanking.accelerator.common.test.CustomStep2"); - stepsConfig.get("Retrieve").get(1).equals("com.wso2.openbanking.accelerator.common.test.CustomStep1"); - - Map> apiMap = openBankingConfigParser.getAllowedAPIs(); - List roles = apiMap.get("DynamicClientRegistration"); - Assert.assertNotNull(apiMap); - Assert.assertNotNull(apiMap.get("DynamicClientRegistration")); - Assert.assertTrue(apiMap.get("AccountandTransactionAPI") instanceof List); - Assert.assertTrue(roles.contains("AISP")); - Assert.assertFalse(openBankingConfigParser.getServiceActivatorSubscribers().isEmpty()); - - Map openBankingEventExecutors = - OpenBankingConfigParser.getInstance().getOpenBankingEventExecutors(); - - openBankingEventExecutors.get(1). - equals("com.wso2.openbanking.accelerator.common.test.CustomEventExecutor1"); - openBankingEventExecutors.get(2). - equals("com.wso2.openbanking.accelerator.common.test.CustomEventExecutor2"); - - } - - @Test(priority = 5) - public void testSingleton() { - - OpenBankingConfigParser instance1 = OpenBankingConfigParser.getInstance(); - OpenBankingConfigParser instance2 = OpenBankingConfigParser.getInstance(); - Assert.assertEquals(instance2, instance1); - } - - @Test(priority = 6) - public void testCarbonPath() { - - String carbonConfigDirPath = CarbonUtils.getCarbonConfigDirPath(); - System.setProperty("carbon.config.dir.path", carbonConfigDirPath); - Assert.assertEquals(CarbonUtils.getCarbonConfigDirPath(), carbonConfigDirPath); - } - - @Test(priority = 7) - public void testGetDatasourceName() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String config = OpenBankingConfigParser.getInstance(dummyConfigFile).getDataSourceName(); - Assert.assertNotNull(config); - } - - @Test(priority = 8) - public void testGetConnectionPoolMaxConnections() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - int maxConnections = OpenBankingConfigParser.getInstance(dummyConfigFile).getConnectionPoolMaxConnections(); - int maxConnectionsPerRoute = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getConnectionPoolMaxConnectionsPerRoute(); - - Assert.assertEquals(maxConnections, 1000); - Assert.assertEquals(maxConnectionsPerRoute, 500); - } - - @Test(priority = 8) - public void testConsentPeriodicalExpirationConfigs() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String expirationCronValue = OpenBankingConfigParser.getInstance(dummyConfigFile). - getConsentExpiryCronExpression(); - String wordingForExpiredConsents = OpenBankingConfigParser.getInstance(dummyConfigFile). - getStatusWordingForExpiredConsents(); - String eligibleStatusesForConsentExpiry = OpenBankingConfigParser.getInstance(dummyConfigFile). - getEligibleStatusesForConsentExpiry(); - boolean periodicalJobEnabled = OpenBankingConfigParser.getInstance(dummyConfigFile) - .isConsentExpirationPeriodicalJobEnabled(); - - Assert.assertEquals(expirationCronValue, "0 0 0 * * ?"); - Assert.assertEquals(wordingForExpiredConsents, "Expired"); - Assert.assertEquals(periodicalJobEnabled, false); - Assert.assertEquals(eligibleStatusesForConsentExpiry, "authorised"); - } - - @Test (priority = 9) - public void testGetTrustStoreDynamicLoadingInterval() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - long dynamicLoadingInterval = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getTruststoreDynamicLoadingInterval(); - - Assert.assertEquals(dynamicLoadingInterval, Long.parseLong("86400")); - } - - @Test (priority = 10) - public void testGetAuthServletExtension() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String authServletExtension = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getAuthServletExtension(); - - Assert.assertEquals(authServletExtension, "sampleServletExtension"); - } - - @Test (priority = 11) - public void testGetEmptyCibaServletExtension() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String authServletExtension = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getCibaServletExtension(); - - Assert.assertEquals(authServletExtension, "sampleCIBAServletExtension"); - } - - @Test (priority = 12) - public void testGetJWKSConnectionTimeout() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String connectionTimeOut = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJWKSConnectionTimeOut(); - - Assert.assertEquals(connectionTimeOut, "1000"); - } - - @Test (priority = 13) - public void testGetConnectionVerificationTimeout() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - int connectionTimeOut = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getConnectionVerificationTimeout(); - - Assert.assertEquals(connectionTimeOut, 1000); - } - - @Test (priority = 14) - public void testGetJWKSReadTimeout() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String connectionTimeOut = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJWKSReadTimeOut(); - - Assert.assertEquals(connectionTimeOut, "3000"); - } - - @Test (priority = 15) - public void testGetSPMetadataFilterExtension() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String connectionTimeOut = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getSPMetadataFilterExtension(); - - Assert.assertEquals(connectionTimeOut, "sampleSPMetadataFilterExtension"); - } - - @Test (priority = 16) - public void testGetEventNotificationTokenIssuer() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String tokenIssuer = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getEventNotificationTokenIssuer(); - - Assert.assertEquals(tokenIssuer, "www.wso2.com"); - } - - @Test (priority = 17) - public void testGetNumberOfSetsToReturn() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - int maxEvents = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getNumberOfSetsToReturn(); - - Assert.assertEquals(maxEvents, 5); - } - - @Test (priority = 18) - public void testGetCommonCacheModifiedExpiryTime() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String connectionTimeOut = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getCommonCacheModifiedExpiryTime(); - - Assert.assertEquals(connectionTimeOut, "60"); - } - - @Test (priority = 19) - public void testGetCommonCacheAccessExpiryTime() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String connectionTimeOut = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getCommonCacheAccessExpiryTime(); - - Assert.assertEquals(connectionTimeOut, "60"); - } - - @Test (priority = 20) - public void testGetJwsRequestSigningAlgorithms() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - List algorithmConstraints = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJwsRequestSigningAlgorithms(); - - Assert.assertEquals(algorithmConstraints, Arrays.asList("PS256")); - } - - @Test (priority = 20) - public void testIsJwsSignatureValidationEnabled() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - boolean isEnabled = OpenBankingConfigParser.getInstance(dummyConfigFile) - .isJwsSignatureValidationEnabled(); - - Assert.assertFalse(isEnabled); - } - - @Test (priority = 21) - public void testGetOBIdnRetrieverSigningCertificateAlias() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String certificateAlias = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getOBIdnRetrieverSigningCertificateAlias(); - - Assert.assertEquals(certificateAlias, "wso2carbon"); - } - - @Test (priority = 22) - public void testOBIdnRetrieverSandboxSigningCertificateAlias() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String certificateAlias = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getOBIdnRetrieverSandboxSigningCertificateAlias(); - - Assert.assertEquals(certificateAlias, "wso2carbon-sandbox"); - } - - @Test (priority = 23) - public void testGetOBIdnRetrieverSigningCertificateKid() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String certificateAlias = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getOBIdnRetrieverSigningCertificateKid(); - - Assert.assertEquals(certificateAlias, "1234"); - } - - @Test (priority = 24) - public void testGetJwsResponseSigningAlgorithm() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String certificateAlias = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJwsResponseSigningAlgorithm(); - - Assert.assertEquals(certificateAlias, "PS256"); - } - - @Test (priority = 25) - public void testIsJwsResponseSigningEnabled() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - boolean isEnabled = OpenBankingConfigParser.getInstance(dummyConfigFile) - .isJwsResponseSigningEnabled(); - - Assert.assertEquals(isEnabled, false); - } - - @Test (priority = 26) - public void testGetJwksRetrieverSizeLimit() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String sizeLimit = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJwksRetrieverSizeLimit(); - - Assert.assertEquals(sizeLimit, "51200"); - } - - @Test (priority = 27) - public void testGetJwksRetrieverConnectionTimeout() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String timeout = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJwksRetrieverConnectionTimeout(); - - Assert.assertEquals(timeout, "2000"); - } - - @Test (priority = 28) - public void testGetJwksRetrieverReadTimeout() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String timeout = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getJwksRetrieverReadTimeout(); - - Assert.assertEquals(timeout, "2000"); - } - - @Test (priority = 29) - public void testIsToeClaimIncluded() { - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - Boolean isToeClaimIncluded = OpenBankingConfigParser.getInstance(dummyConfigFile).isToeClaimIncluded(); - - Assert.assertTrue(isToeClaimIncluded); - } - - @Test (priority = 30) - public void testWithRetentionConfigs() { - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(dummyConfigFile); - - Assert.assertTrue(openBankingConfigParser.isConsentDataRetentionEnabled()); - Assert.assertTrue(openBankingConfigParser.isRetentionDataDBSyncEnabled()); - Assert.assertNotNull(openBankingConfigParser.getRetentionDataDBSyncCronExpression()); - Assert.assertNotNull(openBankingConfigParser.getRetentionDataSourceName()); - Assert.assertEquals(openBankingConfigParser.getRetentionDataSourceConnectionVerificationTimeout(), 1); - } - - @Test (priority = 31) - public void testIsDisputeResolutionEnabled() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - boolean isEnabled = OpenBankingConfigParser.getInstance(dummyConfigFile) - .isDisputeResolutionEnabled(); - - Assert.assertTrue(isEnabled); - } - - @Test (priority = 32) - public void testIsNonErrorDisputeDataPublishingEnabled() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - boolean isEnabled = OpenBankingConfigParser.getInstance(dummyConfigFile) - .isNonErrorDisputeDataPublishingEnabled(); - - Assert.assertTrue(isEnabled); - } - - @Test (priority = 33) - public void testRealtimeEventNotificationConfigs() { - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(dummyConfigFile); - - Assert.assertTrue(openBankingConfigParser.isRealtimeEventNotificationEnabled()); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationSchedulerCronExpression(), - "0 0/1 0 ? * * *"); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationTimeoutInSeconds(), 60); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationMaxRetries(), 5); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationInitialBackoffTimeInSeconds(), - 60); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationBackoffFunction(), "EX"); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationCircuitBreakerOpenTimeoutInSeconds(), - 600); - Assert.assertEquals(openBankingConfigParser.getEventNotificationThreadpoolSize(), 20); - Assert.assertEquals(openBankingConfigParser.getRealtimeEventNotificationRequestGenerator(), - "com.wso2.openbanking.accelerator.event.notifications.service.realtime" + - ".service.DefaultRealtimeEventNotificationRequestGenerator"); - - } - - @Test (priority = 34) - public void testIsConsentAmendmentHistoryEnabled() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - boolean isEnabled = OpenBankingConfigParser.getInstance(dummyConfigFile) - .isConsentAmendmentHistoryEnabled(); - - Assert.assertTrue(isEnabled); - } - - @Test (priority = 35) - public void testGetOBKeyManagerExtensionImpl() { - - String dummyConfigFile = absolutePathForTestResources + "/open-banking.xml"; - String className = OpenBankingConfigParser.getInstance(dummyConfigFile) - .getOBKeyManagerExtensionImpl(); - - Assert.assertEquals(className, "com.wso2.openbanking.accelerator.keymanager.OBKeyManagerImpl"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/config/TextFileReaderTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/config/TextFileReaderTest.java deleted file mode 100644 index 0884d150..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/config/TextFileReaderTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.test.config; - -import com.wso2.openbanking.accelerator.common.config.TextFileReader; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.testng.annotations.Test; - -import java.io.IOException; - -/** - * Text file reader test. - */ -public class TextFileReaderTest { - - private static final Log logger = LogFactory.getLog(TextFileReader.class); - - @Test - public void testReadFile() { - - try { - TextFileReader textFileReader = TextFileReader.getInstance(); - textFileReader.setDirectoryPath("src/test/resources"); - String file = textFileReader.readFile("testFile.js"); - Assert.assertNotNull(file); - } catch (IOException e) { - logger.error("Error while reading file", e); - } - } - - @Test - public void testRetrieveFileFromMap() { - - try { - TextFileReader textFileReader = TextFileReader.getInstance(); - String file = textFileReader.readFile("testFile.js"); - Assert.assertNotNull(file); - } catch (IOException e) { - logger.error("Error while reading file", e); - } - } - - @Test(description = "test whether empty string is returned when trying to retrieve non existing file") - public void testRetrieveWrongFile() { - - try { - TextFileReader textFileReader = TextFileReader.getInstance(); - textFileReader.setDirectoryPath("src/test/resources"); - String file = textFileReader.readFile("testFileOne.js"); - Assert.assertEquals(file, ""); - } catch (IOException e) { - logger.error("Error while reading file", e); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/event/executor/OBEventExecutorTests.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/event/executor/OBEventExecutorTests.java deleted file mode 100644 index 9910e26a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/event/executor/OBEventExecutorTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.event.executor; - -import com.wso2.openbanking.accelerator.common.event.executor.DefaultOBEventExecutor; -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import com.wso2.openbanking.accelerator.common.internal.OpenBankingCommonDataHolder; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test for Open Banking event executor. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingCommonDataHolder.class}) -public class OBEventExecutorTests extends PowerMockTestCase { - - private static ByteArrayOutputStream outContent; - private static Logger logger = null; - private static PrintStream printStream; - - @BeforeClass - public void beforeTests() { - - outContent = new ByteArrayOutputStream(); - printStream = new PrintStream(outContent); - System.setOut(printStream); - logger = LogManager.getLogger(OBEventExecutorTests.class); - } - - @Test - public void testAddingDataToQueue() { - - outContent.reset(); - Map configs = new HashMap<>(); - configs.put("Event.WorkerThreadCount", "3"); - configs.put("Event.QueueSize", "10"); - - OBEvent obEvent = new OBEvent("revoked", new HashMap<>()); - - OpenBankingCommonDataHolder openBankingCommonDataHolderMock = mock(OpenBankingCommonDataHolder.class); - mockStatic(OpenBankingCommonDataHolder.class); - when(OpenBankingCommonDataHolder.getInstance()).thenReturn(openBankingCommonDataHolderMock); - - when(openBankingCommonDataHolderMock.getOBEventQueue()).thenReturn(new OBEventQueue(Integer - .parseInt(configs.get("Event.QueueSize").toString()), Integer.parseInt(configs - .get("Event.WorkerThreadCount").toString()))); - - Map obEventExecutors = new HashMap<>(); - obEventExecutors.put(1, DefaultOBEventExecutor.class.getName()); - when(openBankingCommonDataHolderMock.getOBEventExecutors()).thenReturn(obEventExecutors); - - - OBEventQueue obEventQueue = openBankingCommonDataHolderMock.getOBEventQueue(); - - obEventQueue.put(obEvent); - // there should be an error log or a warning if the queue is full. - Assert.assertTrue(outContent.toString().isEmpty()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/CertificateUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/CertificateUtilsTest.java deleted file mode 100644 index 3cfb2c49..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/CertificateUtilsTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.security.cert.X509Certificate; - -/** - * Certificate Util test class. - */ -public class CertificateUtilsTest { - - private X509Certificate expiredX509Cert; - - @BeforeClass - public void init() throws OpenBankingException { - this.expiredX509Cert = CommonTestUtil.getExpiredSelfCertificate(); - } - - @Test(description = "when valid transport cert, return x509 certificate") - public void testParseCertificate() throws OpenBankingException { - Assert.assertNotNull(CertificateUtils - .parseCertificate(CommonTestUtil.TEST_CLIENT_CERT)); - } - - @Test (expectedExceptions = OpenBankingException.class) - public void testParseCertificateWithInvalidCert() throws OpenBankingException { - Assert.assertNull(CertificateUtils - .parseCertificate("-----INVALID CERTIFICATE-----")); - } - - @Test - public void testParseCertificateWithInvalidBase64CharactersCert() throws OpenBankingException { - Assert.assertNotNull(CertificateUtils - .parseCertificate(CommonTestUtil.WRONGLY_FORMATTED_CERT)); - } - - @Test - public void testParseCertificateWithEmptyCert() throws OpenBankingException { - Assert.assertNull(CertificateUtils - .parseCertificate("")); - } - - @Test(description = "when certificate expired, return true") - public void testIsExpiredWithExpiredCert() throws OpenBankingException { - X509Certificate testCert = CertificateUtils - .parseCertificate(CommonTestUtil.EXPIRED_SELF_CERT); - Assert.assertNotNull(testCert); - Assert.assertTrue(CommonTestUtil.hasExpired(testCert)); - } - - @Test(description = "when valid certificate, return false") - public void testIsExpired() throws OpenBankingException { - X509Certificate testCert = CertificateUtils - .parseCertificate(CommonTestUtil.TEST_CLIENT_CERT); - Assert.assertNotNull(testCert); - Assert.assertFalse(CommonTestUtil.hasExpired(testCert)); - } - - @Test - public void testIsCertValidWithExpiredCert() { - Assert.assertTrue(CertificateUtils.isExpired(expiredX509Cert)); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/CommonTestUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/CommonTestUtil.java deleted file mode 100644 index 0d35ddec..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/CommonTestUtil.java +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; - -import java.io.ByteArrayInputStream; -import java.lang.reflect.Field; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Base64; -import java.util.Map; -import java.util.Optional; - -/** - * Utility class for tests. - */ -public class CommonTestUtil { - - public static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; - public static final String END_CERT = "-----END CERTIFICATE-----"; - public static final String X509_CERT_INSTANCE_NAME = "X.509"; - private static X509Certificate expiredSelfCertificate = null; - public static final String EIDAS_CERT = "-----BEGIN CERTIFICATE-----" + - "MIIEjDCCA3SgAwIBAgILAKTSmx6PZuerUKkwDQYJKoZIhvcNAQELBQAwSDELMAkG" + - "A1UEBhMCREUxDDAKBgNVBAoMA0JEUjERMA8GA1UECwwISVQgLSBEZXYxGDAWBgNV" + - "BAMMD1BTRDIgVGVzdCBTdWJDQTAeFw0xODEyMTIxNDIzMjBaFw0xOTA2MTAxNDIz" + - "MjBaMIHFMQswCQYDVQQGEwJERTEkMCIGA1UECgwbSGFuc2VhdGljIEJhbmsgR21i" + - "SCAmIENvIEtHMRAwDgYDVQQHDAdIYW1idXJnMRAwDgYDVQQIDAdoYW1idXJnMSAw" + - "HgYDVQQJDBdCcmFtZmVsZGVyIENoYXVzc2VlIDEwMTEdMBsGA1UEAwwUd3d3Lmhh" + - "bnNlYXRpY2JhbmsuZGUxGzAZBgNVBGETElBTRERFLUJBRklOLTEyMzQ1NjEOMAwG" + - "A1UEERMFMjIxNzcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCq+FfA" + - "Yg8kcypd0HWhZqW8vtm/1KV+CVbertirwc3nbeufIha82kmJr/0ybxPhdJuPSXPA" + - "9YPnGyg4aHBjwGWJhI5sMxynVB6+JrENu1wp4MSUr6BUrNvpiYo7uU2mEe9jEheQ" + - "vqQ45vPw1f2B1YSZgQ5OaSAeLnOqjwDoHseT+mNSJbRznJguwb7hLl78VCuJeYrB" + - "8E1AfJrrKWAVov6TldInq8xP47kspJCheIrEMZskehvuvn11ir24CnTrFe6G4B2v" + - "e5VDR40YbYGD/yD/m8Y2/Y5BGZGw7ty5RqS0ubB99lRkc13KpkAEI45QWQyXVTIF" + - "cORodKZHdoSwcORZAgMBAAGjgfgwgfUwgYgGCCsGAQUFBwEDBHwwejB4BgYEAIGY" + - "JwIwbjA5MBEGBwQAgZgnAQQMBlBTUF9JQzARBgcEAIGYJwECDAZQU1BfUEkwEQYH" + - "BACBmCcBAwwGUFNQX0FJDCdGZWRlcmFsIEZpbmFuY2lhbCBTdXBlcnZpc29yeSBB" + - "dXRob3JpdHkMCERFLUJBRklOMAsGA1UdDwQEAwIFoDAdBgNVHSUEFjAUBggrBgEF" + - "BQcDAQYIKwYBBQUHAwIwGwYDVR0RBBQwEoIQaGFuc2VhdGljYmFuay5kZTAfBgNV" + - "HSMEGDAWgBRczgCARJu0XDNe5JrFOPI4CIgFojANBgkqhkiG9w0BAQsFAAOCAQEA" + - "l8IGrflLcPpmpKIxlmASRtPk96Dh5E3Is2dDCO/yiv2TKoBjyGRYLSPKD7mS1YBr" + - "g2/l2yPK6+5V5n/pIZ3V8SezfFlzs65i1Jc9XwB/236BjgRMXuAMJmB0Rjo31Nd0" + - "o/FAOEvIpNh0+GVz6SnY07qry2BWCYAqyHSih20Wjj6yOHHvQtXRaQijQSwo5WGS" + - "grHH0Thh+MBlyc8iNajrrNxKRYWyXrpGpukMOR4CYWp2CeC22+zLQIEI9gcnl0hr" + - "/yBbG/db3ZujZvjW34KreOkxjzc+/bhQlubv7KrSruj1OoDzq8e+ELCoNII2JU3h" + - "R783WZESc2tbq1LYOH5wNg==" + - "-----END CERTIFICATE-----"; - public static final String TEST_CLIENT_CERT = "-----BEGIN CERTIFICATE-----" + - "MIIFLTCCBBWgAwIBAgIEWcbiiDANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJH" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNVBAMTJU9wZW5CYW5raW5nIFBy" + - "ZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwHhcNMjMxMTE1MDUxMDA4WhcNMjQxMjE1" + - "MDU0MDA4WjBhMQswCQYDVQQGEwJHQjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxGzAZ" + - "BgNVBAsTEjAwMTU4MDAwMDFIUVFyWkFBWDEfMB0GA1UEAxMWakZRdVE0ZVFiTkNN" + - "U3FkQ29nMjFuRjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKi36HD0" + - "prx1N3pfafJc6pSMg0i0jOiQrt+WZ6GphKUhA2JrbBxWTvabX1Q7hifl5UbkBOkn" + - "n3SCyqBplPSqksYLdPSckb2J7UVLj76O7RkELoFD+vSrQ8FWEn8lXv4UiS8ylvlr" + - "IPa8+pVtAwOuI3/YFmqB1lcHgBI8EELDUWHXSp3OhkcKjrm76t1sQz0tsmi5aHZR" + - "3FXb0dACQO+dGakIerqzUmAdccLtWuSJMT+b7c7IDDm/IR/MV7iol04yeBkOlWre" + - "IKOqHU16PI3N/PSMEt96JAUKZ/n0VC0x4YHaBYDX27sf4Gypubgmkcd4IbG/8XEu" + - "Hq3Ik84oEpP5QEUCAwEAAaOCAfkwggH1MA4GA1UdDwEB/wQEAwIGwDAVBgNVHSUE" + - "DjAMBgorBgEEAYI3CgMMMIHgBgNVHSAEgdgwgdUwgdIGCysGAQQBqHWBBgFkMIHC" + - "MCoGCCsGAQUFBwIBFh5odHRwOi8vb2IudHJ1c3Rpcy5jb20vcG9saWNpZXMwgZMG" + - "CCsGAQUFBwICMIGGDIGDVXNlIG9mIHRoaXMgQ2VydGlmaWNhdGUgY29uc3RpdHV0" + - "ZXMgYWNjZXB0YW5jZSBvZiB0aGUgT3BlbkJhbmtpbmcgUm9vdCBDQSBDZXJ0aWZp" + - "Y2F0aW9uIFBvbGljaWVzIGFuZCBDZXJ0aWZpY2F0ZSBQcmFjdGljZSBTdGF0ZW1l" + - "bnQwbQYIKwYBBQUHAQEEYTBfMCYGCCsGAQUFBzABhhpodHRwOi8vb2IudHJ1c3Rp" + - "cy5jb20vb2NzcDA1BggrBgEFBQcwAoYpaHR0cDovL29iLnRydXN0aXMuY29tL29i" + - "X3BwX2lzc3VpbmdjYS5jcnQwOgYDVR0fBDMwMTAvoC2gK4YpaHR0cDovL29iLnRy" + - "dXN0aXMuY29tL29iX3BwX2lzc3VpbmdjYS5jcmwwHwYDVR0jBBgwFoAUUHORxiFy" + - "03f0/gASBoFceXluP1AwHQYDVR0OBBYEFKjCef/JxD+ND9eSb7hQlmEhSxUqMA0G" + - "CSqGSIb3DQEBCwUAA4IBAQCnKH9FdLmJMruX2qfbrpT0qaV8bP7xa9UDRYSMsAWC" + - "2kqCxs8CJmARt5+xsxBW6P65+mkLS2vXgQl7J8RTMiQVnHJvvNaldYnV6odsYOqv" + - "v+vGib8Qe0gKWSjih+Gd1Ct4UQFtn6P3ph+6OBB0OieZb7DYXqPJrX5UlG7K2fQ4" + - "0MdFgBdeQZ3iNkXi43UIrQ5cF4cjYavmEFRmYeHya8AKfNCiWly15mNazW/X6SWf" + - "7pz+yk/l+gBv0wm3QT7ANXGf8izgoh6T5fmixPXSbdn8RUIV0kXp2TRRZ+CYUWBP" + - "Jc3PvRXiiEEo2eHLXfEHG2jzrt1iKnjk6hzuC1hUzK0t" + - "-----END CERTIFICATE-----"; - public static final String EXPIRED_SELF_CERT = "-----BEGIN CERTIFICATE-----" + - "MIIDiTCCAnGgAwIBAgIENx3SZjANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJs" + - "azEQMA4GA1UECBMHd2VzdGVybjEQMA4GA1UEBxMHY29sb21ibzENMAsGA1UEChME" + - "d3NvMjEUMBIGA1UECxMLb3BlbmJhbmtpbmcxHTAbBgNVBAMTFG9wZW5iYW5raW5n" + - "LndzbzIuY29tMB4XDTIwMDMwMTEyMjE1MVoXDTIwMDUzMDEyMjE1MVowdTELMAkG" + - "A1UEBhMCbGsxEDAOBgNVBAgTB3dlc3Rlcm4xEDAOBgNVBAcTB2NvbG9tYm8xDTAL" + - "BgNVBAoTBHdzbzIxFDASBgNVBAsTC29wZW5iYW5raW5nMR0wGwYDVQQDExRvcGVu" + - "YmFua2luZy53c28yLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB" + - "AKWMb1mhSthxi5vmQcvEnt0rauYv8uFWjGyiuCkk5wQbArybGXyC8rrZf5qNNY4s" + - "RG2+Yimxph2Z8MWWPFBebTIABPuRcVDquX7fL4+8FZJTH3JLwfT+slunAA4473mZ" + - "9s2fAVu6CmQf1V09+fEbMGI9WWh53g19wg5WdlToOX4g5lh4QtGRpbWpEWaYrKzS" + - "B5EWOUI7lroFtv6s9OpEO59VAkXWKUbT98T8TCYqiDH+nMy3k+GbVawxXeHYHQr+" + - "XlbcChPaCwhMXspqKG49xaJmrOuRMoAWCBGUW8r2RDhQ+FP5V/sTRMqKmBv9gTe6" + - "RJwoKPlDt+0aX9vaFjKpjPcCAwEAAaMhMB8wHQYDVR0OBBYEFGH0gyeHIz1+ONGI" + - "PuGnAhrS3apoMA0GCSqGSIb3DQEBCwUAA4IBAQCVEakh1SLnZOz2IK0ISbAV5UBb" + - "nerLNDl+X+YSYsCQM1SBcXDjlkSAeP3ErJEO3RW3wdRQjLRRHomwSCSRE84SUfSL" + - "VPIbeR7jm4sS9x5rnlGF6iqhYh2MlZD/hFxdrGoYv8g/JN4FFFMXRmmaQ8ouYJwc" + - "4ZoxRdCXszeI5Zp2+b14cs/nf4geYliHtcDr/w7fkvQ0hn+c1lTihbW0/eE32aUK" + - "SULAmjx0sCDfDAQItP79CC7jCW0TFN0CMORw/+fzp/dnVboSZ2MgcuRIH1Ez+6/1" + - "1QJD2SrkkaRSEaXI6fe9jgHVhnqK9V3y3WAuzEKjaKw6jV8BjkXAA4dQj1Re" + - "-----END CERTIFICATE-----"; - - public static final String WRONGLY_FORMATTED_CERT = "-----BEGIN CERTIFICATE-----\n" + - "MIIFljCCA36gAwIBAgIJAN5zDsVzPq0aMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYD " + - "VQQGEwJMSzELMAkGA1UECAwCV1AxDDAKBgNVBAcMA0NPTDEaMBgGA1UECgwRV1NP" + - "MiAoVUspIExJTUlURUQxFDASBgNVBAsMC09wZW5CYW5raW5nMS4wLAYDVQQDDCVP" + - "cGVuQmFua2luZyBQcmUtUHJvZHVjdGlvbiBJc3N1aW5nIENBMSAwHgYJKoZIhvcN" + - "AQkBFhFtYWxzaGFuaUB3c28yLmNvbTAeFw0yMjAxMTgwNzI3NDJaFw0yNDAxMTgw" + - "NzI3NDJaMHMxCzAJBgNVBAYTAkdCMRowGAYDVQQKDBFXU08yIChVSykgTElNSVRF" + - "RDErMCkGA1UEYQwiUFNER0ItT0ItVW5rbm93bjAwMTU4MDAwMDFIUVFyWkFBWDEb" + - "MBkGA1UEAwwSMDAxNTgwMDAwMUhRUXJaQUFYMIIBIjANBgkqhkiG9w0BAQEFAAOC" + - "AQ8AMIIBCgKCAQEA59+TouW8sLFWk7MUht40v+DDglinjL2qmQ+wP3YNtvza/7Ue" + - "KZ+gWw92jd0v99xZz7c5KOgtTgctAmIU1qjGLwzHzn/fl/ZrO4spGLIbU7RwGHA7" + - "BSpB4k0vGdpCBigaaILHhBrAczDJ1BLYMS4lg69+6fYTeY2s0Khv92NWl8TXorAH" + - "W0D8KrbZ3chWIynZamNu8KN6s+GL5jyu6pzJpXVNOXiUdRr4U9fLctw7qPw4RbBM" + - "edXohmVFwMTQ7lMKax+wHOjfQDQW7KuZxRRYiUqB3hjyhrKlIpjjWtnxLclymTAI" + - "TRMqFlH8KFq/rVBGQ8F3SnDp90E25RbSWdfNRwIDAQABo4HyMIHvMA4GA1UdDwEB" + - "/wQEAwIHgDAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwHQYDVR0OBBYE" + - "FNxNxhzaeU3VdIMlXkNiYbnjheOnMIGeBggrBgEFBQcBAwSBkTCBjjATBgYEAI5G" + - "AQYwCQYHBACORgEGAzB3BgYEAIGYJwIwbTBGMEQGBwQAgZgnAQEMBlBTUF9BUwYH" + - "BACBmCcBAgwGUFNQX1BJBgcEAIGYJwEDDAZQU1BfQUkGBwQAgZgnAQQMBlBTUF9J" + - "QwwbRmluYW5jaWFsIENvbmR1Y3QgQXV0aG9yaXR5DAZHQi1GQ0EwDQYJKoZIhvcN" + - "AQEFBQADggIBABBM63bCwANVRR44wFCZysbppYAT4mms3dUqoP3XCUXaO3+7zNWa" + - "siZ90cje3fuiTD5SAyykm/I/mlgVx92ZbYFW0VG7IVkuC7Fid5iPywHX7Bm1xmEY" + - "bL1AtAm4sBzE1Kw5dnB1L30do7sp9fuJCdom5/fhrh2GyLBd0iA62qQ+F9uALrC0" + - "bub0KnGaEf9g1UltgxuqguoYoHb46ICJ03kMGZMC5BcjDDEbDQQ3kT+g9evaBUBm" + - "3A3cNJURF7/07iLEfHNYrMxDLIw6aC4svbcx+IquO81xpTCefhTU4UFSLN1/DXWW" + - "qrjCqkvHE53mb33QCXmnsooTP8pABG2q2+w5EC9yeX6Fln6M8VwZL5P2stELWXZE" + - "876kCo0LkmoP3s6Z62bF4u9hJvM9mQRvmDVqN2Y7eLMty4qmGEmAYYiHOG+FXNKo" + - "io9MXbB3B7tdeM4g2HlQGfRIrTrfAOu2cH1l1ZwHZgx7oCXN1nuZgE3r07kJx4Bn" + - "DXCRpXoZq4pB3AlzcWEPh51/SS8Wsz52CNSDGoMB7HPkNnoDrYoibb1LFrOwJ3IM" + - "VUKCSnt1QdnrKtMVMTd0iI4uk7kCKt7QFeiizN+oW6BI/MNm6mHEWd9CKWmrZT56" + - "wU3ZM7vgwugq9tAs+oi8Lf3ZODuXAsiSpgcd6dceatoqeyB4E+6kp0Ge" + - "-----END CERTIFICATE-----"; - - public static void injectEnvironmentVariable(String key, String value) - throws ReflectiveOperationException { - - Class processEnvironment = Class.forName("java.lang.ProcessEnvironment"); - - Field unmodifiableMapField = getAccessibleField(processEnvironment, "theUnmodifiableEnvironment"); - Object unmodifiableMap = unmodifiableMapField.get(null); - injectIntoUnmodifiableMap(key, value, unmodifiableMap); - - Field mapField = getAccessibleField(processEnvironment, "theEnvironment"); - Map map = (Map) mapField.get(null); - map.put(key, value); - } - - private static Field getAccessibleField(Class clazz, String fieldName) - throws NoSuchFieldException { - - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - return field; - } - - public static synchronized X509Certificate getExpiredSelfCertificate() - throws OpenBankingException { - if (expiredSelfCertificate == null) { - expiredSelfCertificate = CertificateUtils.parseCertificate(EXPIRED_SELF_CERT); - } - return expiredSelfCertificate; - } - - private static void injectIntoUnmodifiableMap(String key, String value, Object map) - throws ReflectiveOperationException { - - Class unmodifiableMap = Class.forName("java.util.Collections$UnmodifiableMap"); - Field field = getAccessibleField(unmodifiableMap, "m"); - Object obj = field.get(map); - ((Map) obj).put(key, value); - } - - public static Optional parseTransportCert(String strTransportCert) throws CertificateException { - - // decoding pem formatted transport cert - byte[] decodedTransportCert = Base64.getDecoder().decode(strTransportCert - .replace(BEGIN_CERT, "").replace(END_CERT, "")); - - X509Certificate transportCert = (X509Certificate) CertificateFactory.getInstance(X509_CERT_INSTANCE_NAME) - .generateCertificate(new ByteArrayInputStream(decodedTransportCert)); - - return Optional.ofNullable(transportCert); - } - - /** - * Test util method to check cert expiry. - * - * @param peerCertificate - * @return - */ - public static boolean hasExpired(X509Certificate peerCertificate) { - try { - peerCertificate.checkValidity(); - } catch (CertificateException e) { - return true; - } - return false; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/HTTPClientUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/HTTPClientUtilsTest.java deleted file mode 100644 index c58d9484..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/HTTPClientUtilsTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.io.File; - -/** - * Http Client util test. - */ -public class HTTPClientUtilsTest { - - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - - @Test - public void testLoadKeystore() throws OpenBankingException { - - Assert.assertNotNull(HTTPClientUtils.loadKeyStore(absolutePathForTestResources + "/wso2carbon.jks", - "wso2carbon")); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testLoadInvalidKeystore() throws OpenBankingException { - - HTTPClientUtils.loadKeyStore(absolutePathForTestResources + "/wso2carbon2.jks", - "wso2carbon"); - } - - @Test - public void testHostNameVerifier() throws OpenBankingException { - - Assert.assertEquals(HTTPClientUtils.getX509HostnameVerifier(), - SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - System.setProperty(HTTPClientUtils.HOST_NAME_VERIFIER, - String.valueOf(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)); - - Assert.assertEquals(HTTPClientUtils.getX509HostnameVerifier(), - SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - System.setProperty(HTTPClientUtils.HOST_NAME_VERIFIER, - String.valueOf(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER)); - - Assert.assertEquals(HTTPClientUtils.getX509HostnameVerifier(), - SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/JWTUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/JWTUtilsTest.java deleted file mode 100644 index 0658d00c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/JWTUtilsTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.test.util.testutils.JWTUtilsTestDataProvider; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.util.Date; - -/** - * Test class for Unit Testing JWTUtils. - */ -public class JWTUtilsTest { - - @Test(dataProviderClass = JWTUtilsTestDataProvider.class, dataProvider = "jwtStrings") - public void testIsJWT(String jwtString, boolean expected) { - - Assert.assertEquals(JWTUtils.isValidJWSFormat(jwtString), expected); - } - - @Test(dataProviderClass = JWTUtilsTestDataProvider.class, dataProvider = "validParsableJwtStrings") - public void testGetSignedJWT(String jwtString) throws ParseException { - - Assert.assertNotNull(JWTUtils.getSignedJWT(jwtString)); - } - - @Test(expectedExceptions = ParseException.class, - dataProviderClass = JWTUtilsTestDataProvider.class, dataProvider = "validNotParsableJwtStrings") - public void testGetSignedJWTWIthNotParsableJWT(String jwtString) throws ParseException { - - JWTUtils.getSignedJWT(jwtString); - } - - @Test(expectedExceptions = IllegalArgumentException.class, - dataProviderClass = JWTUtilsTestDataProvider.class, dataProvider = "notValidJwtStrings") - public void testGetSignedJWTWIthNotValidJWT(String jwtString) throws ParseException { - - JWTUtils.getSignedJWT(jwtString); - } - - @Test(dataProviderClass = JWTUtilsTestDataProvider.class, dataProvider = "expiryTimeProvider") - public void testValidExpirationTime(Date time, long timeSkew, boolean expected) { - - Assert.assertEquals(JWTUtils.isValidExpiryTime(time, timeSkew), expected); - } - - @Test(dataProviderClass = JWTUtilsTestDataProvider.class, dataProvider = "nbfProvider") - public void testValidNotValidBefore(Date time, long timeSkew, boolean expected) { - - Assert.assertEquals(JWTUtils.isValidNotValidBeforeTime(time, timeSkew), expected); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/OpenBankingUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/OpenBankingUtilsTest.java deleted file mode 100644 index 5a408663..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/OpenBankingUtilsTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.identity.IdentityConstants; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.text.ParseException; - -import static org.mockito.Mockito.when; - - -/** - * Test for Open Banking Utils. - */ -@PrepareForTest({OpenBankingConfigParser.class}) -@PowerMockIgnore({"jdk.internal.reflect.*", "javax.management.*"}) -public class OpenBankingUtilsTest extends PowerMockTestCase { - - private static final Log log = LogFactory.getLog(OpenBankingUtilsTest.class); - @Mock - OpenBankingConfigParser openBankingConfigParser; - - @BeforeMethod() - public void before() { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - openBankingConfigParser = PowerMockito.mock(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - } - - @Test(priority = 1) - public void getSoftwareEnvironmentFromSSA() throws ParseException { - String sandboxSsa = "eyJ0eXAiOiJKV1QiLCJraWQiOiJoM1pDRjBWcnpnWGduSENxYkhiS1h6emZqVGciLCJhbGciOiJQUzI1NiJ9." + - "eyJpYXQiOjE2OTg2ODQ4MjUsIm5iZiI6MTY5ODY4NDgyMSwiZXhwIjoxNjk4Njg4NDI2LCJqdGkiOiIyNDdlNjdmNjBmODA0YT" + - "k5MTY5ODY4NDgyNSIsImlzcyI6Ik9wZW5CYW5raW5nIEx0ZCIsInNvZnR3YXJlX2Vudmlyb25tZW50Ijoic2FuZGJveCIsInNv" + - "ZnR3YXJlX21vZGUiOiJUZXN0Iiwic29mdHdhcmVfaWQiOiIxMlp6RkZCeFNMR0VqUFpvZ1JBYnZGZHMxMTY5ODY4NDgyNSIsIn" + - "NvZnR3YXJlX2NsaWVudF9pZCI6IjEwWnpGRkJ4U0xHRWpQWm9nUkFidkZkczEiLCJzb2Z0d2FyZV9jbGllbnRfbmFtZSI6IldT" + - "TzIgT3BlbiBCYW5raW5nIFRQUCAoU2FuZGJveCkiLCJzb2Z0d2FyZV9jbGllbnRfZGVzY3JpcHRpb24iOiJXU08yIE9wZW4gQm" + - "Fua2luZyBUUFAgZm9yIHRlc3RpbmciLCJzb2Z0d2FyZV92ZXJzaW9uIjoxLjUsInNvZnR3YXJlX2NsaWVudF91cmkiOiJodHRw" + - "czovL3d3dy5nb29nbGUuY29tIiwic29mdHdhcmVfcmVkaXJlY3RfdXJpcyI6WyJodHRwczovL3d3dy5nb29nbGUuY29tL3JlZG" + - "lyZWN0cy9yZWRpcmVjdDEiXSwic29mdHdhcmVfcm9sZXMiOlsiUElTUCIsIkFJU1AiLCJDQlBJSSJdLCJvcmdhbmlzYXRpb25f" + - "Y29tcGV0ZW50X2F1dGhvcml0eV9jbGFpbXMiOnsiYXV0aG9yaXR5X2lkIjoiT0JHQlIiLCJyZWdpc3RyYXRpb25faWQiOiJVbm" + - "tub3duMDAxNTgwMDAwMUhRUXJaQUFYIiwic3RhdHVzIjoiQWN0aXZlIiwiYXV0aG9yaXNhdGlvbnMiOlt7Im1lbWJlcl9zdGF0" + - "ZSI6IkdCIiwicm9sZXMiOlsiUElTUCIsIkFJU1AiLCJDQlBJSSJdfSx7Im1lbWJlcl9zdGF0ZSI6IklFIiwicm9sZXMiOlsiUE" + - "lTUCIsIkNCUElJIiwiQUlTUCJdfSx7Im1lbWJlcl9zdGF0ZSI6Ik5MIiwicm9sZXMiOlsiUElTUCIsIkFJU1AiLCJDQlBJSSJd" + - "fV19LCJzb2Z0d2FyZV9sb2dvX3VyaSI6Imh0dHBzOi8vd3d3Lmdvb2dsZS5jb20iLCJvcmdfc3RhdHVzIjoiQWN0aXZlIiwib3" + - "JnX2lkIjoiMDAxNTgwMDAwMUhRUXJaQUFYIiwib3JnX25hbWUiOiJXU08yIChVSykgTElNSVRFRCIsIm9yZ19jb250YWN0cyI6" + - "W3sibmFtZSI6IlRlY2huaWNhbCIsImVtYWlsIjoic2FjaGluaXNAd3NvMi5jb20iLCJwaG9uZSI6Iis5NDc3NDI3NDM3NCIsIn" + - "R5cGUiOiJUZWNobmljYWwifSx7Im5hbWUiOiJCdXNpbmVzcyIsImVtYWlsIjoic2FjaGluaXNAd3NvMi5jb20iLCJwaG9uZSI6" + - "Iis5NDc3NDI3NDM3NCIsInR5cGUiOiJCdXNpbmVzcyJ9XSwib3JnX2p3a3NfZW5kcG9pbnQiOiJodHRwczovL2tleXN0b3JlLm" + - "9wZW5iYW5raW5ndGVzdC5vcmcudWsvMDAxNTgwMDAwMUhRUXJaQUFYLzAwMTU4MDAwMDFIUVFyWkFBWC5qd2tzIiwib3JnX2p3" + - "a3NfcmV2b2tlZF9lbmRwb2ludCI6Imh0dHBzOi8va2V5c3RvcmUub3BlbmJhbmtpbmd0ZXN0Lm9yZy51ay8wMDE1ODAwMDAxSF" + - "FRclpBQVgvcmV2b2tlZC8wMDE1ODAwMDAxSFFRclpBQVguandrcyIsInNvZnR3YXJlX2p3a3NfZW5kcG9pbnQiOiJodHRwczov" + - "L2tleXN0b3JlLm9wZW5iYW5raW5ndGVzdC5vcmcudWsvMDAxNTgwMDAwMUhRUXJaQUFYLzAwMTU4MDAwMDFIUVFyWkFBWC5qd2" + - "tzIiwic29mdHdhcmVfandrc19yZXZva2VkX2VuZHBvaW50IjoiaHR0cHM6Ly9rZXlzdG9yZS5vcGVuYmFua2luZ3Rlc3Qub3Jn" + - "LnVrLzAwMTU4MDAwMDFIUVFyWkFBWC9yZXZva2VkLzlaekZGQnhTTEdFalBab2dSQWJ2RmQuandrcyIsInNvZnR3YXJlX3BvbG" + - "ljeV91cmkiOiJodHRwczovL3d3dy5nb29nbGUuY29tIiwic29mdHdhcmVfdG9zX3VyaSI6Imh0dHBzOi8vd3d3Lmdvb2dsZS5j" + - "b20iLCJzb2Z0d2FyZV9vbl9iZWhhbGZfb2Zfb3JnIjpudWxsfQ.SUZaSo0sEfBU2ffN73IqNG8KAoYEO8vUIrZHBOxA-gF5dKN" + - "IZR6pQ9cnuc3NzhmfHr9TAhiC_KVV9ULiwg0Kh0V79z57Ykjz6NuZ8m0tZPQbjOMQBrRXdnLkqqot_pO_2vwLCRFDfhWM2wqR4" + - "lTXkM0KsdNSWgG3vl25JTkwqo1tTsYlZUcQFltlLQ-lCXT2nWnu_dPZWUqzVb9g4s2DcQ78xkJwqHJKgGLsloXzAMDx36MZQ01" + - "fHP2eIFu82D0PgsxqvHbNeyXVlg5XsX5TLRwrRy8W4wP_SLMoP7jDic0yEufBRULROX2ckpoZuk31a_QyaJFKtIiPj9zlltM9Zg"; - PowerMockito.when(OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyValueForSandbox()).thenReturn("sandbox"); - PowerMockito.when(OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyName()).thenReturn("software_environment"); - String softwareEnvironmentFromSSA = OpenBankingUtils.getSoftwareEnvironmentFromSSA(sandboxSsa); - Assert.assertEquals(softwareEnvironmentFromSSA, IdentityConstants.SANDBOX); - } - - @Test() - public void getSoftwareEnvironmentFromSSAForProd() throws ParseException { - String prodSsa = "eyJ0eXAiOiJKV1QiLCJraWQiOiJoM1pDRjBWcnpnWGduSENxYkhiS1h6emZqVGciLCJhbGciOiJQUzI1NiJ9." + - "eyJpYXQiOjE2OTg2ODQ4MjUsIm5iZiI6MTY5ODY4NDgyMSwiZXhwIjoxNjk4Njg4NDI2LCJqdGkiOiIyNDdlNjdmNjBmODA0YT" + - "k5MTY5ODY4NDgyNSIsImlzcyI6Ik9wZW5CYW5raW5nIEx0ZCIsInNvZnR3YXJlX2Vudmlyb25tZW50IjoicHJvZCIsInNvZnR3" + - "YXJlX21vZGUiOiJUZXN0Iiwic29mdHdhcmVfaWQiOiIxMlp6RkZCeFNMR0VqUFpvZ1JBYnZGZHMxMTY5ODY4NDgyNSIsInNvZn" + - "R3YXJlX2NsaWVudF9pZCI6IjEwWnpGRkJ4U0xHRWpQWm9nUkFidkZkczEiLCJzb2Z0d2FyZV9jbGllbnRfbmFtZSI6IldTTzIg" + - "T3BlbiBCYW5raW5nIFRQUCAoU2FuZGJveCkiLCJzb2Z0d2FyZV9jbGllbnRfZGVzY3JpcHRpb24iOiJXU08yIE9wZW4gQmFua2" + - "luZyBUUFAgZm9yIHRlc3RpbmciLCJzb2Z0d2FyZV92ZXJzaW9uIjoxLjUsInNvZnR3YXJlX2NsaWVudF91cmkiOiJodHRwczov" + - "L3d3dy5nb29nbGUuY29tIiwic29mdHdhcmVfcmVkaXJlY3RfdXJpcyI6WyJodHRwczovL3d3dy5nb29nbGUuY29tL3JlZGlyZW" + - "N0cy9yZWRpcmVjdDEiXSwic29mdHdhcmVfcm9sZXMiOlsiUElTUCIsIkFJU1AiLCJDQlBJSSJdLCJvcmdhbmlzYXRpb25fY29t" + - "cGV0ZW50X2F1dGhvcml0eV9jbGFpbXMiOnsiYXV0aG9yaXR5X2lkIjoiT0JHQlIiLCJyZWdpc3RyYXRpb25faWQiOiJVbmtub3" + - "duMDAxNTgwMDAwMUhRUXJaQUFYIiwic3RhdHVzIjoiQWN0aXZlIiwiYXV0aG9yaXNhdGlvbnMiOlt7Im1lbWJlcl9zdGF0ZSI6" + - "IkdCIiwicm9sZXMiOlsiUElTUCIsIkFJU1AiLCJDQlBJSSJdfSx7Im1lbWJlcl9zdGF0ZSI6IklFIiwicm9sZXMiOlsiUElTUC" + - "IsIkNCUElJIiwiQUlTUCJdfSx7Im1lbWJlcl9zdGF0ZSI6Ik5MIiwicm9sZXMiOlsiUElTUCIsIkFJU1AiLCJDQlBJSSJdfV19" + - "LCJzb2Z0d2FyZV9sb2dvX3VyaSI6Imh0dHBzOi8vd3d3Lmdvb2dsZS5jb20iLCJvcmdfc3RhdHVzIjoiQWN0aXZlIiwib3JnX2" + - "lkIjoiMDAxNTgwMDAwMUhRUXJaQUFYIiwib3JnX25hbWUiOiJXU08yIChVSykgTElNSVRFRCIsIm9yZ19jb250YWN0cyI6W3si" + - "bmFtZSI6IlRlY2huaWNhbCIsImVtYWlsIjoic2FjaGluaXNAd3NvMi5jb20iLCJwaG9uZSI6Iis5NDc3NDI3NDM3NCIsInR5cG" + - "UiOiJUZWNobmljYWwifSx7Im5hbWUiOiJCdXNpbmVzcyIsImVtYWlsIjoic2FjaGluaXNAd3NvMi5jb20iLCJwaG9uZSI6Iis5" + - "NDc3NDI3NDM3NCIsInR5cGUiOiJCdXNpbmVzcyJ9XSwib3JnX2p3a3NfZW5kcG9pbnQiOiJodHRwczovL2tleXN0b3JlLm9wZW" + - "5iYW5raW5ndGVzdC5vcmcudWsvMDAxNTgwMDAwMUhRUXJaQUFYLzAwMTU4MDAwMDFIUVFyWkFBWC5qd2tzIiwib3JnX2p3a3Nf" + - "cmV2b2tlZF9lbmRwb2ludCI6Imh0dHBzOi8va2V5c3RvcmUub3BlbmJhbmtpbmd0ZXN0Lm9yZy51ay8wMDE1ODAwMDAxSFFRcl" + - "pBQVgvcmV2b2tlZC8wMDE1ODAwMDAxSFFRclpBQVguandrcyIsInNvZnR3YXJlX2p3a3NfZW5kcG9pbnQiOiJodHRwczovL2tl" + - "eXN0b3JlLm9wZW5iYW5raW5ndGVzdC5vcmcudWsvMDAxNTgwMDAwMUhRUXJaQUFYLzAwMTU4MDAwMDFIUVFyWkFBWC5qd2tzIi" + - "wic29mdHdhcmVfandrc19yZXZva2VkX2VuZHBvaW50IjoiaHR0cHM6Ly9rZXlzdG9yZS5vcGVuYmFua2luZ3Rlc3Qub3JnLnVr" + - "LzAwMTU4MDAwMDFIUVFyWkFBWC9yZXZva2VkLzlaekZGQnhTTEdFalBab2dSQWJ2RmQuandrcyIsInNvZnR3YXJlX3BvbGljeV" + - "91cmkiOiJodHRwczovL3d3dy5nb29nbGUuY29tIiwic29mdHdhcmVfdG9zX3VyaSI6Imh0dHBzOi8vd3d3Lmdvb2dsZS5jb20i" + - "LCJzb2Z0d2FyZV9vbl9iZWhhbGZfb2Zfb3JnIjpudWxsfQ.NLglx-H9D-i2f9GmSrxq00wTlKGHW_6zmKxGg_UhX0P0dzqJmNW" + - "UCDBdz-HhjlPSGeLqumyM_hJZELGv96p6CllmHdNA12gIGem3oBqnaPq9wfcr5Esn7sfRODPComjr6lKxNSXraLT7qpRHCJoxq" + - "yi72RH7T6HyF5lobTHWcZRkCNtc9cWJMKbftGCDSGRlO0XSYvvdGMDBCQT5-KiuKiWcKcBcFX2TLpTDDYaf-GNtATQ0O_vl266" + - "fDPyzG9XF6NLheG0ITrTBGuVN2JzSDC50_vCqR754LtFKNLXKQ2WTnrY3TgEBbyaKj3N0_YdDIuT442zkadg8lvoNpXyk4A"; - - PowerMockito.when(OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyValueForSandbox()).thenReturn("sandbox"); - PowerMockito.when(OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyName()).thenReturn("software_environment"); - String softwareEnvironmentFromSSA = OpenBankingUtils.getSoftwareEnvironmentFromSSA(prodSsa); - Assert.assertEquals(softwareEnvironmentFromSSA, IdentityConstants.PRODUCTION); - } - - @Test - public void testDisputeDataWhenNonErrorPublishingEnabled() throws Exception { - - when(openBankingConfigParser.isNonErrorDisputeDataPublishingEnabled()).thenReturn(true); - - Assert.assertTrue(OpenBankingUtils.isPublishableDisputeData(400)); - Assert.assertTrue(OpenBankingUtils.isPublishableDisputeData(200)); - } - - @Test - public void testDisputeDataWhenNonErrorPublishingDisabled() throws Exception { - - when(openBankingConfigParser.isNonErrorDisputeDataPublishingEnabled()).thenReturn(false); - - Assert.assertTrue(OpenBankingUtils.isPublishableDisputeData(400)); - Assert.assertFalse(OpenBankingUtils.isPublishableDisputeData(200)); - } - - @Test - public void testReducingStringLength() throws Exception { - - String body = "String Body"; - Assert.assertEquals(OpenBankingUtils.reduceStringLength(body, 25), body); - Assert.assertEquals(OpenBankingUtils.reduceStringLength(body, 6), "String"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/SPQueryExecutorUtilTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/SPQueryExecutorUtilTest.java deleted file mode 100644 index 3fba38f3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/SPQueryExecutorUtilTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.common.util.SPQueryExecutorUtil; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.ParseException; -import org.apache.commons.io.FileUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - -/** - * Test class for SPQueryExecutorUtil. - */ -@PrepareForTest({HTTPClientUtils.class}) -@PowerMockIgnore({"jdk.internal.reflect.*"}) -public class SPQueryExecutorUtilTest { - private static final String spApiHost = "https://localhost:7444"; - private static final String spUsername = "admin@wso2.com@carbon.super"; - private static final String spPassword = "wso2123"; - private static final String appName = "dummyAppName"; - private static final String query = "dummyQuery"; - private static final String records = "records"; - - @BeforeClass - public void initTest() throws ReflectiveOperationException { - - MockitoAnnotations.initMocks(this); - - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void testSPQueryExecutor() throws OpenBankingException, IOException, ParseException { - File file = new File("src/test/resources/test-data.json"); - byte[] crlBytes = FileUtils.readFileToString(file, String.valueOf(StandardCharsets.UTF_8)) - .getBytes(StandardCharsets.UTF_8); - InputStream inStream = new ByteArrayInputStream(crlBytes); - - StatusLine statusLineMock = Mockito.mock(StatusLine.class); - Mockito.doReturn(HttpStatus.SC_OK).when(statusLineMock).getStatusCode(); - HttpEntity httpEntityMock = Mockito.mock(HttpEntity.class); - Mockito.doReturn(inStream).when(httpEntityMock).getContent(); - - CloseableHttpResponse httpResponseMock = Mockito.mock(CloseableHttpResponse.class); - Mockito.doReturn(statusLineMock).when(httpResponseMock).getStatusLine(); - Mockito.doReturn(httpEntityMock).when(httpResponseMock).getEntity(); - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doReturn(httpResponseMock).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - PowerMockito.mockStatic(HTTPClientUtils.class); - Mockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - JSONObject result = SPQueryExecutorUtil.executeQueryOnStreamProcessor(appName, query, spUsername, - spPassword, spApiHost); - Assert.assertNotNull(result); - Assert.assertTrue(result.containsKey(records)); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/SecurityUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/SecurityUtilsTest.java deleted file mode 100644 index 2e9437f0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/SecurityUtilsTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util; - -import com.wso2.openbanking.accelerator.common.util.SecurityUtils; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Tests Common Security Utils. - */ -public class SecurityUtilsTest { - - @Test - public void testSanitizeString() { - String sanitizedString = SecurityUtils.sanitizeString("tests\nsanitizing"); - Assert.assertFalse(sanitizedString.contains("\n")); - } - - @Test - public void testSanitizeStringList() { - List sanitizedList = new ArrayList<>(); - sanitizedList.add("tests\nsanitizing"); - sanitizedList.add("tests\nsan\nitizing"); - sanitizedList.add("tests\nsanitizing\n"); - - Assert.assertFalse(SecurityUtils.sanitize(sanitizedList).stream().anyMatch(s -> s.contains("\n"))); - } - - @Test - public void testSanitizeStringSet() { - Set sanitizedList = new HashSet<>(); - sanitizedList.add("tests\nsanitizing"); - sanitizedList.add("tests\nsanitizingtext"); - sanitizedList.add("tests\nsanitizingwords"); - - Assert.assertFalse(SecurityUtils.sanitize(sanitizedList).stream().anyMatch(s -> s.contains("\n"))); - } - - @Test - public void testContainSpecialChars() { - Assert.assertTrue(SecurityUtils.containSpecialChars("tests&sanitizing")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/eidas/certificate/extractor/CertificateContentExtractorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/eidas/certificate/extractor/CertificateContentExtractorTest.java deleted file mode 100644 index 03913254..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/eidas/certificate/extractor/CertificateContentExtractorTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util.eidas.certificate.extractor; - -import com.wso2.openbanking.accelerator.common.test.util.CommonTestUtil; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.CertificateContent; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.CertificateContentExtractor; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * Certificate content extractor test. - */ -public class CertificateContentExtractorTest { - - - @Test - public void testExtractValidCertificate() throws Exception { - - X509Certificate cert = - CommonTestUtil.parseTransportCert(CommonTestUtil.EIDAS_CERT).orElse(null); - - CertificateContent extract = CertificateContentExtractor.extract(cert); - - Assert.assertTrue(extract.getPspRoles().size() == 3); - Assert.assertTrue(extract.getPspRoles().contains("AISP")); - Assert.assertTrue(extract.getPspRoles().contains("PISP")); - Assert.assertTrue(extract.getPspRoles().contains("CBPII")); - Assert.assertTrue(extract.getPspAuthorisationNumber().equals("PSDDE-BAFIN-123456")); - Assert.assertTrue(extract.getName().equals("www.hanseaticbank.de")); - Assert.assertTrue(extract.getNcaName().equals("Federal Financial Supervisory Authority")); - Assert.assertTrue(extract.getNcaId().equals("DE-BAFIN")); - } - - @Test - public void testExtractInvalidCertificate() throws CertificateException { - - X509Certificate cert = CommonTestUtil - .parseTransportCert(CommonTestUtil.TEST_CLIENT_CERT).orElse(null); - try { - CertificateContentExtractor.extract(cert); - } catch (Exception ex) { - Assert.assertEquals("X509 V3 Extensions not found in the certificate.", ex.getMessage()); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/testutils/JWTUtilsTestDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/testutils/JWTUtilsTestDataProvider.java deleted file mode 100644 index c1ef208f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/util/testutils/JWTUtilsTestDataProvider.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.util.testutils; - -import org.testng.annotations.DataProvider; - -import java.util.Date; - -/** - * Data Provider for JWTUtilsTest. - */ -public class JWTUtilsTestDataProvider { - - @DataProvider(name = "jwtStrings") - - public Object[][] getJwtStrings() { - - return new Object[][] { - - // Valid JWT String - {"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv" + - "aG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQSflK.xwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", - true}, - // Empty String - {"", false}, - // Null String - {null, false}, - // Invalid JWT String with less than 2 dots - {"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", false}, - // Invalid JWT String with more than 2 dots - {"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4" + - "gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c.extra", - false}, - // JWT String with whitespace - {" eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG" + - "4gRG9lIiwiaWF0IjoxNT.E2MjM5MDIyfQSflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ", - true}, - // JWT String with only dots - {"...", false}, - // JWT String with valid segments but invalid encoding - {"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.InvalidBase64.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", - true}, - // JWT String with valid segments and valid encoding but invalid JSON - {"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG" + - "9lIiwiaWF0IjoxNTE2MjM5MDIyfQSflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c.invalidJSON", - true} - }; - } - - @DataProvider(name = "validParsableJwtStrings") - public Object[][] getValidParsablejwtStrings() { - - String parsableJwtString = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaWQiOiI1NTBmNDQ1My05NTQ3LT" + - "RlNGYtYmUwNi04ZGIyZWVkNTYzYjMiLCJsb2dpbkhpbnQiOiJhZG1pbkB3c28yLmNvb" + - "SIsImlhdCI6MTcxNDkyOTk2MCwianRpIjoiNmU0MWM4N2UtYWJmNi00ZjU1LTliNjQt" + - "NjYwMWFlODg2NjZjIiwiZXhwIjoxNzE0OTMxNzYwLCJuYmYiOjE3MTQ5Mjk5NjB9.WB" + - "7qvq3w6htUop600H5C4HwL-r0wb8GekJE6X4-zrFn2IofEcwV0yisSE5fH8uyrzdmVm" + - "OiBgFXY9Y9cUVlS6t9HMbhlzs2qY0bVzDYVNG7GjgnYIcyh3lx9obqL9O3DJKNre5GS" + - "3b-ATPN6VvYC9F2KnwwuoNky-3Wlcw3G9-E"; - - return new String[][] { - {parsableJwtString} - }; - } - - @DataProvider(name = "validNotParsableJwtStrings") - public Object[][] getValidNotParsableJwtStrings() { - - String notParsableJwtString = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXNOTVCJ9.eyJkaWQiOiI1NTBmNDQ1My05NTQ" + - "RlNGYtYmUwNi04ZGIyZWVkNTYzYjMiLCJsb2dpbkhpbnQiOiJhZG1pbkB3c28yLmNvb" + - "SIsImlhdCI6MTcxNDkyOTk2MCwianRpIjoiNmU0MWM4N2UtYWJmNi00ZjU1LTliNjQt" + - "NjYwMWFlODg2NjZjIiwiZXhwIjoxNzE0OTMxNzYwLCJuYmYiOjE3MTQ5Mjk5NjB9.WB" + - "7qvq3w6htUop600H5C4HwL-r0wb8GekJE6X4-zrFn2IofEcwV0yisSE5fH8uyrzdmVm" + - "OiBgFXY9Y9cUVlS6t9HMbhlzs2qY0bVzDYVNG7GjgnYIcyh3lx9obqL9O3DJKNre5GS" + - "3b-ATPN6VvYC9F2KnwwuoNky-3Wlcw3G9-E3LT"; - - return new String[][] { - {notParsableJwtString} - }; - } - - @DataProvider(name = "notValidJwtStrings") - public Object[][] getNotValidJwtStrings() { - - String notValidJwtString = - "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4" + - "gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c.extra"; - - return new String[][] { - {notValidJwtString} - }; - } - - @DataProvider(name = "expiryTimeProvider") - public Object[][] getExpiryTime() { - - return new Object[][]{ - {null, 0, false}, - {new Date(System.currentTimeMillis() - 10 * 1000), 0, false}, - {new Date(System.currentTimeMillis() + 10 * 100), 0, true} - }; - } - - @DataProvider(name = "nbfProvider") - public Object[][] getNbf() { - - return new Object[][]{ - {null, 0, false}, - {new Date(System.currentTimeMillis() + 10 * 1000), 0, false}, - {new Date(System.currentTimeMillis() - 3 * 1000), 0, true} - }; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/LogicValidatorsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/LogicValidatorsTest.java deleted file mode 100644 index 53f631c9..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/LogicValidatorsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.validator; - -import com.nimbusds.jwt.JWTClaimsSet; -import com.wso2.openbanking.accelerator.common.test.validator.resources.SampleChildRequestObject; -import com.wso2.openbanking.accelerator.common.test.validator.resources.SampleRequestObject; -import com.wso2.openbanking.accelerator.common.test.validator.resources.ValidatorTestDataProvider; -import com.wso2.openbanking.accelerator.common.validator.OpenBankingValidator; -import org.hibernate.validator.HibernateValidator; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; - - -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; - -/** - * Logic validators test. - */ -public class LogicValidatorsTest { - - private SampleRequestObject sampleRequestObject = new SampleRequestObject(); - private static Validator uut = Validation.byProvider(HibernateValidator.class).configure().addProperty( - "hibernate.uut.fail_fast", "true").buildValidatorFactory().getValidator(); - - @Test(dataProvider = "dp-checkValidScopeFormat", dataProviderClass = ValidatorTestDataProvider.class) - public void checkValidScopeFormat(String claimsString) throws ParseException { - - //Assign - sampleRequestObject.setClaimSet(JWTClaimsSet.parse(claimsString)); - - //Act - Set> violations = uut.validate(sampleRequestObject); - - //Assert - String violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertNull("Valid scope formats should pass", violation); - - } - - @Test(dataProvider = "dp-checkValidationsInherited", dataProviderClass = ValidatorTestDataProvider.class) - public void checkValidationsInherited(String claimsString) throws ParseException { - - SampleChildRequestObject sampleChildRequestObject = new SampleChildRequestObject(); - - sampleChildRequestObject.setClaimSet(JWTClaimsSet.parse(claimsString)); - Set> violations = uut.validate(sampleChildRequestObject); - String violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertNotNull("Inherited validations should work", violation); - } - - @Test(dataProvider = "dp-checkValidScopeFormat", dataProviderClass = ValidatorTestDataProvider.class) - public void checkOpenBankingValidator(String claimsString) throws ParseException { - - //Assign - sampleRequestObject.setClaimSet(JWTClaimsSet.parse(claimsString)); - - //Act - String violation = OpenBankingValidator.getInstance().getFirstViolation(sampleRequestObject); - - //Assert - assertNull("Valid scope formats should pass", violation); - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/ModelValidatorsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/ModelValidatorsTest.java deleted file mode 100644 index c8a44ae7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/ModelValidatorsTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.wso2.openbanking.accelerator.common.test.validator; -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import com.nimbusds.jwt.JWTClaimsSet; -import com.wso2.openbanking.accelerator.common.test.validator.resources.SampleDifferentClass; -import com.wso2.openbanking.accelerator.common.test.validator.resources.SampleRequestObject; -import com.wso2.openbanking.accelerator.common.test.validator.resources.ValidatorTestDataProvider; -import com.wso2.openbanking.accelerator.common.validator.OpenBankingValidator; -import org.hibernate.validator.HibernateValidator; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNull; - -/** - * Model validators test. - */ -public class ModelValidatorsTest { - - private SampleRequestObject sampleRequestObject = new SampleRequestObject(); - private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().addProperty( - "hibernate.validator.fail_fast", "true").buildValidatorFactory().getValidator(); - - private static Validator validator2 = Validation.byProvider(HibernateValidator.class).configure().addProperty( - "hibernate.validator.fail_fast", "true").buildValidatorFactory().getValidator(); - - private static Validator validator3 = Validation.byProvider(HibernateValidator.class).configure().addProperty( - "hibernate.validator.fail_fast", "true").buildValidatorFactory().getValidator(); - - - @Test(dataProvider = "dp-checkValidScopeFormat", dataProviderClass = ValidatorTestDataProvider.class) - public void checkValidScopeFormat(String claimsString) throws ParseException { - - sampleRequestObject.setClaimSet(JWTClaimsSet.parse(claimsString)); - Set> violations = validator.validate(sampleRequestObject); - String violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertNull("Valid scope formats should pass", violation); - } - - @Test(dataProvider = "dp-checkValidSingleScopes", dataProviderClass = ValidatorTestDataProvider.class) - public void checkValidSingleScopes(String claimsString) throws ParseException { - - sampleRequestObject.setClaimSet(JWTClaimsSet.parse(claimsString)); - Set> violations = validator.validate(sampleRequestObject); - String violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertNull("Valid single scope should pass", violation); - } - - @Test - public void checkMandatoryParamsValidationFailing() { - - SampleDifferentClass sampleRequestObject = new SampleDifferentClass(); - sampleRequestObject.setName("name"); - sampleRequestObject.setMale(true); - - Set> violations = validator.validate(sampleRequestObject); - String violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertEquals("age failed", violation); - - // - sampleRequestObject = new SampleDifferentClass(); - sampleRequestObject.setName("name"); - sampleRequestObject.setAge(70); - - violations = validator2.validate(sampleRequestObject); - violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertEquals("male failed", violation); - - // - sampleRequestObject = new SampleDifferentClass(); - sampleRequestObject.setMale(true); - sampleRequestObject.setAge(70); - - violations = validator3.validate(sampleRequestObject); - violation = violations.stream().findFirst().map(ConstraintViolation::getMessage).orElse(null); - assertEquals("name failed", violation); - - } - - @Test - public void checkOpenBankingValidator() { - - SampleDifferentClass sampleRequestObject = new SampleDifferentClass(); - sampleRequestObject.setName("name"); - sampleRequestObject.setMale(true); - - String violation = OpenBankingValidator.getInstance().getFirstViolation(sampleRequestObject); - assertEquals("age failed", violation); - - // - sampleRequestObject = new SampleDifferentClass(); - sampleRequestObject.setName("name"); - sampleRequestObject.setAge(70); - - violation = OpenBankingValidator.getInstance().getFirstViolation(sampleRequestObject); - assertEquals("male failed", violation); - - // - sampleRequestObject = new SampleDifferentClass(); - sampleRequestObject.setMale(true); - sampleRequestObject.setAge(70); - - violation = OpenBankingValidator.getInstance().getFirstViolation(sampleRequestObject); - assertEquals("name failed", violation); - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleChildRequestObject.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleChildRequestObject.java deleted file mode 100644 index 74849b20..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleChildRequestObject.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.validator.resources; - -import com.wso2.openbanking.accelerator.common.validator.annotation.RequiredParameter; - -/** - * Sample child request object resource. - */ -@RequiredParameter(param = "name", message = "name failed") -public class SampleChildRequestObject extends SampleRequestObject { - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleDifferentClass.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleDifferentClass.java deleted file mode 100644 index 80e0a429..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleDifferentClass.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.common.test.validator.resources; - -import com.wso2.openbanking.accelerator.common.validator.annotation.RequiredParameter; - -/** - * Sample Different class resource. - */ -@RequiredParameter(param = "name", message = "name failed") -@RequiredParameter(param = "age", message = "age failed") -@RequiredParameter(param = "male", message = "male failed") -public class SampleDifferentClass { - - private String name; - private int age; - private boolean male; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public boolean isMale() { - return male; - } - - public void setMale(boolean male) { - this.male = male; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleRequestObject.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleRequestObject.java deleted file mode 100644 index dc5a6c67..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/SampleRequestObject.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.common.test.validator.resources; - -import com.nimbusds.jwt.JWTClaimsSet; -import com.wso2.openbanking.accelerator.common.validator.annotation.ValidScopeFormat; - -/** - * Sample request object resource. - */ -@ValidScopeFormat(scope = "claimsSet.claims.scope", message = "Non Confirming Scope") -public class SampleRequestObject { - - private JWTClaimsSet claimsSet; - - public SampleRequestObject() { - } - - public JWTClaimsSet getClaimsSet() { - return claimsSet; - } - - public void setClaimSet(JWTClaimsSet claimsSet) { - this.claimsSet = claimsSet; - } - - public void setClaimsSet(JWTClaimsSet claimsSet) { - this.claimsSet = claimsSet; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/ValidatorTestDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/ValidatorTestDataProvider.java deleted file mode 100644 index a5e91864..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/java/com/wso2/openbanking/accelerator/common/test/validator/resources/ValidatorTestDataProvider.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.wso2.openbanking.accelerator.common.test.validator.resources; -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -import org.testng.annotations.DataProvider; - -/** - * validator test data provider resource. - */ -public class ValidatorTestDataProvider { - - private String claimsTemplate = "{\n" + - " \"aud\": \"https://localhost:8243/token\",\n" + - " \"response_type\": \"code id_token\",\n" + - " \"client_id\": \"iTKOfuqz46Y1HVY2BF0Z7JM18Awa\",\n" + - " \"redirect_uri\": \"https://localhost/test/a/app1/callback\",\n" + - " \"scope\": \"${SCOPE}\",\n" + - " \"state\": \"af0ifjsldkj\",\n" + - " \"nonce\": \"n-0S6_WzA2Mj\",\n" + - " \"claims\": {\n" + - " \"sharing_duration\": \"7200\",\n" + - " \"id_token\": {\n" + - " \"acr\": {\n" + - " \"essential\": true,\n" + - " \"values\": [\n" + - " \"urn:cds.au:cdr:3\"\n" + - " ]\n" + - " }\n" + - " },\n" + - " \"userinfo\": {\n" + - " \"given_name\": null,\n" + - " \"family_name\": null\n" + - " }\n" + - " }\n" + - "}"; - - - @DataProvider(name = "dp-checkValidScopeFormat") - public Object[][] dpCheckValidScopeFormat() { - - return new Object[][]{ - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.basic:read bank:accounts.detail:read bank:transactions:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.basic:read")}, - {claimsTemplate.replace("${SCOPE}", - " openid bank:accounts.basic:read bank:accounts.detail:read bank:transactions:read ")}, - {claimsTemplate.replace("${SCOPE}", - "openid profile bank:accounts.basic:read bank:accounts.detail:read bank:transactions:read")} - }; - } - - @DataProvider(name = "dp-checkValidSingleScopes") - public Object[][] dpCheckValidSingleScopes() { - - return new Object[][]{ - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.basic:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.detail:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:transactions:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:payees:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:regular_payments:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid common:customer.basic:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid common:customer.detail:read")}, - - // - {claimsTemplate.replace("${SCOPE}", - "accounts openid")}, - {claimsTemplate.replace("${SCOPE}", - "openid payments")}, - {claimsTemplate.replace("${SCOPE}", - "openid fundsconfirmations")}, - - // - {claimsTemplate.replace("${SCOPE}", - "ais openid")}, - {claimsTemplate.replace("${SCOPE}", - "pis openid")} - }; - } - - @DataProvider(name = "dp-checkInValidScopeFormat") - public Object[][] dpCheckInValidScopeFormat() { - - return new Object[][]{ - {claimsTemplate.replace("${SCOPE}", - "bank:accounts.basic:read")}, - {claimsTemplate.replace("${SCOPE}", - "openid")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.basic")}, - {claimsTemplate.replace("${SCOPE}", - "openid xyz")}, - {claimsTemplate.replace("${SCOPE}", - "xyz")}, - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.basic")}, - {claimsTemplate.replace("${SCOPE}", - "openid common:customer.detail:read")}, - - // - {claimsTemplate.replace("${SCOPE}", - "Accounts openid")}, - {claimsTemplate.replace("${SCOPE}", - "openid Payments")}, - {claimsTemplate.replace("${SCOPE}", - "openid FundsConfirmations")}, - - // - {claimsTemplate.replace("${SCOPE}", - "AIS openid")}, - {claimsTemplate.replace("${SCOPE}", - "PIS openid")} - }; - } - - @DataProvider(name = "dp-checkValidationsInherited") - public Object[][] dpCheckValidationsInherited() { - - return new Object[][]{ - {claimsTemplate.replace("${SCOPE}", - "sactions:read")} - }; - } - - @DataProvider(name = "dp-checkMandatoryParamsValidationFailing") - public Object[][] dpCheckMandatoryParamsValidationFailing() { - - return new Object[][]{ - {claimsTemplate.replace("${SCOPE}", - "openid bank:accounts.basic:read")} - }; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/open-banking-empty.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/open-banking-empty.xml deleted file mode 100644 index 0882a6d1..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/open-banking-empty.xml +++ /dev/null @@ -1,17 +0,0 @@ - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/open-banking.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/open-banking.xml deleted file mode 100644 index a3dbb816..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/open-banking.xml +++ /dev/null @@ -1,284 +0,0 @@ - - - - - - - - sampleDataSourceName - - 1000 - - - - jdbc/WSO2OB_RET_DB - - 1 - - - - - sampleRequestObjectValidator - - - - - sampleServletExtension - - - - - sampleCIBAServletExtension - - - - - sampleSPMetadataFilterExtension - - - - - - DummyValue - ${some.property} - - ${carbon.home} - - - - Nothing - Everything - Anything - - - - - - - - - - - - - - - - - - - - - - - - - false - - - - - true - - - - - - - - - - 3600 - 3600 - 86400 - - true - 3 - - - true - PROXY_HOSTNAME - 8080 - - - - - - - - - CN=Test Pre-Production Issuing CA, O=Test, C=GB - - - true - - - - - - true - true - 0 0 0 * * ? - - - false - 0 0 0 * * ? - Expired - authorised - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - true - true - - - - - - - - - - true - - Sample - - - - - 1000 - 3000 - - - - 1000 - 500 - - - - - full.qualified.name.class1 - full.qualified.name.class2 - - - - - com.wso2.openbanking.accelerator.keymanager.OBKeyManagerImpl - - - - - - - www.wso2.com - 5 - com.wso2.openbanking.accelerator.event.notifications.service.handler.DefaultEventCreationServiceHandler - com.wso2.openbanking.accelerator.event.notifications.service.handler.DefaultEventPollingServiceHandler - com.wso2.openbanking.accelerator.event.notifications.service.service.DefaultEventNotificationGenerator - com.wso2.openbanking.accelerator.event.notifications.service.handler.DefaultEventSubscriptionServiceHandler - - true - true - true - - - - - - false - - PS256 - ES256 - - - - false - - PS256 - ES256 - - - - - - - wso2carbon - wso2carbon-sandbox - 1234 - 5678 - - - 51200 - 2000 - 2000 - - - - - - - - - - - - - - true - 0 0/1 0 ? * * * - 60 - 5 - 60 - EX - 600 - 20 - com.wso2.openbanking.accelerator.event.notifications.service.realtime.service.DefaultRealtimeEventNotificationRequestGenerator - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/test-data.json b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/test-data.json deleted file mode 100644 index dae4490a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/test-data.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "records": [ - [ - 1689313470, - "d40e6fa2-fd1a-41b0-89e8-09d5b0791904", - "10.00", - "GBP", - "Sweepco" - ] - ] -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/testFile.js b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/testFile.js deleted file mode 100644 index 2701713b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/testFile.js +++ /dev/null @@ -1,78 +0,0 @@ - -var psuChannel = 'Online Banking'; - -function onLoginRequest(context) { - reportingData(context, "AuthenticationAttempted", false, psuChannel); - - executeStep(1, { - onSuccess: function (context) { - var supportedAcrValues = ['urn:openbanking:psd2:sca', 'urn:openbanking:psd2:ca']; - var selectedAcr = selectAcrFrom(context, supportedAcrValues); - reportingData(context, "AuthenticationSuccessful", false, psuChannel); - - if (isACREnabled()) { - - context.selectedAcr = selectedAcr; - if (isTRAEnabled()) { - if (selectedAcr === 'urn:openbanking:psd2:ca') { - executeTRAFunction(context); - } else { - executeStep(2, { - onSuccess: function (context) { - reportingData(context, "AuthenticationSuccessful", true, psuChannel); - }, - onFail: function (context) { - reportingData(context, "AuthenticationFailed", false, psuChannel); - } - }); - } - } else { - if (selectedAcr == 'urn:openbanking:psd2:sca') { - executeStep(2, { - onSuccess: function (context) { - reportingData(context, "AuthenticationSuccessful", true, psuChannel); - }, - onFail: function (context) { - reportingData(context, "AuthenticationFailed", false, psuChannel); - } - }); - } - } - - } else { - if (isTRAEnabled()) { - executeTRAFunction(context); - } else { - executeStep(2, { - onSuccess: function (context) { - reportingData(context, "AuthenticationSuccessful", true, psuChannel); - }, - onFail: function (context) { - reportingData(context, "AuthenticationFailed", false, psuChannel); - } - }); - } - } - }, - onFail: function (context) { //basic auth fail - reportingData(context, "AuthenticationFailed", false, psuChannel); - //retry - } - }); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/testng.xml deleted file mode 100644 index 9b956e1e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/testng.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/wso2carbon.jks b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/wso2carbon.jks deleted file mode 100644 index c8775783..00000000 Binary files a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.common/src/test/resources/wso2carbon.jks and /dev/null differ diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/pom.xml deleted file mode 100644 index cd79cfd7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/pom.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - - - 4.0.0 - - - com.wso2.openbanking.accelerator.data.publisher - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../pom.xml - - - com.wso2.openbanking.accelerator.authentication.data.publisher - bundle - WSO2 Open Banking - Authentication Data Publisher - - - - org.eclipse.osgi - org.eclipse.osgi - - - commons-logging - commons-logging - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.authentication.framework - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.data.publisher.common - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - org.testng - testng - test - - - org.powermock - powermock-module-testng - test - - - org.powermock - powermock-api-mockito - test - - - org.mockito - mockito-all - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.authentication.data.publisher.internal - - - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - com.wso2.openbanking.accelerator.common.*; version="${project.version}", - com.wso2.openbanking.accelerator.data.publisher.common.*; version="${project.version}", - org.wso2.carbon.identity.application.authentication.framework.*; - version="${carbon.identity.framework.version.range}", - org.apache.commons.logging; version="${commons.logging.version}" - - - !com.wso2.openbanking.accelerator.authentication.data.publisher.internal, - com.wso2.openbanking.accelerator.authentication.data.publisher.*;version="${project.version}", - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.jacoco - jacoco-maven-plugin - - - - **/*ServiceComponent.class - **/*AuthPublisherConstants.class - **/AuthenticationDataPublisherDataHolder.class - - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.80 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/constant/AuthPublisherConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/constant/AuthPublisherConstants.java deleted file mode 100644 index 63d3307f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/constant/AuthPublisherConstants.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.constant; - -/** - * Class containing the constants for Open Banking Authentication Data Publisher module. - */ -public class AuthPublisherConstants { - - public static final String AUTHENTICATION_SUCCESSFUL = "AuthenticationSuccessful"; - public static final String AUTHENTICATION_FAILED = "AuthenticationFailed"; - public static final String AUTHENTICATION_ATTEMPTED = "AuthenticationAttempted"; - public static final String AUTHENTICATED_USER = "authenticatedUser"; - public static final String BASIC_AUTHENTICATOR = "BasicAuthenticator"; - public static final String LAST_LOGIN_FAILED_USER = "lastLoginFailedUser"; - public static final String USER_ID = "userId"; - public static final String AUTHENTICATION_STATUS = "authenticationStatus"; - public static final String AUTHENTICATION_STEP = "authenticationStep"; - public static final String TIMESTAMP = "timestamp"; - public static final String AUTHENTICATION_APPROACH = "authenticationApproach"; - public static final String AUTHENTICATION_INPUT_STREAM = "AuthenticationInputStream"; - public static final String REDIRECT = "redirect"; - public static final String STREAM_VERSION = "1.0.0"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/extension/AbstractAuthDataPublisher.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/extension/AbstractAuthDataPublisher.java deleted file mode 100644 index 03878c22..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/extension/AbstractAuthDataPublisher.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.extension; - -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; - -import java.util.Map; - -/** - * Open Banking abstract Authentication Data Publisher. - */ -public abstract class AbstractAuthDataPublisher { - - public abstract Map getAdditionalData(JsAuthenticationContext context, String authenticationStatus); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/extension/DefaultAuthDataPublisher.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/extension/DefaultAuthDataPublisher.java deleted file mode 100644 index 63d72b02..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/extension/DefaultAuthDataPublisher.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.extension; - -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; - -import java.util.HashMap; -import java.util.Map; - -/** - * Open Banking default Authentication Data Publisher. - */ -public class DefaultAuthDataPublisher extends AbstractAuthDataPublisher { - - @Override - public Map getAdditionalData(JsAuthenticationContext context, String authenticationStatus) { - - return new HashMap<>(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/internal/AuthenticationDataPublisherDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/internal/AuthenticationDataPublisherDataHolder.java deleted file mode 100644 index b41072c4..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/internal/AuthenticationDataPublisherDataHolder.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.internal; - -import com.wso2.openbanking.accelerator.authentication.data.publisher.extension.AbstractAuthDataPublisher; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; - -/** - * Data holder for Open Banking Authentication Data Publisher. - */ -public class AuthenticationDataPublisherDataHolder { - - private static volatile AuthenticationDataPublisherDataHolder instance; - private OpenBankingConfigurationService openBankingConfigurationService; - private AbstractAuthDataPublisher authDataPublisher; - - public static AuthenticationDataPublisherDataHolder getInstance() { - - if (instance == null) { - synchronized (AuthenticationDataPublisherDataHolder.class) { - if (instance == null) { - instance = new AuthenticationDataPublisherDataHolder(); - } - } - } - return instance; - } - - public void setOpenBankingConfigurationService( - OpenBankingConfigurationService openBankingConfigurationService) { - - this.openBankingConfigurationService = openBankingConfigurationService; - AbstractAuthDataPublisher abstractAuthDataPublisher = - (AbstractAuthDataPublisher) OpenBankingUtils.getClassInstanceFromFQN(openBankingConfigurationService - .getConfigurations().get("DataPublishing.AuthDataPublisher").toString()); - this.setAuthDataPublisher(abstractAuthDataPublisher); - } - - public AbstractAuthDataPublisher getAuthDataPublisher() { - return authDataPublisher; - } - - public void setAuthDataPublisher(AbstractAuthDataPublisher authDataPublisher) { - - this.authDataPublisher = authDataPublisher; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/internal/AuthenticationDataPublisherServiceComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/internal/AuthenticationDataPublisherServiceComponent.java deleted file mode 100644 index dc45d91a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/internal/AuthenticationDataPublisherServiceComponent.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.internal; - -import com.wso2.openbanking.accelerator.authentication.data.publisher.service.AuthenticationDataPublisherService; -import com.wso2.openbanking.accelerator.authentication.data.publisher.service.AuthenticationDataPublisherServiceImpl; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry; - -/** - * Method to register authentication data publisher OSGi Services. - */ -@Component( - name = "com.wso2.open.banking.authentication.data.publisher", - immediate = true -) -public class AuthenticationDataPublisherServiceComponent { - - private AuthenticationDataPublisherServiceImpl authenticationDataPublisherService; - private JsFunctionRegistry jsFunctionRegistry; - private static final Log log = LogFactory.getLog(AuthenticationDataPublisherServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - try { - authenticationDataPublisherService = new AuthenticationDataPublisherServiceImpl(); - - jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "publishAuthData", - (AuthenticationDataPublisherService) authenticationDataPublisherService::authDataExtractor); - } catch (Throwable e) { - log.error("Custom adaptive authentication function for data publishing activation failed", e); - } - - if (log.isDebugEnabled()) { - log.debug("Authentication Data Publisher component is activated successfully."); - } - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - if (jsFunctionRegistry != null) { - jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "publishAuthData"); - } - if (log.isDebugEnabled()) { - log.debug("Authentication Data Publisher component is deactivated."); - } - } - - @Reference( - service = JsFunctionRegistry.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetJsFunctionRegistry" - ) - public void setJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) { - - this.jsFunctionRegistry = jsFunctionRegistry; - } - public void unsetJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) { - this.jsFunctionRegistry = null; - } - - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - AuthenticationDataPublisherDataHolder.getInstance() - .setOpenBankingConfigurationService(openBankingConfigurationService); - } - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - AuthenticationDataPublisherDataHolder.getInstance() - .setOpenBankingConfigurationService(openBankingConfigurationService); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/AuthenticationDataPublisherService.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/AuthenticationDataPublisherService.java deleted file mode 100644 index 0a44f1b8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/AuthenticationDataPublisherService.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.service; - -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; - -import java.io.UnsupportedEncodingException; -import java.util.Map; - -/** - * Functional interface for authDataExtractor method that implements custom adaptive authentication function. - */ -@FunctionalInterface -public interface AuthenticationDataPublisherService { - - void authDataExtractor(JsAuthenticationContext context, String authenticationStatus, - Map parameterMap) - throws UnsupportedEncodingException; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/AuthenticationDataPublisherServiceImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/AuthenticationDataPublisherServiceImpl.java deleted file mode 100644 index 2466812f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/AuthenticationDataPublisherServiceImpl.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.service; - -import com.wso2.openbanking.accelerator.authentication.data.publisher.constant.AuthPublisherConstants; -import com.wso2.openbanking.accelerator.authentication.data.publisher.extension.AbstractAuthDataPublisher; -import com.wso2.openbanking.accelerator.authentication.data.publisher.internal.AuthenticationDataPublisherDataHolder; -import com.wso2.openbanking.accelerator.authentication.data.publisher.internal.AuthenticationDataPublisherServiceComponent; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; - -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; - -/** - * This class implements the custom adaptive authentication function for publishing authentication data. - */ -public class AuthenticationDataPublisherServiceImpl implements AuthenticationDataPublisherService { - - private static final Log log = LogFactory.getLog(AuthenticationDataPublisherServiceComponent.class); - - @Override - public void authDataExtractor(JsAuthenticationContext context, String authenticationStatus, - Map parameterMap) { - - HashMap authenticationData = new HashMap<>(); - String userName = null; - String authenticationStep = null; - long unixTimestamp = Instant.now().getEpochSecond(); - - //Retrieves the user ID from context - if (AuthPublisherConstants.AUTHENTICATION_SUCCESSFUL.equals(authenticationStatus)) { - AuthenticatedUser authenticatedUser = context.getWrapped().getLastAuthenticatedUser(); - userName = authenticatedUser.getAuthenticatedSubjectIdentifier(); - } else if (AuthPublisherConstants.AUTHENTICATION_FAILED.equals(authenticationStatus)) { - if ((context.getWrapped()).getParameters().get(AuthPublisherConstants.AUTHENTICATED_USER) != null) { - userName = ((AuthenticatedUser) context.getWrapped().getParameters() - .get(AuthPublisherConstants.AUTHENTICATED_USER)).getUserName(); - } else if ((context.getWrapped()).getParameters() - .get(AuthPublisherConstants.LAST_LOGIN_FAILED_USER) != null) { - userName = ((AuthenticatedUser) context.getWrapped().getParameters() - .get(AuthPublisherConstants.LAST_LOGIN_FAILED_USER)).getUserName(); - } else { - log.error("Failed to retrieve the user name relating to the authentication"); - } - } - - //Retrieves authentication step from context - if (context.getWrapped().getCurrentAuthenticator() != null) { - authenticationStep = context.getWrapped().getCurrentAuthenticator(); - } else if (context.getWrapped().getCurrentAuthenticator() == null && - AuthPublisherConstants.AUTHENTICATION_ATTEMPTED.equalsIgnoreCase(authenticationStatus)) { - authenticationStep = null; - } else { - log.error("Failed to retrieve the authentication step relating to the authentication"); - } - - //Collects additional data from toolkit level depending on the configurations - AuthenticationDataPublisherDataHolder authenticationDataPublisherDataHolder - = getAuthenticationDataPublisherDataHolder(); - AbstractAuthDataPublisher authDataPublisher = authenticationDataPublisherDataHolder.getAuthDataPublisher(); - Map additionalData = authDataPublisher.getAdditionalData(context, authenticationStatus); - for (Map.Entry dataElement : additionalData.entrySet()) { - authenticationData.put(dataElement.getKey(), dataElement.getValue()); - } - - //Collect data from the map sent by adaptive authentication function - if (parameterMap != null) { - HashMap authProperties = new HashMap<>(parameterMap); //write a config - for (Map.Entry element : authProperties.entrySet()) { - authenticationData.put(element.getKey(), element.getValue()); - } - } - authenticationData.put(AuthPublisherConstants.USER_ID, userName); - authenticationData.put(AuthPublisherConstants.AUTHENTICATION_STATUS, authenticationStatus); - authenticationData.put(AuthPublisherConstants.AUTHENTICATION_STEP, authenticationStep); - authenticationData.put(AuthPublisherConstants.TIMESTAMP, unixTimestamp); - authenticationData.put(AuthPublisherConstants.AUTHENTICATION_APPROACH, AuthPublisherConstants.REDIRECT); - - //Publish Data - OBDataPublisherUtil.publishData(AuthPublisherConstants.AUTHENTICATION_INPUT_STREAM, - AuthPublisherConstants.STREAM_VERSION, authenticationData); - } - - @Generated(message = "Added for testing purposes") - protected AuthenticationDataPublisherDataHolder getAuthenticationDataPublisherDataHolder() { - - return AuthenticationDataPublisherDataHolder.getInstance(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/resources/findbugs-include.xml deleted file mode 100644 index 649d044e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/test/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/OBAuthDataPublisherTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/test/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/OBAuthDataPublisherTest.java deleted file mode 100644 index 820b9543..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/test/java/com/wso2/openbanking/accelerator/authentication/data/publisher/service/OBAuthDataPublisherTest.java +++ /dev/null @@ -1,206 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.data.publisher.service; - -import com.wso2.openbanking.accelerator.authentication.data.publisher.constant.AuthPublisherConstants; -import com.wso2.openbanking.accelerator.authentication.data.publisher.extension.DefaultAuthDataPublisher; -import com.wso2.openbanking.accelerator.authentication.data.publisher.internal.AuthenticationDataPublisherDataHolder; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.AbstractMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Test for Open Banking default Authentication Data Publisher. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OBDataPublisherUtil.class}) -public class OBAuthDataPublisherTest { - - public static final Map SCRIPT_DATA_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("key1", "value1"), - new AbstractMap.SimpleImmutableEntry<>("key2", "value2"), - new AbstractMap.SimpleImmutableEntry<>("key3", "value3")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - public static final Map ADDITIONAL_DATA_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("_key1", "_value1"), - new AbstractMap.SimpleImmutableEntry<>("_key2", "_value2"), - new AbstractMap.SimpleImmutableEntry<>("_key3", "_value3")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - public static final Map ASSERT_DATA_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("_key1", "_value1"), - new AbstractMap.SimpleImmutableEntry<>("_key2", "_value2"), - new AbstractMap.SimpleImmutableEntry<>("_key3", "_value3"), - new AbstractMap.SimpleImmutableEntry<>("key1", "value1"), - new AbstractMap.SimpleImmutableEntry<>("key2", "value2"), - new AbstractMap.SimpleImmutableEntry<>("key3", "value3"), - new AbstractMap.SimpleImmutableEntry<>(AuthPublisherConstants.USER_ID, "bob@wso2.com"), - new AbstractMap.SimpleImmutableEntry<>(AuthPublisherConstants - .AUTHENTICATION_APPROACH, AuthPublisherConstants.REDIRECT), - new AbstractMap.SimpleImmutableEntry<>(AuthPublisherConstants - .AUTHENTICATION_STATUS, AuthPublisherConstants.AUTHENTICATION_SUCCESSFUL), - new AbstractMap.SimpleImmutableEntry<>(AuthPublisherConstants - .AUTHENTICATION_STEP, AuthPublisherConstants.BASIC_AUTHENTICATOR)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - private static ByteArrayOutputStream outContent; - private static Logger logger = null; - private static PrintStream printStream; - - @BeforeClass - public void initializeConfigurations() { - - OBAuthDataPublisherTest.outContent = new ByteArrayOutputStream(); - OBAuthDataPublisherTest.printStream = new PrintStream(OBAuthDataPublisherTest.outContent); - System.setOut(OBAuthDataPublisherTest.printStream); - OBAuthDataPublisherTest.logger = LogManager.getLogger(OBAuthDataPublisherTest.class); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void invokeFunctionWithoutUserID() throws Exception { - - outContent.reset(); - PowerMockito.mockStatic(OBDataPublisherUtil.class); - AuthenticationDataPublisherServiceImpl - authenticationDataPublisherService = Mockito.spy(AuthenticationDataPublisherServiceImpl.class); - DefaultAuthDataPublisher authDataPublisher = Mockito.mock(DefaultAuthDataPublisher.class); - AuthenticationDataPublisherDataHolder - authenticationDataPublisherDataHolder = Mockito.spy(AuthenticationDataPublisherDataHolder.class); - authenticationDataPublisherDataHolder.setAuthDataPublisher(authDataPublisher); - Mockito.doReturn(authenticationDataPublisherDataHolder).when(authenticationDataPublisherService) - .getAuthenticationDataPublisherDataHolder(); - PowerMockito.doNothing().when(OBDataPublisherUtil.class, - "publishData", Mockito.anyString(), Mockito.anyString(), Mockito.any()); - AuthenticationContext authContext = new AuthenticationContext(); - - //Setting null values for all possible user ID data - authContext.addParameter(AuthPublisherConstants.AUTHENTICATED_USER, null); - authContext.addParameter(AuthPublisherConstants.LAST_LOGIN_FAILED_USER, null); - authContext.setCurrentAuthenticator(AuthPublisherConstants.BASIC_AUTHENTICATOR); - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setAuthenticatedSubjectIdentifier(null); - authContext.setSubject(authenticatedUser); - JsAuthenticationContext context = new JsAuthenticationContext(authContext); - authenticationDataPublisherService - .authDataExtractor(context, AuthPublisherConstants.AUTHENTICATION_FAILED, SCRIPT_DATA_MAP); - - Assert.assertTrue(OBAuthDataPublisherTest.outContent.toString().contains("Failed to retrieve the " + - "user name relating to the authentication")); - } - - @Test - public void invokeFunctionWithoutAuthenticationStep() throws Exception { - - outContent.reset(); - PowerMockito.mockStatic(OBDataPublisherUtil.class); - AuthenticationDataPublisherServiceImpl - authenticationDataPublisherService = Mockito.spy(AuthenticationDataPublisherServiceImpl.class); - DefaultAuthDataPublisher authDataPublisher = Mockito.mock(DefaultAuthDataPublisher.class); - AuthenticationDataPublisherDataHolder - authenticationDataPublisherDataHolder = Mockito.spy(AuthenticationDataPublisherDataHolder.class); - authenticationDataPublisherDataHolder.setAuthDataPublisher(authDataPublisher); - Mockito.doReturn(authenticationDataPublisherDataHolder).when(authenticationDataPublisherService) - .getAuthenticationDataPublisherDataHolder(); - PowerMockito.doNothing().when(OBDataPublisherUtil.class, - "publishData", Mockito.anyString(), Mockito.anyString(), Mockito.any()); - AuthenticationContext authContext = new AuthenticationContext(); - - authContext.addParameter(AuthPublisherConstants.AUTHENTICATED_USER, "mark@wso2.com"); - authContext.addParameter(AuthPublisherConstants.LAST_LOGIN_FAILED_USER, "anne@wso2.com"); - - //Setting null value for authentication step - authContext.setCurrentAuthenticator(null); - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setAuthenticatedSubjectIdentifier("bob@wso2.com"); - authContext.setSubject(authenticatedUser); - JsAuthenticationContext context = new JsAuthenticationContext(authContext); - authenticationDataPublisherService - .authDataExtractor(context, AuthPublisherConstants.AUTHENTICATION_SUCCESSFUL, SCRIPT_DATA_MAP); - - Assert.assertTrue(OBAuthDataPublisherTest.outContent.toString().contains("Failed to retrieve the " + - "authentication step relating to the authentication")); - } - - @Test - public void publishData() throws Exception { - - outContent.reset(); - PowerMockito.mockStatic(OBDataPublisherUtil.class); - - //Mocking classes - AuthenticationDataPublisherServiceImpl - authenticationDataPublisherService = Mockito.spy(AuthenticationDataPublisherServiceImpl.class); - DefaultAuthDataPublisher authDataPublisher = Mockito.mock(DefaultAuthDataPublisher.class); - AuthenticationDataPublisherDataHolder - authenticationDataPublisherDataHolder = Mockito.spy(AuthenticationDataPublisherDataHolder.class); - Mockito.doReturn(ADDITIONAL_DATA_MAP).when(authDataPublisher).getAdditionalData(Mockito.any(), Mockito.any()); - authenticationDataPublisherDataHolder.setAuthDataPublisher(authDataPublisher); - Mockito.doReturn(authenticationDataPublisherDataHolder).when(authenticationDataPublisherService) - .getAuthenticationDataPublisherDataHolder(); - - //Invoking the method - AuthenticationContext authContext = new AuthenticationContext(); - authContext.addParameter(AuthPublisherConstants.AUTHENTICATED_USER, "mark@wso2.com"); - authContext.addParameter(AuthPublisherConstants.LAST_LOGIN_FAILED_USER, "anne@wso2.com"); - authContext.setCurrentAuthenticator(AuthPublisherConstants.BASIC_AUTHENTICATOR); - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setAuthenticatedSubjectIdentifier("bob@wso2.com"); - authContext.setSubject(authenticatedUser); - JsAuthenticationContext context = new JsAuthenticationContext(authContext); - ArgumentCaptor argumentStream = ArgumentCaptor.forClass(String.class); - ArgumentCaptor argumentVersion = ArgumentCaptor.forClass(String.class); - ArgumentCaptor argumentData = ArgumentCaptor.forClass(Map.class); - PowerMockito.doNothing().when(OBDataPublisherUtil.class, - "publishData", argumentStream.capture(), argumentVersion.capture(), argumentData.capture()); - authenticationDataPublisherService - .authDataExtractor(context, AuthPublisherConstants.AUTHENTICATION_SUCCESSFUL, SCRIPT_DATA_MAP); - - Map receivedMap = argumentData.getValue(); - receivedMap.remove(AuthPublisherConstants.TIMESTAMP); - - //Assert the values passed to the publish() method - Assert.assertEquals(argumentStream.getValue(), AuthPublisherConstants.AUTHENTICATION_INPUT_STREAM); - Assert.assertEquals(argumentVersion.getValue(), AuthPublisherConstants.STREAM_VERSION); - Assert.assertEquals(receivedMap, ASSERT_DATA_MAP); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/test/resources/testng.xml deleted file mode 100644 index 596587bd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.authentication.data.publisher/src/test/resources/testng.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/pom.xml deleted file mode 100644 index 281e547a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/pom.xml +++ /dev/null @@ -1,201 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.data.publisher.common - bundle - WSO2 Open Banking - Data Publisher Common Module - - - - org.wso2.carbon.analytics-common - org.wso2.carbon.databridge.agent - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - com.github.spotbugs - spotbugs-annotations - ${spotbugs.annotations.version} - - - org.testng - testng - test - - - org.powermock - powermock-module-testng - test - - - org.powermock - powermock-api-mockito - test - - - org.mockito - mockito-all - test - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.data.publisher.common.internal - - - org.osgi.framework; version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component; version="${osgi.service.component.imp.pkg.version.range}", - org.wso2.carbon.databridge.agent.*; version="${carbon.analytics.common.version.range}", - org.wso2.carbon.databridge.commons.*; version="${carbon.analytics.common.version.range}", - com.wso2.openbanking.accelerator.common.*; version="${project.version}", - org.apache.tomcat.dbcp.pool2.*; version="${tomcat.catalina.version}" - - - !com.wso2.openbanking.accelerator.data.publisher.common.internal, - com.wso2.openbanking.accelerator.data.publisher.common.constants; version="${project.version}", - com.wso2.openbanking.accelerator.data.publisher.common.model; version="${project.version}", - com.wso2.openbanking.accelerator.data.publisher.common.util; version="${project.version}", - com.wso2.openbanking.accelerator.data.publisher.common.*; version="${project.version}" - - <_dsannotations>* - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.jacoco - jacoco-maven-plugin - - - - **/*ServiceComponent.class - **/*DataPublishingConstants.class - **/*OBAnalyticsEvent.class - **/*QueueWorker.class - **/*EventQueue.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.80 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherFactory.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherFactory.java deleted file mode 100644 index d7b17ed2..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import org.apache.tomcat.dbcp.pool2.BasePooledObjectFactory; -import org.apache.tomcat.dbcp.pool2.PooledObject; -import org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject; - -/** - * Data Publisher Factory class. - * - * @param - */ -public class DataPublisherFactory extends BasePooledObjectFactory { - - @Override - public OpenBankingDataPublisher create() { - - return (OpenBankingDataPublisher) new OBThriftDataPublisher(); - } - - @Override - public PooledObject wrap(OpenBankingDataPublisher openBankingDataPublisher) { - - return new DefaultPooledObject(openBankingDataPublisher); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherPool.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherPool.java deleted file mode 100644 index ade99f3a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherPool.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import org.apache.tomcat.dbcp.pool2.PooledObjectFactory; -import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPool; -import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPoolConfig; - -/** - * Data Publisher Pool class. - * @param - */ -public class DataPublisherPool extends GenericObjectPool { - - public DataPublisherPool(PooledObjectFactory factory, - GenericObjectPoolConfig config) { - - super(factory, config); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/EventQueue.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/EventQueue.java deleted file mode 100644 index 99cd0b06..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/EventQueue.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import com.wso2.openbanking.accelerator.data.publisher.common.model.OBAnalyticsEvent; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; - -/** - * Event queue wrapper class wrapping the ArrayBlockingQueue. - */ -public class EventQueue { - - private static final Log log = LogFactory.getLog(EventQueue.class); - private final BlockingQueue eventQueue; - private final ExecutorService publisherExecutorService; - - public EventQueue(int queueSize, int workerThreadCount) { - - // Note : Using a fixed worker thread pool and a bounded queue to control the load on the server - publisherExecutorService = Executors.newFixedThreadPool(workerThreadCount); - eventQueue = new ArrayBlockingQueue<>(queueSize); - } - - public void put(OBAnalyticsEvent obAnalyticsEvent) { - - try { - if (eventQueue.offer(obAnalyticsEvent)) { - publisherExecutorService.submit(new QueueWorker(eventQueue, publisherExecutorService)); - } else { - log.error("Event queue is full. Starting to drop OB analytics events."); - } - } catch (RejectedExecutionException e) { - log.warn("Task submission failed. Task queue might be full", e); - } - } - - @Override - protected void finalize() throws Throwable { - publisherExecutorService.shutdown(); - super.finalize(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/OBThriftDataPublisher.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/OBThriftDataPublisher.java deleted file mode 100644 index 94aa48f7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/OBThriftDataPublisher.java +++ /dev/null @@ -1,288 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.data.publisher.common.constants.DataPublishingConstants; -import com.wso2.openbanking.accelerator.data.publisher.common.internal.OBAnalyticsDataHolder; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.databridge.agent.DataPublisher; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointException; -import org.wso2.carbon.databridge.commons.Event; -import org.wso2.carbon.databridge.commons.exception.TransportException; -import org.wso2.carbon.databridge.commons.utils.DataBridgeCommonsUtils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Open Banking Thrift Data publisher. - */ -public class OBThriftDataPublisher implements OpenBankingDataPublisher { - - private DataPublisher dataPublisher; - private Map> streamAttributeMap = new HashMap<>(); - private Map> attributeValidationMap; - private static final Log log = LogFactory.getLog(OBThriftDataPublisher.class); - private Map obConfigurations; - - public OBThriftDataPublisher() { - this.init(); - } - - @Override - public void publish(String streamName, String streamVersion, Map analyticsData) { - - // Set payloads - Object[] payload = setPayload(streamName, analyticsData); - - // Log error and return if payload is not set - if (payload.length == 0) { - log.error("Error while setting payload to publish data."); - return; - } - - // Create wso2 event to publish - Event event = new Event(); - event.setStreamId(DataBridgeCommonsUtils.generateStreamId(streamName, streamVersion)); - event.setMetaData(null); - event.setCorrelationData(null); - event.setPayloadData(payload); - - try { - // Try to publish event with timeout - // If the queue is full, this will wait timeout time and retry to add to queue. If still full this - // returns false - boolean published = dataPublisher.tryPublish(event, - Long.parseLong((String) obConfigurations.get(DataPublishingConstants.THRIFT_PUBLISHING_TIMEOUT))); - if (!published) { - log.error("Unable to publish data for stream: " + streamName.replaceAll("[\r\n]", "") + - ". Queue is full."); - } - } catch (Exception e) { - // Catching exception and logging error because data publishing issues should not hinder other flows. - log.error("Error occurred while publishing the data", e); - } - - } - - /** - * Initialize OB Thrift Data publisher. - * This method initializes data publisher and read the attribute map for each data stream. - */ - protected void init() { - - log.debug("Initializing the Open Banking Thrift data publisher"); - obConfigurations = OBAnalyticsDataHolder.getInstance().getConfigurationMap(); - String serverUser = (String) obConfigurations.get(DataPublishingConstants.DATA_PUBLISHING_USERNAME); - String serverPassword = (String) obConfigurations.get(DataPublishingConstants.DATA_PUBLISHING_PASSWORD); - String serverURL = (String) obConfigurations.get(DataPublishingConstants.DATA_PUBLISHING_SERVER_URL); - String authURL = (String) obConfigurations.get(DataPublishingConstants.DATA_PUBLISHING_AUTH_URL); - - if (serverURL == null || serverPassword == null || serverUser == null) { - log.error("Error while retrieving publisher server configs"); - return; - } - - log.debug("Reading attribute list for data streams"); - buildStreamAttributeMap(); - attributeValidationMap = OBAnalyticsDataHolder.getInstance().getOpenBankingConfigurationService() - .getDataPublishingValidationMap(); - - try { - //Create new DataPublisher for the tenant. - dataPublisher = getDataPublisher(serverURL, authURL, serverUser, serverPassword); - } catch (DataEndpointConfigurationException e) { - log.error("Error while creating data publisher with the configurations", e); - } catch (DataEndpointException | DataEndpointAgentConfigurationException | TransportException | - DataEndpointAuthenticationException e) { - log.error("Error while creating data publisher", e); - } - - } - - @Generated(message = "Method to get new Thrift data publisher") - protected DataPublisher getDataPublisher(String serverURL, String authURL, String serverUser, - String serverPassword) - throws DataEndpointAuthenticationException, DataEndpointAgentConfigurationException, TransportException, - DataEndpointException, DataEndpointConfigurationException { - - return new DataPublisher(null, serverURL, authURL, serverUser, serverPassword); - } - - protected void setDataPublisher(DataPublisher dataPublisher) { - this.dataPublisher = dataPublisher; - } - - /** - * Create event payload for the given stream. - * - * @param streamName stream name - * @param analyticsData map of data to be published - * @return payload of object[] - */ - protected Object[] setPayload(String streamName, Map analyticsData) { - - if (streamAttributeMap.containsKey(streamName)) { - List attributes = streamAttributeMap.get(streamName); - boolean isValid = validateAttributes(streamName, attributes, analyticsData); - if (isValid) { - ArrayList payload = new ArrayList<>(); - for (String attribute : attributes) { - payload.add(analyticsData.get(attribute)); - } - return payload.toArray(); - } - } - return new Object[]{}; - } - - /** - * Validate whether the required parameters are present and are of correct data type. - * @param streamName stream name - * @param analyticsData data map - * @return boolean isValid - */ - private boolean validateAttributes(String streamName, List attributes, Map analyticsData) { - - Map> attributeValidations = getAttributeValidationMap(); - for (String attribute: attributes) { - String attributeNameKey = streamName + "_" + attribute; - boolean isRequired = (boolean) attributeValidations.get(attributeNameKey) - .get(OpenBankingConstants.REQUIRED); - String type = (String) attributeValidations.get(attributeNameKey).get(OpenBankingConstants.ATTRIBUTE_TYPE); - - // validation for required attributes - if (isRequired) { - if (analyticsData.containsKey(attribute)) { - if (analyticsData.get(attribute) == null) { - log.error(attribute.replaceAll("[\r\n]", "") + " is missing in data map for " + - streamName.replaceAll("[\r\n]", "") + ". This event " - + "will not be processed further."); - return false; - } - } else { - log.error(attribute.replaceAll("[\r\n]", "") + " is missing in data map for " + - streamName.replaceAll("[\r\n]", "") + ". This event " - + "will not be processed further."); - return false; - } - } - - // validation for data type - if (analyticsData.containsKey(attribute) && analyticsData.get(attribute) != null) { - if (!isValidDataType(type, attribute, analyticsData.get(attribute))) { - return false; - } - } - } - return true; - } - - /** - * Build a map of attributes to be published for each stream. - */ - protected void buildStreamAttributeMap() { - - Map> dataStreamAttributes = OBAnalyticsDataHolder.getInstance() - .getOpenBankingConfigurationService().getDataPublishingStreams(); - dataStreamAttributes.keySet().forEach(dataStream -> { - Map integerStringMap = dataStreamAttributes.get(dataStream); - List attributeList = integerStringMap.keySet().stream() - .map(integerStringMap::get).collect(Collectors.toList()); - streamAttributeMap.put(dataStream, attributeList); - }); - } - - @Generated(message = "Added for testing purposes") - protected Map> getStreamAttributeMap() { - - return streamAttributeMap; - } - - @Generated(message = "Added for testing purposes") - protected Map> getAttributeValidationMap() { - return attributeValidationMap; - } - - @SuppressFBWarnings("IMPROPER_UNICODE") - // Suppressed content - ype.toLowerCase(Locale.ENGLISH) - // Suppression reason - False Positive : Since the value is used in switch statements, it cannot be used - // maliciously - // Suppressed warning count - 1 - private boolean isValidDataType(String type, String attributeName, Object attributeValue) { - - Class attributeClass = attributeValue.getClass(); - switch (type.toLowerCase(Locale.ENGLISH)) { - case "string" : - if (!(attributeClass.equals(String.class))) { - logInvalidDataTypeError(attributeName, String.class.getName(), attributeClass.getName()); - return false; - } - break; - case "int" : - if (!(attributeClass.equals(Integer.class))) { - logInvalidDataTypeError(attributeName, Integer.class.getName(), attributeClass.getName()); - return false; - } - break; - case "long" : - if (!(attributeClass.equals(Long.class))) { - logInvalidDataTypeError(attributeName, Long.class.getName(), attributeClass.getName()); - return false; - } - break; - case "boolean" : - if (!(attributeClass.equals(Boolean.class))) { - logInvalidDataTypeError(attributeName, Boolean.class.getName(), attributeClass.getName()); - return false; - } - break; - case "double" : - if (!(attributeClass.equals(Double.class))) { - logInvalidDataTypeError(attributeName, Double.class.getName(), attributeClass.getName()); - return false; - } - break; - case "float" : - if (!(attributeClass.equals(Float.class))) { - logInvalidDataTypeError(attributeName, Float.class.getName(), attributeClass.getName()); - return false; - } - break; - } - return true; - } - - private void logInvalidDataTypeError(String attributeName, String expectedDataType, String actualDataType) { - log.error(attributeName.replaceAll("[\r\n]", "") + " is expecting a " + - expectedDataType.replaceAll("[\r\n]", "") + " type attribute while attribute of " + - "type " + actualDataType.replaceAll("[\r\n]", "") + " is present."); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/OpenBankingDataPublisher.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/OpenBankingDataPublisher.java deleted file mode 100644 index 20aab29d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/OpenBankingDataPublisher.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; -import java.util.Map; - -/** - * Interface for Open Banking Data publisher. - */ -public interface OpenBankingDataPublisher { - - void publish(String streamName, String streamVersion, Map analyticsData); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/QueueWorker.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/QueueWorker.java deleted file mode 100644 index 56ad52b3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/QueueWorker.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import com.wso2.openbanking.accelerator.data.publisher.common.model.OBAnalyticsEvent; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; - -/** - * Queue worker implementation for publish events in queue. - */ -public class QueueWorker implements Runnable { - - private BlockingQueue eventQueue; - private ExecutorService executorService; - private static final Log log = LogFactory.getLog(QueueWorker.class); - - public QueueWorker(BlockingQueue queue, ExecutorService executorService) { - - this.eventQueue = queue; - this.executorService = executorService; - } - - public void run() { - - ThreadPoolExecutor threadPoolExecutor = ((ThreadPoolExecutor) executorService); - - do { - OBAnalyticsEvent event = eventQueue.poll(); - if (event != null) { - OpenBankingDataPublisher dataPublisher = OBDataPublisherUtil.getDataPublisherInstance(); - if (dataPublisher != null) { - dataPublisher.publish(event.getStreamName(), event.getStreamVersion(), event.getAnalyticsData()); - OBDataPublisherUtil.releaseDataPublishingInstance(dataPublisher); - } - } - } while (threadPoolExecutor.getActiveCount() == 1 && eventQueue.size() != 0); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/constants/DataPublishingConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/constants/DataPublishingConstants.java deleted file mode 100644 index 30f8d7e1..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/constants/DataPublishingConstants.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common.constants; - -/** - * Class containing the constants for Open Banking Data Publishing module. - */ -public class DataPublishingConstants { - - public static final String DATA_PUBLISHING_USERNAME = "DataPublishing.Username"; - public static final String DATA_PUBLISHING_PASSWORD = "DataPublishing.Password"; - public static final String DATA_PUBLISHING_SERVER_URL = "DataPublishing.ServerURL"; - public static final String DATA_PUBLISHING_AUTH_URL = "DataPublishing.AuthURL"; - public static final String DATA_PUBLISHING_POOL_SIZE = "DataPublishing.PoolSize"; - public static final String DATA_PUBLISHING_POOL_WAIT_TIME = "DataPublishing.PoolWaitTimeMs"; - public static final String DATA_PUBLISHING_PROTOCOL = "DataPublishing.Protocol"; - public static final String DATA_PUBLISHING_ENABLED = "DataPublishing.Enabled"; - public static final String ELK_ANALYTICS_ENABLED = "ELKAnalytics.Enabled"; - public static final String APIM_ANALYTICS_ENABLED = "APIMAnalytics.Enabled"; - public static final String QUEUE_SIZE = "DataPublishing.QueueSize"; - public static final String WORKER_THREAD_COUNT = "DataPublishing.WorkerThreadCount"; - public static final String THRIFT_PUBLISHING_TIMEOUT = "DataPublishing.Thrift.PublishingTimeout"; - public static final String LOG_FILE_NAME = "OB_LOG"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/internal/OBAnalyticsDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/internal/OBAnalyticsDataHolder.java deleted file mode 100644 index 84bb2373..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/internal/OBAnalyticsDataHolder.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.data.publisher.common.DataPublisherFactory; -import com.wso2.openbanking.accelerator.data.publisher.common.DataPublisherPool; -import com.wso2.openbanking.accelerator.data.publisher.common.EventQueue; -import com.wso2.openbanking.accelerator.data.publisher.common.OpenBankingDataPublisher; -import com.wso2.openbanking.accelerator.data.publisher.common.constants.DataPublishingConstants; -import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPoolConfig; - -import java.util.Map; - -/** - * Data holder for Open Banking Analytics. - */ -public class OBAnalyticsDataHolder { - - private static volatile OBAnalyticsDataHolder instance; - private OpenBankingConfigurationService openBankingConfigurationService; - private Map configurationMap; - private DataPublisherPool pool; - private int poolSize; - private EventQueue eventQueue; - - public static OBAnalyticsDataHolder getInstance() { - - if (instance == null) { - synchronized (OBAnalyticsDataHolder.class) { - if (instance == null) { - instance = new OBAnalyticsDataHolder(); - } - } - } - return instance; - } - - public Map getConfigurationMap() { - - return configurationMap; - } - - public OpenBankingConfigurationService getOpenBankingConfigurationService() { - - return openBankingConfigurationService; - } - - public void setOpenBankingConfigurationService( - OpenBankingConfigurationService openBankingConfigurationService) { - - this.openBankingConfigurationService = openBankingConfigurationService; - this.configurationMap = openBankingConfigurationService.getConfigurations(); - } - - /** - * Initialize pool of data publishers. - */ - public void initializePool() { - - GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); - poolSize = Integer.parseInt((String) configurationMap.get(DataPublishingConstants.DATA_PUBLISHING_POOL_SIZE)); - int timeout = Integer.parseInt( - (String) configurationMap.get(DataPublishingConstants.DATA_PUBLISHING_POOL_WAIT_TIME)); - config.setMaxIdle(poolSize); - config.setMaxTotal(poolSize); - config.setMaxWaitMillis(timeout); - pool = new DataPublisherPool<>(new DataPublisherFactory<>(), config); - } - - public DataPublisherPool getDataPublisherPool() { - - return pool; - } - - public void closePool() { - - pool.close(); - } - - public void initializeEventQueue() { - - int queueSize = Integer.parseInt((String) configurationMap.get(DataPublishingConstants.QUEUE_SIZE)); - int workerThreadCount = - Integer.parseInt((String) configurationMap.get(DataPublishingConstants.WORKER_THREAD_COUNT)); - eventQueue = new EventQueue(queueSize, workerThreadCount); - } - - public EventQueue getEventQueue() { - - return eventQueue; - } - - @Generated(message = "Event queue setter for testing purposes") - public void setEventQueue(EventQueue eventQueue) { - - this.eventQueue = eventQueue; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/internal/OBAnalyticsServiceComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/internal/OBAnalyticsServiceComponent.java deleted file mode 100644 index 9497f52e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/internal/OBAnalyticsServiceComponent.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; - -/** - * Service class for Open Banking Data Publishing Component. - */ -@Component( - name = "com.wso2.openbanking.accelerator.data.publisher.common.internal.OBAnalyticsServiceComponent", - immediate = true -) -public class OBAnalyticsServiceComponent { - - private static final Log log = LogFactory.getLog(OBAnalyticsServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - OBAnalyticsDataHolder.getInstance().initializePool(); - OBAnalyticsDataHolder.getInstance().initializeEventQueue(); - log.debug("Open banking data publishing component is activated "); - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - OBAnalyticsDataHolder.getInstance().closePool(); - log.debug("Open banking data publishing component is deactivated "); - } - - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/model/OBAnalyticsEvent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/model/OBAnalyticsEvent.java deleted file mode 100644 index 2aff8b6c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/model/OBAnalyticsEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common.model; - -import java.util.Map; - -/** - * Open Banking Analytics event model class. - */ -public class OBAnalyticsEvent { - - private String streamName; - private String streamVersion; - private Map analyticsData; - - - public OBAnalyticsEvent(String streamName, String streamVersion, Map analyticsData) { - this.streamName = streamName; - this.streamVersion = streamVersion; - this.analyticsData = analyticsData; - } - - public String getStreamName() { - - return streamName; - } - - public String getStreamVersion() { - - return streamVersion; - } - - public Map getAnalyticsData() { - - return analyticsData; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/util/OBDataPublisherUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/util/OBDataPublisherUtil.java deleted file mode 100644 index 771b8d4d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/java/com/wso2/openbanking/accelerator/data/publisher/common/util/OBDataPublisherUtil.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.AnalyticsLogsUtils; -import com.wso2.openbanking.accelerator.data.publisher.common.DataPublisherPool; -import com.wso2.openbanking.accelerator.data.publisher.common.EventQueue; -import com.wso2.openbanking.accelerator.data.publisher.common.OpenBankingDataPublisher; -import com.wso2.openbanking.accelerator.data.publisher.common.constants.DataPublishingConstants; -import com.wso2.openbanking.accelerator.data.publisher.common.internal.OBAnalyticsDataHolder; -import com.wso2.openbanking.accelerator.data.publisher.common.model.OBAnalyticsEvent; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Map; - -/** - * Utility class for Data Publishing. - */ -public class OBDataPublisherUtil { - - private static final Log log = LogFactory.getLog(OBDataPublisherUtil.class); - - public static OpenBankingDataPublisher getDataPublisherInstance() { - - DataPublisherPool pool = - OBAnalyticsDataHolder.getInstance().getDataPublisherPool(); - try { - return pool.borrowObject(); - } catch (Exception e) { - log.error("Error while receiving Thrift Data Publisher from the pool."); - } - return null; - } - - public static void releaseDataPublishingInstance(OpenBankingDataPublisher instance) { - - OBAnalyticsDataHolder.getInstance().getDataPublisherPool().returnObject(instance); - log.debug("Data publishing instance released to the pool"); - } - - /** - * Util method to publish OB analytics data. - * This method will put received data to an event queue and take care of asynchronous data publishing. - */ - public static void publishData(String streamName, String streamVersion, Map analyticsData) { - - // Analytics data will be added to the OB analytics logfile for processing if ELK is configured for the server. - if (Boolean.parseBoolean((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(DataPublishingConstants.ELK_ANALYTICS_ENABLED))) { - try { - AnalyticsLogsUtils.addAnalyticsLogs(DataPublishingConstants.LOG_FILE_NAME, streamName, - streamVersion, analyticsData); - } catch (OpenBankingException e) { - log.error("Error occurred while writing analytics logs", e); - } - } - - if (Boolean.parseBoolean((String) OBAnalyticsDataHolder.getInstance().getConfigurationMap() - .get(DataPublishingConstants.DATA_PUBLISHING_ENABLED))) { - - EventQueue eventQueue = OBAnalyticsDataHolder.getInstance().getEventQueue(); - if (!(eventQueue == null)) { - OBAnalyticsEvent event = new OBAnalyticsEvent(streamName, streamVersion, analyticsData); - eventQueue.put(event); - } else { - log.error("Unable to get the event queue. Data publishing may be disabled."); - } - } else { - log.debug("Data publishing is disabled. Failed to obtain a data publisher instance."); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index c96aff43..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherPoolTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherPoolTest.java deleted file mode 100644 index e689f948..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/DataPublisherPoolTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.data.publisher.common.internal.OBAnalyticsDataHolder; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Data publisher pool test. - */ -public class DataPublisherPoolTest { - - private DataPublisherPool pool; - - @Test(priority = 1) - public void testInitializePool() { - - Map configs = new HashMap<>(); - configs.put("DataPublishing.PoolSize", "3"); - configs.put("DataPublishing.PoolWaitTimeMs", "500"); - configs.put("DataPublishing.Enabled", "true"); - OpenBankingConfigurationService openBankingConfigurationService = - Mockito.mock(OpenBankingConfigurationService.class); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configs); - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - - OBAnalyticsDataHolder.getInstance().initializePool(); - pool = OBAnalyticsDataHolder.getInstance().getDataPublisherPool(); - Assert.assertEquals(pool.getCreatedCount(), 0); - Assert.assertEquals(pool.getMaxTotal(), 3); - Assert.assertEquals(pool.getMaxIdle(), 3); - Assert.assertEquals(pool.getBorrowedCount(), 0); - } - - @Test(priority = 2) - public void testBorrowInstances() { - - OpenBankingDataPublisher instance = OBDataPublisherUtil.getDataPublisherInstance(); - Assert.assertEquals(pool.getCreatedCount(), 1); - Assert.assertEquals(pool.getBorrowedCount(), 1); - Assert.assertEquals(pool.getNumIdle(), 0); - OBDataPublisherUtil.releaseDataPublishingInstance(instance); - Assert.assertEquals(pool.getNumIdle(), 1); - } - - @Test(priority = 3) - public void tryBorrowOverMaxLimit() throws InterruptedException { - - List instances = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - instances.add(OBDataPublisherUtil.getDataPublisherInstance()); - } - Assert.assertEquals(pool.getCreatedCount(), 3); - Assert.assertEquals(pool.getBorrowedCount(), 4); - } - - @Test(priority = 100) - public void testPoolClose() { - OBAnalyticsDataHolder.getInstance().closePool(); - Assert.assertTrue(pool.isClosed()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/OBAnalyticsEventQueueTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/OBAnalyticsEventQueueTest.java deleted file mode 100644 index 522ca4ef..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/OBAnalyticsEventQueueTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.data.publisher.common.internal.OBAnalyticsDataHolder; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.HashMap; -import java.util.Map; - -/** - * Open Banking analytics event queue test. - */ -@PowerMockIgnore({"jdk.internal.reflect.*"}) -@PrepareForTest({OpenBankingConfigParser.class}) -public class OBAnalyticsEventQueueTest extends PowerMockTestCase { - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - private static ByteArrayOutputStream outContent; - private static Logger logger = null; - private static PrintStream printStream; - - @BeforeClass - public void beforeTests() { - - MockitoAnnotations.initMocks(this); - outContent = new ByteArrayOutputStream(); - printStream = new PrintStream(outContent); - System.setOut(printStream); - logger = LogManager.getLogger(OBAnalyticsEventQueueTest.class); - } - - @Test - public void testAddingDataToQueue() { - - outContent.reset(); - Map configs = new HashMap<>(); - configs.put("DataPublishing.WorkerThreadCount", "3"); - configs.put("DataPublishing.QueueSize", "10"); - configs.put("DataPublishing.Enabled", "true"); - configs.put("ELKAnalytics.Enabled", "true"); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - Mockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - Mockito.when(openBankingConfigParser.getConfiguration()).thenReturn(configs); - - OpenBankingConfigurationService openBankingConfigurationService = - Mockito.mock(OpenBankingConfigurationService.class); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configs); - OBAnalyticsDataHolder.getInstance().setEventQueue(Mockito.mock(EventQueue.class)); - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - - OBDataPublisherUtil.publishData("testStream", "1.0", configs); - try { - Assert.assertTrue(outContent.toString().contains("Data Stream : testStream , Data Stream Version : 1.0 , " + - "Data : {\"payload\":" + new ObjectMapper().writeValueAsString(configs) + "}")); - Assert.assertFalse(outContent.toString().contains("Data publishing is disabled. " + - "Failed to obtain a data publisher instance.")); - } catch (JsonProcessingException e) { - throw new OpenBankingRuntimeException("Error in processing JSON payload", e); - } - } - - @Test - public void tryAddingToQueueWhenDataPublishingDisabled() { - - outContent.reset(); - Map configs = new HashMap<>(); - configs.put("DataPublishing.WorkerThreadCount", "3"); - configs.put("DataPublishing.QueueSize", "10"); - configs.put("DataPublishing.Enabled", "false"); - configs.put("ELKAnalytics.Enabled", "true"); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - Mockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - Mockito.when(openBankingConfigParser.getConfiguration()).thenReturn(configs); - - OpenBankingConfigurationService openBankingConfigurationService = - Mockito.mock(OpenBankingConfigurationService.class); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configs); - OBAnalyticsDataHolder.getInstance().setEventQueue(Mockito.mock(EventQueue.class)); - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - - OBDataPublisherUtil.publishData("testStream", "1.0", configs); - Assert.assertTrue(outContent.toString().contains("Data publishing is disabled. " + - "Failed to obtain a data publisher instance.")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/OBThriftDataPublisherTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/OBThriftDataPublisherTest.java deleted file mode 100644 index 61d5fdad..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/java/com/wso2/openbanking/accelerator/data/publisher/common/OBThriftDataPublisherTest.java +++ /dev/null @@ -1,387 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.data.publisher.common; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.data.publisher.common.internal.OBAnalyticsDataHolder; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.databridge.agent.DataPublisher; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointException; -import org.wso2.carbon.databridge.commons.exception.TransportException; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Test for Open Banking thrift data publisher. - */ -public class OBThriftDataPublisherTest { - - public static final Map ATTRIBUTE_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>(2, "SampleStringAttribute"), - new AbstractMap.SimpleImmutableEntry<>(3, "SampleIntAttribute"), - new AbstractMap.SimpleImmutableEntry<>(1, "SampleBooleanAttribute")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - public static final Map ATTRIBUTE_MAP2 = Stream.of( - new AbstractMap.SimpleImmutableEntry<>(2, "SampleFloatAttribute"), - new AbstractMap.SimpleImmutableEntry<>(3, "SampleLongAttribute"), - new AbstractMap.SimpleImmutableEntry<>(1, "SampleDoubleAttribute")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - private static final Map> STREAM_ATTRIBUTE_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("testStream", ATTRIBUTE_MAP), - new AbstractMap.SimpleImmutableEntry<>("testStream2", ATTRIBUTE_MAP2)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - OBThriftDataPublisher thriftDataPublisher; - private static ByteArrayOutputStream outContent; - private static Logger logger = null; - private static PrintStream printStream; - private float floatNum = 4f; - private long longNum = 2L; - private double doubleNum = 5.5; - - @BeforeClass - public void initializeConfigurations() { - - OpenBankingConfigurationService openBankingConfigurationService = - Mockito.mock(OpenBankingConfigurationService.class); - Mockito.when(openBankingConfigurationService.getDataPublishingStreams()).thenReturn(STREAM_ATTRIBUTE_MAP); - Map configs = new HashMap<>(); - configs.put("DataPublishing.Username", "admin"); - configs.put("DataPublishing.Password", "admin"); - configs.put("DataPublishing.ServerURL", "{tcp://localhost:7612}"); - configs.put("DataPublishing.Thrift.PublishingTimeout", "2000"); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configs); - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - OBThriftDataPublisherTest.outContent = new ByteArrayOutputStream(); - OBThriftDataPublisherTest.printStream = new PrintStream(OBThriftDataPublisherTest.outContent); - System.setOut(OBThriftDataPublisherTest.printStream); - OBThriftDataPublisherTest.logger = LogManager.getLogger(OBThriftDataPublisherTest.class); - } - - @Test - public void init() { - - OBThriftDataPublisher thriftDataPublisher = new MockedOBThriftDataPublisher(); - DataPublisher dataPublisher = Mockito.mock(DataPublisher.class); - thriftDataPublisher.setDataPublisher(dataPublisher); - thriftDataPublisher.init(); - } - - @Test - public void tryInitWithoutRequiredConfigs() - throws DataEndpointAuthenticationException, DataEndpointAgentConfigurationException, DataEndpointException, - DataEndpointConfigurationException, TransportException { - outContent.reset(); - OpenBankingConfigurationService openBankingConfigurationService = - Mockito.mock(OpenBankingConfigurationService.class); - Mockito.when(openBankingConfigurationService.getDataPublishingStreams()).thenReturn(STREAM_ATTRIBUTE_MAP); - Map configs = new HashMap<>(); - configs.put("DataPublishing.Thrift.PublishingTimeout", "2000"); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configs); - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - OBThriftDataPublisher thriftDataPublisher = Mockito.spy(OBThriftDataPublisher.class); - Mockito.doReturn(Mockito.mock(DataPublisher.class)).when(thriftDataPublisher) - .getDataPublisher(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - thriftDataPublisher.init(); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains("ERROR : Error while retrieving " + - "publisher server configs")); - } - - @Test(priority = 1) - public void testStreamAttributeMapCreation() { - - thriftDataPublisher = new MockedOBThriftDataPublisher(); - thriftDataPublisher.buildStreamAttributeMap(); - - List attributes = new ArrayList<>(); - attributes.add("SampleBooleanAttribute"); - attributes.add("SampleStringAttribute"); - attributes.add("SampleIntAttribute"); - List attributesSet2 = new ArrayList<>(); - attributesSet2.add("SampleDoubleAttribute"); - attributesSet2.add("SampleFloatAttribute"); - attributesSet2.add("SampleLongAttribute"); - Map> expectedMap = new HashMap<>(); - expectedMap.put("testStream", attributes); - expectedMap.put("testStream2", attributesSet2); - Assert.assertEquals(thriftDataPublisher.getStreamAttributeMap(), expectedMap); - - } - - @Test(priority = 2) - public void setPayload() { - - String streamName = "testStream"; - Map data = new HashMap<>(); - data.put("SampleStringAttribute", "StringValue1"); - data.put("SampleIntAttribute", 2); - data.put("SampleBooleanAttribute", true); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{ - true, "StringValue1", 2 - }; - - Assert.assertEquals(result, expectedOutput); - } - - @Test(priority = 2) - public void setPayloadWithoutRequiredAttributes() { - - outContent.reset(); - String streamName = "testStream"; - Map data = new HashMap<>(); - data.put("SampleStringAttribute", "StringValue1"); - data.put("SampleIntAttribute", 2); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains("is missing in data map for ")); - } - - @Test(priority = 2) - public void setPayloadWithoutRequiredAttributes2() { - - outContent.reset(); - String streamName = "testStream"; - Map data = new HashMap<>(); - data.put("SampleStringAttribute", "StringValue1"); - data.put("SampleIntAttribute", 2); - data.put("SampleBooleanAttribute", null); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains("is missing in data map for ")); - } - - @Test(priority = 2) - public void setPayloadWithInvalidBooleanData() { - - outContent.reset(); - String streamName = "testStream"; - Map data = new HashMap<>(); - data.put("SampleStringAttribute", "StringValue1"); - data.put("SampleIntAttribute", 2); - data.put("SampleBooleanAttribute", "true"); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains(" is expecting a " + - Boolean.class.getName() + " type attribute while attribute of type ")); - } - - @Test(priority = 2) - public void setPayloadWithInvalidIntegerData() { - - outContent.reset(); - String streamName = "testStream"; - Map data = new HashMap<>(); - data.put("SampleStringAttribute", "StringValue1"); - data.put("SampleIntAttribute", 2.14); - data.put("SampleBooleanAttribute", true); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains(" is expecting a " + - Integer.class.getName() + " type attribute while attribute of type ")); - } - - @Test(priority = 2) - public void setPayloadWithInvalidStringData() { - - outContent.reset(); - String streamName = "testStream"; - Map data = new HashMap<>(); - data.put("SampleStringAttribute", 1); - data.put("SampleIntAttribute", 2); - data.put("SampleBooleanAttribute", true); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains(" is expecting a " + - String.class.getName() + " type attribute while attribute of type ")); - } - - @Test(priority = 2) - public void setPayloadWithInvalidFloatData() { - - outContent.reset(); - String streamName = "testStream2"; - Map data = new HashMap<>(); - data.put("SampleFloatAttribute", 4); - data.put("SampleLongAttribute", longNum); - data.put("SampleDoubleAttribute", doubleNum); - - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains(" is expecting a " + - Float.class.getName() + " type attribute while attribute of type ")); - } - - @Test(priority = 2) - public void setPayloadWithInvalidLongData() { - - outContent.reset(); - String streamName = "testStream2"; - Map data = new HashMap<>(); - data.put("SampleFloatAttribute", floatNum); - data.put("SampleLongAttribute", 2.2); - data.put("SampleDoubleAttribute", doubleNum); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains(" is expecting a " + - Long.class.getName() + " type attribute while attribute of type ")); - } - - @Test(priority = 2) - public void setPayloadWithInvalidDoubleData() { - - outContent.reset(); - String streamName = "testStream2"; - Map data = new HashMap<>(); - data.put("SampleFloatAttribute", floatNum); - data.put("SampleLongAttribute", longNum); - data.put("SampleDoubleAttribute", 5); - - Object[] result = thriftDataPublisher.setPayload(streamName, data); - Object[] expectedOutput = new Object[]{}; - - Assert.assertEquals(result, expectedOutput); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains(" is expecting a " + - Double.class.getName() + " type attribute while attribute of type ")); - } - - @Test - public void publish() { - - outContent.reset(); - OBThriftDataPublisher thriftDataPublisher = new MockedOBThriftDataPublisher(); - DataPublisher dataPublisher = Mockito.mock(DataPublisher.class); - thriftDataPublisher.setDataPublisher(dataPublisher); - Mockito.doReturn(true).when(dataPublisher).tryPublish(Mockito.any(), Mockito.anyLong()); - Map data = new HashMap<>(); - data.put("SampleStringAttribute", "StringValue1"); - data.put("SampleIntAttribute", 2); - data.put("SampleBooleanAttribute", true); - thriftDataPublisher.publish("testStream", "1.0", data); - Assert.assertFalse(OBThriftDataPublisherTest.outContent.toString().contains("ERROR")); - } - - @Test - public void tryPublishWhenAttributesNotDefined() { - - outContent.reset(); - OpenBankingConfigurationService openBankingConfigurationService = - Mockito.mock(OpenBankingConfigurationService.class); - Mockito.when(openBankingConfigurationService.getDataPublishingStreams()).thenReturn(STREAM_ATTRIBUTE_MAP); - Map configs = new HashMap<>(); - configs.put("DataPublishing.Username", "admin"); - configs.put("DataPublishing.Password", "admin"); - configs.put("DataPublishing.ServerURL", "{tcp://localhost:7612}"); - configs.put("DataPublishing.Thrift.PublishingTimeout", "2000"); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configs); - OBAnalyticsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - OBThriftDataPublisher thriftDataPublisher = new MockedOBThriftDataPublisher(); - DataPublisher dataPublisher = Mockito.mock(DataPublisher.class); - thriftDataPublisher.setDataPublisher(dataPublisher); - Mockito.doReturn(true).when(dataPublisher).tryPublish(Mockito.any(), Mockito.anyLong()); - Map data = new HashMap<>(); - thriftDataPublisher.publish("testStream2", "1.0", data); - Assert.assertTrue(OBThriftDataPublisherTest.outContent.toString().contains("ERROR : Error while setting " + - "payload to publish data.")); - } - - private class MockedOBThriftDataPublisher extends OBThriftDataPublisher { - - private Map> validationMap; - - public MockedOBThriftDataPublisher() { - validationMap = new HashMap<>(); - Map metadata1 = new HashMap<>(); - Map metadata2 = new HashMap<>(); - Map metadata3 = new HashMap<>(); - Map metadata4 = new HashMap<>(); - Map metadata5 = new HashMap<>(); - Map metadata6 = new HashMap<>(); - metadata1.put("required", true); - metadata1.put("type", "int"); - validationMap.put("testStream_SampleIntAttribute", metadata1); - metadata2.put("required", true); - metadata2.put("type", "boolean"); - validationMap.put("testStream_SampleBooleanAttribute", metadata2); - metadata3.put("required", false); - metadata3.put("type", "string"); - validationMap.put("testStream_SampleStringAttribute", metadata3); - metadata4.put("required", true); - metadata4.put("type", "float"); - validationMap.put("testStream2_SampleFloatAttribute", metadata4); - metadata5.put("required", true); - metadata5.put("type", "long"); - validationMap.put("testStream2_SampleLongAttribute", metadata5); - metadata6.put("required", false); - metadata6.put("type", "double"); - validationMap.put("testStream2_SampleDoubleAttribute", metadata6); - } - - @Override - protected DataPublisher getDataPublisher(String serverURL, String authURLSet, String serverUser, - String serverPassword) { - - return Mockito.mock(DataPublisher.class); - } - - @Override - protected Map> getAttributeValidationMap() { - - return validationMap; - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/resources/testng.xml deleted file mode 100644 index 732af2c3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/com.wso2.openbanking.accelerator.data.publisher.common/src/test/resources/testng.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/pom.xml deleted file mode 100644 index ec348abf..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.data.publisher/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.data.publisher - WSO2 Open Banking - Data Publisher - pom - - - com.wso2.openbanking.accelerator.data.publisher.common - com.wso2.openbanking.accelerator.authentication.data.publisher - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/pom.xml deleted file mode 100644 index c3456744..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/pom.xml +++ /dev/null @@ -1,301 +0,0 @@ - - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - - com.wso2.openbanking.accelerator.gateway - bundle - WSO2 Open Banking - Gateway component - - - org.wso2.eclipse.osgi - org.eclipse.osgi.services - - - org.eclipse.osgi - org.eclipse.osgi - - - commons-logging - commons-logging - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - org.apache.synapse - synapse-core - - - io.swagger.core.v3 - swagger-models - - - io.swagger.parser.v3 - swagger-parser - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.data.publisher.common - - - org.wso2.orbit.com.hazelcast - hazelcast - - - - - org.wso2.orbit.org.bouncycastle - bcprov-jdk18on - - - org.testng - testng - test - - - org.powermock - powermock-module-testng - test - - - org.powermock - powermock-api-mockito - test - - - org.mockito - mockito-all - test - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.common.gateway - - - org.wso2.orbit.com.hazelcast - hazelcast - - - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.keymgt - - - org.wso2.orbit.com.hazelcast - hazelcast - - - - - io.jsonwebtoken - jjwt - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.orbit.com.hazelcast - hazelcast - - - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-annotations - - - org.wso2.am.analytics.publisher - org.wso2.am.analytics.publisher.client - - - org.wso2.orbit.com.hazelcast - hazelcast - - - - - org.wso2.orbit.com.nimbusds - nimbus-jose-jwt - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.gateway.internal - - - org.osgi.framework; version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component; version="${osgi.service.component.imp.pkg.version.range}", - org.wso2.am.analytics.publisher.*; version="${analytics.publisher.version}", - - com.nimbusds.jwt.*;version="${nimbusds.osgi.version.range}", - com.nimbusds.jose.*;version="${nimbusds.osgi.version.range}", - - - !com.wso2.openbanking.accelerator.gateway.internal, - com.wso2.openbanking.accelerator.gateway.*; - version="${project.version}", - com.wso2.openbanking.accelerator.gateway.executor.*; - version="${project.version}", - com.wso2.openbanking.accelerator.gateway.reporter.*; - version="${project.version}", - - * - <_dsannotations>* - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - false - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.jacoco - jacoco-maven-plugin - - - - **/*Constants.class - **/*Component.class - **/*APIRequestContext.class - **/*APIResponseContext.class - **/*GatewayCache.class - **/*CertificateRevocationCache.class - **/*TppValidationCache.class - **/*GatewayCacheKey.class - **/*OpenBankingExecutorError.class - **/*DataHolder.class - **/*Exception.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.73 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - org.wso2.orbit.com.fasterxml.jackson.core:jackson-core - org.wso2.orbit.com.hazelcast:hazelcast:3.12.2.wso2v1 - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/CertificateRevocationCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/CertificateRevocationCache.java deleted file mode 100644 index a1a41640..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/CertificateRevocationCache.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCache; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; - -/** - * Cache definition to store API Resource Security Schemes. - */ -public class CertificateRevocationCache extends OpenBankingBaseCache { - - private static final String CACHE_NAME = "OPEN_BANKING_CLIENT_CERTIFICATE_CACHE"; - - private static CertificateRevocationCache clientCertificateCache; - private final Integer accessExpiryMinutes; - private final Integer modifiedExpiryMinutes; - - /** - * Initialize with unique cache name. - */ - private CertificateRevocationCache() { - - super(CACHE_NAME); - this.accessExpiryMinutes = setAccessExpiryMinutes(); - this.modifiedExpiryMinutes = setModifiedExpiryMinutes(); - } - - /** - * Singleton getInstance method to create only one object. - * - * @return TPPValidationCache object - */ - public static synchronized CertificateRevocationCache getInstance() { - if (clientCertificateCache == null) { - clientCertificateCache = new CertificateRevocationCache(); - } - return clientCertificateCache; - } - - @Override - public int getCacheAccessExpiryMinutes() { - - return accessExpiryMinutes; - } - - @Override - public int getCacheModifiedExpiryMinutes() { - - return modifiedExpiryMinutes; - } - - public int setAccessExpiryMinutes() { - - return TPPCertValidatorDataHolder.getInstance().getTppCertRevocationCacheExpiry(); - } - - public int setModifiedExpiryMinutes() { - - return TPPCertValidatorDataHolder.getInstance().getTppCertRevocationCacheExpiry(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/GatewayCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/GatewayCache.java deleted file mode 100644 index d716c8a7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/GatewayCache.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCache; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; - -/** - * Cache definition to store API Resource Security Schemes. - */ -public class GatewayCache extends OpenBankingBaseCache { - - private static final String cacheName = "OPEN_BANKING_GATEWAY_CACHE"; - - private Integer accessExpiryMinutes; - private Integer modifiedExpiryMinutes; - - /** - * Initialize with unique cache name. - */ - public GatewayCache() { - - super(cacheName); - this.accessExpiryMinutes = setAccessExpiryMinutes(); - this.modifiedExpiryMinutes = setModifiedExpiryMinutes(); - } - - @Override - public int getCacheAccessExpiryMinutes() { - - return accessExpiryMinutes; - } - - @Override - public int getCacheModifiedExpiryMinutes() { - - return modifiedExpiryMinutes; - } - - public int setAccessExpiryMinutes() { - - return GatewayDataHolder.getInstance().getGatewayCacheAccessExpiry(); - } - - public int setModifiedExpiryMinutes() { - - return GatewayDataHolder.getInstance().getGatewayCacheModifiedExpiry(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/GatewayCacheKey.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/GatewayCacheKey.java deleted file mode 100644 index 3077c60a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/GatewayCacheKey.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCacheKey; - -import java.io.Serializable; -import java.util.Objects; - -/** - * Cache Key for Open Banking Gateway cache. - */ -public class GatewayCacheKey extends OpenBankingBaseCacheKey implements Serializable { - - private static final long serialVersionUID = 883027070771592120L; - public String gatewayCacheKey; - - public GatewayCacheKey(String gatewayCacheKey) { - - this.gatewayCacheKey = gatewayCacheKey; - } - - public static GatewayCacheKey of(String gatewayCacheKey) { - - return new GatewayCacheKey(gatewayCacheKey); - } - - @Override - public boolean equals(Object o) { - - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - GatewayCacheKey that = (GatewayCacheKey) o; - return Objects.equals(gatewayCacheKey, that.gatewayCacheKey); - } - - @Override - public int hashCode() { - - return Objects.hash(gatewayCacheKey); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/TppValidationCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/TppValidationCache.java deleted file mode 100644 index 610a6528..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/cache/TppValidationCache.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCache; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; - -/** - * Cache definition to store API Resource Security Schemes. - */ -public class TppValidationCache extends OpenBankingBaseCache { - - private static final String CACHE_NAME = "OPEN_BANKING_TPP_VALIDATION_CACHE"; - - private static TppValidationCache tppValidationCache; - private final Integer accessExpiryMinutes; - private final Integer modifiedExpiryMinutes; - - /** - * Initialize with unique cache name. - */ - private TppValidationCache() { - - super(CACHE_NAME); - this.accessExpiryMinutes = setAccessExpiryMinutes(); - this.modifiedExpiryMinutes = setModifiedExpiryMinutes(); - } - - /** - * Singleton getInstance method to create only one object. - * - * @return TPPValidationCache object - */ - public static synchronized TppValidationCache getInstance() { - if (tppValidationCache == null) { - tppValidationCache = new TppValidationCache(); - } - return tppValidationCache; - } - - @Override - public int getCacheAccessExpiryMinutes() { - - return accessExpiryMinutes; - } - - @Override - public int getCacheModifiedExpiryMinutes() { - - return modifiedExpiryMinutes; - } - - public int setAccessExpiryMinutes() { - - return TPPCertValidatorDataHolder.getInstance().getTppValidationCacheExpiry(); - } - - public int setModifiedExpiryMinutes() { - - return TPPCertValidatorDataHolder.getInstance().getTppValidationCacheExpiry(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/AbstractRequestRouter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/AbstractRequestRouter.java deleted file mode 100644 index 9c4a35bb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/AbstractRequestRouter.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Open Banking abstract Request Router. - */ -public abstract class AbstractRequestRouter { - - private Map> executorMap = new HashMap<>(); - - /** - * Initiation method of the Router. - */ - @Generated(message = "Ignoring since the method require OSGi services to function. This functionality is tested " + - "in other services") - public void build() { - - Map> executorConfig = - GatewayDataHolder.getInstance().getOpenBankingConfigurationService().getExecutors(); - executorConfig.keySet().forEach(consentType -> { - Map integerStringMap = executorConfig.get(consentType); - List executorList = integerStringMap.keySet().stream() - .map(integer -> (OpenBankingGatewayExecutor) OpenBankingUtils - .getClassInstanceFromFQN(integerStringMap.get(integer))).collect(Collectors.toList()); - executorMap.put(consentType, executorList); - }); - } - - /** - * Method to obtain correct executors for the given request context. ( Expected to be implemented at toolkit) - * - * @param requestContext OB Request context - * @return List of executors - */ - public abstract List getExecutorsForRequest(OBAPIRequestContext requestContext); - - /** - * Method to obtain correct executors for the given response context. ( Expected to be implemented at toolkit) - * - * @param requestContext OB Response context - * @return List of executors - */ - public abstract List getExecutorsForResponse(OBAPIResponseContext requestContext); - - public Map> getExecutorMap() { - - return executorMap; - } - - public void setExecutorMap( - Map> executorMap) { - - this.executorMap = executorMap; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/DefaultRequestRouter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/DefaultRequestRouter.java deleted file mode 100644 index 6e52ee52..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/DefaultRequestRouter.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; - -import java.util.ArrayList; -import java.util.List; - -/** - * Open Banking Default Request Router. - */ -public class DefaultRequestRouter extends AbstractRequestRouter { - - private static final List EMPTY_LIST = new ArrayList<>(); - - public List getExecutorsForRequest(OBAPIRequestContext requestContext) { - if (GatewayConstants.API_TYPE_NON_REGULATORY - .equals(requestContext.getOpenAPI().getExtensions().get(GatewayConstants.API_TYPE_CUSTOM_PROP))) { - requestContext.addContextProperty(GatewayConstants.API_TYPE_CUSTOM_PROP, - GatewayConstants.API_TYPE_NON_REGULATORY); - return EMPTY_LIST; - } else if (GatewayConstants.API_TYPE_CONSENT - .equals(requestContext.getOpenAPI().getExtensions().get(GatewayConstants.API_TYPE_CUSTOM_PROP))) { - requestContext.addContextProperty(GatewayConstants.API_TYPE_CUSTOM_PROP, - GatewayConstants.API_TYPE_CONSENT); - return this.getExecutorMap().get("Consent"); - } else if (requestContext.getMsgInfo().getResource().contains("/register")) { - return this.getExecutorMap().get("DCR"); - } else { - return this.getExecutorMap().get("Default"); - } - } - - public List getExecutorsForResponse(OBAPIResponseContext responseContext) { - - if (responseContext.getContextProps().containsKey(GatewayConstants.API_TYPE_CUSTOM_PROP)) { - if (GatewayConstants.API_TYPE_NON_REGULATORY - .equals(responseContext.getContextProps().get(GatewayConstants.API_TYPE_CUSTOM_PROP))) { - return EMPTY_LIST; - } else if (GatewayConstants.API_TYPE_CONSENT - .equals(responseContext.getContextProps().get(GatewayConstants.API_TYPE_CUSTOM_PROP))) { - return this.getExecutorMap().get("Consent"); - } - } - - if (responseContext.getMsgInfo().getResource().contains("/register")) { - return this.getExecutorMap().get("DCR"); - } else { - return this.getExecutorMap().get("Default"); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/OBExtensionListenerImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/OBExtensionListenerImpl.java deleted file mode 100644 index 22ff79a0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/OBExtensionListenerImpl.java +++ /dev/null @@ -1,280 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseStatus; -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.ResponseContextDTO; -import org.wso2.carbon.apimgt.common.gateway.extensionlistener.ExtensionListener; - -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; - -/** - * Open Banking implementation for Extension listener. - */ -public class OBExtensionListenerImpl implements ExtensionListener { - - private static final Log log = LogFactory.getLog(OBExtensionListenerImpl.class); - - @Override - @Generated(message = "Ignoring since the method has covered in other tests") - public ExtensionResponseDTO preProcessRequest(RequestContextDTO requestContextDTO) { - - OBAPIRequestContext obapiRequestContext = new OBAPIRequestContext(requestContextDTO, new HashMap<>(), - new HashMap<>()); - for (OpenBankingGatewayExecutor gatewayExecutor : - GatewayDataHolder.getInstance().getRequestRouter().getExecutorsForRequest(obapiRequestContext)) { - gatewayExecutor.preProcessRequest(obapiRequestContext); - } - - if (!obapiRequestContext.isError()) { - setPropertiesToCache(requestContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY, obapiRequestContext.getContextProps()); - - setPropertiesToCache(requestContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY, obapiRequestContext.getAnalyticsData()); - } else { - publishAnalyticsData(obapiRequestContext.getAnalyticsData()); - } - return getResponseDTOForRequest(obapiRequestContext); - } - - @Override - @Generated(message = "Ignoring since the method has covered in other tests") - public ExtensionResponseDTO postProcessRequest(RequestContextDTO requestContextDTO) { - - Map contextProps = getPropertiesFromCache(requestContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY); - Map analyticsData = getPropertiesFromCache(requestContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY); - - OBAPIRequestContext obapiRequestContext = - new OBAPIRequestContext(requestContextDTO, contextProps, analyticsData); - for (OpenBankingGatewayExecutor gatewayExecutor : - GatewayDataHolder.getInstance().getRequestRouter().getExecutorsForRequest(obapiRequestContext)) { - gatewayExecutor.postProcessRequest(obapiRequestContext); - } - - if (!obapiRequestContext.isError()) { - setPropertiesToCache(requestContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY, obapiRequestContext.getContextProps()); - - setPropertiesToCache(requestContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY, obapiRequestContext.getAnalyticsData()); - } else { - publishAnalyticsData(obapiRequestContext.getAnalyticsData()); - } - return getResponseDTOForRequest(obapiRequestContext); - } - - @Override - @Generated(message = "Ignoring since the method has covered in other tests") - public ExtensionResponseDTO preProcessResponse(ResponseContextDTO responseContextDTO) { - - Map contextProps = getPropertiesFromCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY); - Map analyticsData = getPropertiesFromCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY); - OBAPIResponseContext obapiResponseContext = - new OBAPIResponseContext(responseContextDTO, contextProps, analyticsData); - for (OpenBankingGatewayExecutor gatewayExecutor : - GatewayDataHolder.getInstance().getRequestRouter().getExecutorsForResponse(obapiResponseContext)) { - gatewayExecutor.preProcessResponse(obapiResponseContext); - } - - if (!obapiResponseContext.isError()) { - setPropertiesToCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY, obapiResponseContext.getContextProps()); - - setPropertiesToCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY, obapiResponseContext.getAnalyticsData()); - } else { - publishAnalyticsData(obapiResponseContext.getAnalyticsData()); - } - return getResponseDTOForResponse(obapiResponseContext); - } - - @Override - @Generated(message = "Ignoring since the method has covered in other tests") - public ExtensionResponseDTO postProcessResponse(ResponseContextDTO responseContextDTO) { - - Map contextProps = getPropertiesFromCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY); - Map analyticsData = getPropertiesFromCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY); - OBAPIResponseContext obapiResponseContext = - new OBAPIResponseContext(responseContextDTO, contextProps, analyticsData); - for (OpenBankingGatewayExecutor gatewayExecutor : - GatewayDataHolder.getInstance().getRequestRouter().getExecutorsForResponse(obapiResponseContext)) { - gatewayExecutor.postProcessResponse(obapiResponseContext); - } - publishAnalyticsData(obapiResponseContext.getAnalyticsData()); - ExtensionResponseDTO responseDTOForResponse = getResponseDTOForResponse(obapiResponseContext); - removePropertiesFromCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.CONTEXT_PROP_CACHE_KEY); - removePropertiesFromCache(responseContextDTO.getMsgInfo().getMessageId() + - GatewayConstants.ANALYTICS_PROP_CACHE_KEY); - return responseDTOForResponse; - } - - protected ExtensionResponseDTO getResponseDTOForRequest(OBAPIRequestContext obapiRequestContext) { - - ExtensionResponseDTO extensionResponseDTO = new ExtensionResponseDTO(); - if (obapiRequestContext.isError()) { - - int statusCode = (!obapiRequestContext.getContextProps().containsKey(GatewayConstants.ERROR_STATUS_PROP)) ? - HttpStatus.SC_INTERNAL_SERVER_ERROR : - Integer.parseInt(obapiRequestContext.getContextProperty(GatewayConstants.ERROR_STATUS_PROP)); - extensionResponseDTO.setStatusCode(statusCode); - extensionResponseDTO.setResponseStatus(ExtensionResponseStatus.RETURN_ERROR.toString()); - } else if (obapiRequestContext.getContextProps().containsKey(GatewayConstants.IS_RETURN_RESPONSE) && - Boolean.parseBoolean(obapiRequestContext.getContextProps().get(GatewayConstants.IS_RETURN_RESPONSE))) { - Map headers = obapiRequestContext.getMsgInfo().getHeaders(); - headers.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - obapiRequestContext.getMsgInfo().setHeaders(headers); - extensionResponseDTO.setHeaders(headers); - if (obapiRequestContext.getContextProps().containsKey(GatewayConstants.MODIFIED_STATUS)) { - extensionResponseDTO.setStatusCode(Integer.parseInt(obapiRequestContext.getContextProps() - .get(GatewayConstants.MODIFIED_STATUS))); - } - extensionResponseDTO.setResponseStatus(ExtensionResponseStatus.RETURN_ERROR.toString()); - } else { - extensionResponseDTO.setResponseStatus(ExtensionResponseStatus.CONTINUE.toString()); - } - - String modifiedPayload = obapiRequestContext.getModifiedPayload(); - if (modifiedPayload != null) { - extensionResponseDTO.setPayload(new ByteArrayInputStream(modifiedPayload.getBytes(StandardCharsets.UTF_8))); - } - Map addedHeaders = obapiRequestContext.getAddedHeaders(); - if (addedHeaders.size() != 0) { - TreeMap headers = new TreeMap<>(); - headers.putAll(obapiRequestContext.getMsgInfo().getHeaders()); - for (Map.Entry headerEntry : addedHeaders.entrySet()) { - headers.put(headerEntry.getKey(), headerEntry.getValue()); - } - extensionResponseDTO.setHeaders(headers); - } - return extensionResponseDTO; - } - - protected ExtensionResponseDTO getResponseDTOForResponse(OBAPIResponseContext obapiResponseContext) { - - ExtensionResponseDTO extensionResponseDTO = new ExtensionResponseDTO(); - if (obapiResponseContext.isError()) { - int statusCode = (!obapiResponseContext.getContextProps().containsKey(GatewayConstants.ERROR_STATUS_PROP)) ? - HttpStatus.SC_INTERNAL_SERVER_ERROR : - Integer.parseInt(obapiResponseContext.getContextProperty(GatewayConstants.ERROR_STATUS_PROP)); - extensionResponseDTO.setStatusCode(statusCode); - extensionResponseDTO.setResponseStatus(ExtensionResponseStatus.RETURN_ERROR.toString()); - } else if (obapiResponseContext.getContextProps().containsKey(GatewayConstants.IS_RETURN_RESPONSE) && - Boolean.parseBoolean(obapiResponseContext.getContextProps().get(GatewayConstants.IS_RETURN_RESPONSE))) { - Map headers = obapiResponseContext.getMsgInfo().getHeaders(); - headers.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - obapiResponseContext.getMsgInfo().setHeaders(headers); - extensionResponseDTO.setHeaders(headers); - if (obapiResponseContext.getContextProps().containsKey(GatewayConstants.MODIFIED_STATUS)) { - extensionResponseDTO.setStatusCode(Integer.parseInt(obapiResponseContext.getContextProps() - .get(GatewayConstants.MODIFIED_STATUS))); - } - extensionResponseDTO.setResponseStatus(ExtensionResponseStatus.RETURN_ERROR.toString()); - } else { - extensionResponseDTO.setResponseStatus(ExtensionResponseStatus.CONTINUE.toString()); - } - - String modifiedPayload = obapiResponseContext.getModifiedPayload(); - if (modifiedPayload != null) { - extensionResponseDTO.setPayload(new ByteArrayInputStream(modifiedPayload.getBytes(StandardCharsets.UTF_8))); - } - Map addedHeaders = obapiResponseContext.getAddedHeaders(); - if (addedHeaders.size() != 0) { - HashMap headers = new HashMap<>(); - headers.putAll(obapiResponseContext.getMsgInfo().getHeaders()); - for (Map.Entry headerEntry : addedHeaders.entrySet()) { - headers.put(headerEntry.getKey(), headerEntry.getValue()); - } - extensionResponseDTO.setHeaders(headers); - } - return extensionResponseDTO; - } - - @Override - public String getType() { - - return null; - } - - /** - * Method to store properties to cache. - * - * @param key unique cache key - * @param contextProps properties to store - */ - private void setPropertiesToCache(String key, Map contextProps) { - - GatewayDataHolder.getGatewayCache().addToCache(GatewayCacheKey.of(key), contextProps); - } - - /** - * Method to retrieve context properties from cache. - * - * @param key unique cache key - * @return context properties - */ - private Map getPropertiesFromCache(String key) { - //Need to implement after adding base cache implementation to the common module. - Object cachedObject = GatewayDataHolder.getGatewayCache().getFromCache(GatewayCacheKey.of(key)); - return cachedObject == null ? new HashMap<>() : (Map) cachedObject; - } - - /** - * Method to remove context properties from cache. - * - * @param key unique cache key - * @return context properties - */ - private void removePropertiesFromCache(String key) { - //Need to implement after adding base cache implementation to the common module. - GatewayDataHolder.getGatewayCache().removeFromCache(GatewayCacheKey.of(key)); - } - - private void publishAnalyticsData(Map analyticsData) { - - if (analyticsData != null && !analyticsData.isEmpty()) { - OBDataPublisherUtil. - publishData(GatewayConstants.API_DATA_STREAM, GatewayConstants.API_DATA_VERSION, analyticsData); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/OpenBankingGatewayExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/OpenBankingGatewayExecutor.java deleted file mode 100644 index 9a659d3a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/core/OpenBankingGatewayExecutor.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; - -/** - * Open Banking executor interface. - */ -public interface OpenBankingGatewayExecutor { - - /** - * Method to handle pre request. - * - * @param obapiRequestContext OB request context object - */ - public void preProcessRequest(OBAPIRequestContext obapiRequestContext); - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - public void postProcessRequest(OBAPIRequestContext obapiRequestContext); - - /** - * Method to handle pre response. - * - * @param obapiResponseContext OB response context object - */ - public void preProcessResponse(OBAPIResponseContext obapiResponseContext); - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - public void postProcessResponse(OBAPIResponseContext obapiResponseContext); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/dcr/DCRExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/dcr/DCRExecutor.java deleted file mode 100644 index 3eefec9c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/dcr/DCRExecutor.java +++ /dev/null @@ -1,1032 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.dcr; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.proc.BadJOSEException; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import org.json.JSONException; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import javax.ws.rs.HttpMethod; - -/** - * Executor for signature validation, am app creation and API subscription for DCR. - */ -public class DCRExecutor implements OpenBankingGatewayExecutor { - - private static final Log log = LogFactory.getLog(DCRExecutor.class); - private static String clientIdParam = "client_id"; - private static String registrationAccessTokenParam = "registration_access_token"; - private static String clientSecret = "client_secret"; - private static String applicationIdParam = "applicationId"; - private static String userName = "userName"; - private static String obDCREndpoint = "api/openbanking/dynamic-client-registration/register"; - private static Map urlMap = GatewayDataHolder.getInstance().getUrlMap(); - - public static void setUrlMap(Map conf) { - - if (urlMap == null) { - DCRExecutor.urlMap = conf; - } - } - - @Generated(message = "Excluding from unit tests since there is an external http call") - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - if (obapiRequestContext.isError()) { - return; - } - boolean validateJWT = true; - Map configs = GatewayDataHolder.getInstance() - .getOpenBankingConfigurationService().getConfigurations(); - if (configs.containsKey(GatewayConstants.VALIDATE_JWT)) { - validateJWT = Boolean.parseBoolean(configs.get(GatewayConstants.VALIDATE_JWT).toString()); - } - - if (validateJWT) { - String payload = obapiRequestContext.getRequestPayload(); - try { - String httpMethod = obapiRequestContext.getMsgInfo().getHttpMethod(); - if (HttpMethod.POST.equalsIgnoreCase(httpMethod) || HttpMethod.PUT.equalsIgnoreCase(httpMethod)) { - if (payload != null) { - //decode request jwt - validateRequestSignature(payload, obapiRequestContext); - } else { - handleBadRequestError(obapiRequestContext, "Malformed request found"); - } - } - } catch (ParseException e) { - log.error("Error occurred while decoding the provided jwt", e); - handleBadRequestError(obapiRequestContext, "Malformed request JWT"); - } catch (BadJOSEException e) { - log.error("Error occurred while validating the signature", e); - handleBadRequestError(obapiRequestContext, "Invalid request signature. " + e.getMessage()); - } catch (JOSEException | MalformedURLException e) { - log.error("Error occurred while validating the signature", e); - handleBadRequestError(obapiRequestContext, "Invalid request signature"); - } catch (OpenBankingExecutorException e) { - log.error("Error occurred while validating the signature", e); - handleBadRequestError(obapiRequestContext, e.getErrorPayload()); - } - } - - } - - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - if (obapiResponseContext.isError()) { - return; - } - String basicAuthHeader = GatewayUtils.getBasicAuthHeader(urlMap.get(userName).toString(), - String.valueOf((char[]) urlMap.get(GatewayConstants.PASSWORD))); - Map> regulatoryAPIs = GatewayDataHolder.getInstance() - .getOpenBankingConfigurationService().getAllowedAPIs(); - - switch (obapiResponseContext.getMsgInfo().getHttpMethod().toUpperCase()) { - case HttpMethod.POST : - if (HttpStatus.SC_CREATED == obapiResponseContext.getStatusCode()) { - String fullBackEndURL = urlMap.get(GatewayConstants.IAM_HOSTNAME).toString().concat("/") - .concat(obDCREndpoint); - postProcessResponseForRegister(obapiResponseContext, basicAuthHeader, fullBackEndURL, - regulatoryAPIs); - } - break; - case HttpMethod.PUT : - if (HttpStatus.SC_OK == obapiResponseContext.getStatusCode()) { - postProcessResponseForUpdate(obapiResponseContext, basicAuthHeader, regulatoryAPIs); - } - break; - case HttpMethod.DELETE : - if (HttpStatus.SC_NO_CONTENT == obapiResponseContext.getStatusCode()) { - postProcessResponseForDelete(obapiResponseContext, basicAuthHeader); - } - } - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Generated(message = "Ignoring since it's implemented as an extension point") - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - if (obapiRequestContext.isError()) { - return; - } - String httpMethod = obapiRequestContext.getMsgInfo().getHttpMethod(); - - if (HttpMethod.GET.equalsIgnoreCase(httpMethod) || HttpMethod.PUT.equalsIgnoreCase(httpMethod) || - HttpMethod.DELETE.equalsIgnoreCase(httpMethod)) { - String[] contextPathValues = obapiRequestContext.getMsgInfo().getResource().split("/"); - String clientIdSentInRequest = ""; - List paramList = Arrays.asList(contextPathValues); - int count = paramList.size(); - clientIdSentInRequest = paramList.stream().skip(count - 1).findFirst().get().toString(); - String clientIdBoundToToken = obapiRequestContext.getApiRequestInfo().getConsumerKey(); - if (!clientIdSentInRequest.equals(clientIdBoundToToken)) { - obapiRequestContext.setError(true); - obapiRequestContext.addContextProperty(GatewayConstants.ERROR_STATUS_PROP, - String.valueOf(OpenBankingErrorCodes.UNAUTHORIZED_CODE)); - Map requestHeaders = obapiRequestContext.getMsgInfo().getHeaders(); - requestHeaders.remove(GatewayConstants.CONTENT_TYPE_TAG); - requestHeaders.remove(GatewayConstants.CONTENT_LENGTH); - obapiRequestContext.getMsgInfo().setHeaders(requestHeaders); - return; - } - } - char[] adminPassword = (char[]) urlMap.get(GatewayConstants.PASSWORD); - String basicAuthHeader = GatewayUtils.getBasicAuthHeader(urlMap.get(userName).toString(), - String.valueOf(adminPassword)); - Map headers = new HashMap<>(); - String bearerAccessToken = ""; - if (obapiRequestContext.getMsgInfo().getHeaders() != null && - obapiRequestContext.getMsgInfo().getHeaders().get(GatewayConstants.AUTH_HEADER) != null) { - bearerAccessToken = obapiRequestContext.getMsgInfo().getHeaders().get(GatewayConstants.AUTH_HEADER) - .replace(GatewayConstants.BEARER_TAG, "").trim(); - } - headers.put(GatewayConstants.AUTH_HEADER, basicAuthHeader); - headers.put(registrationAccessTokenParam, bearerAccessToken); - obapiRequestContext.setAddedHeaders(headers); - if (HttpMethod.DELETE.equalsIgnoreCase(httpMethod)) { - try { - //call dcr endpoint of IS to get the application name to be deleted - JsonObject createdSpDetails = callGet(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(obapiRequestContext.getApiRequestInfo().getConsumerKey()), - basicAuthHeader, "", "").getAsJsonObject(); - String applicationName = createdSpDetails.get("client_name").getAsString(); - - //add application name to the cache - String cacheKey = obapiRequestContext.getApiRequestInfo().getConsumerKey() - .concat(GatewayConstants.AM_APP_NAME_CACHEKEY); - GatewayDataHolder.getGatewayCache().addToCache(GatewayCacheKey.of(cacheKey), applicationName); - - } catch (IOException | OpenBankingException | URISyntaxException e) { - log.error("Error occurred while deleting application", e); - handleRequestInternalServerError(obapiRequestContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - } - - } - } - - /** - * Method to handle response for DCR POST requests. - * - * @param obapiResponseContext OB response context object - * @param basicAuthHeader Basic authentication header for accessing the DCR endpoint. - * @param fullBackEndURL URL of the OB DCR Endpoint - * @param regulatoryAPIs A map containing regulatory API names and the related authorized roles - */ - private void postProcessResponseForRegister(OBAPIResponseContext obapiResponseContext, String basicAuthHeader, - String fullBackEndURL, Map> regulatoryAPIs) { - - try { - JsonParser jsonParser = new JsonParser(); - JsonObject createdDCRAppDetails = ((JsonObject) jsonParser - .parse(obapiResponseContext.getResponsePayload())); - //get software statement from dcr app details - String softwareStatement = createdDCRAppDetails.has(OpenBankingConstants.SOFTWARE_STATEMENT) ? - createdDCRAppDetails.get(OpenBankingConstants.SOFTWARE_STATEMENT).toString() : null; - - //call IS DCR endpoint to create application for obtaining a token to invoke devportal REST APIs - JsonElement registrationResponse = createServiceProvider(basicAuthHeader, - createdDCRAppDetails.get("software_id").getAsString()); - if (registrationResponse == null) { - log.error("Error while creating AM app for invoking APIM rest apis"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - //call token endpoint to retrieve a token for invoking the devportal REST apis - String amRestAPIInvokeClientId = registrationResponse.getAsJsonObject() - .get(clientIdParam).getAsString(); - - String authHeaderForTokenRequest = GatewayUtils - .getBasicAuthHeader(registrationResponse.getAsJsonObject().get(clientIdParam).getAsString(), - registrationResponse.getAsJsonObject().get(clientSecret).getAsString()); - - JsonElement tokenResponse = getToken(authHeaderForTokenRequest, - urlMap.get(GatewayConstants.TOKEN_URL).toString(), amRestAPIInvokeClientId); - - if (tokenResponse == null || tokenResponse.getAsJsonObject().get("access_token") == null) { - log.error("Error while creating tokens"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - //delete SP created for calling dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - String token = tokenResponse.getAsJsonObject().get("access_token").getAsString(); - String getSPDetails = urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(createdDCRAppDetails.get(clientIdParam).getAsString()); - //call IS dcr api to get client secret and client name - JsonElement createdSpDetails = callGet(getSPDetails, basicAuthHeader, "", ""); - if (createdSpDetails == null) { - log.error("Error while retrieving client id and secret"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - //delete SP created for calling dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - - //create am application - JsonObject amAppCreatePayload = getAppCreatePayload(createdSpDetails.getAsJsonObject() - .get("client_name").getAsString()); - JsonElement amApplicationCreateResponse = - callPost(urlMap.get(GatewayConstants.APP_CREATE_URL).toString(), - amAppCreatePayload.toString(), GatewayConstants.BEARER_TAG.concat(token)); - - if (amApplicationCreateResponse == null) { - log.error("Error while creating AM app"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - //delete SP created for calling dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - String keyMapURL = urlMap.get(GatewayConstants.KEY_MAP_URL).toString() - .replace("application-id", amApplicationCreateResponse.getAsJsonObject() - .get(applicationIdParam).getAsString()); - String keyManagerName = GatewayDataHolder.getInstance().getOpenBankingConfigurationService() - .getConfigurations().get(OpenBankingConstants.OB_KM_NAME).toString(); - - //map keys to am application - JsonObject keyMapPayload = getKeyMapPayload(createdDCRAppDetails.get(clientIdParam).getAsString(), - createdSpDetails.getAsJsonObject().get(clientSecret).getAsString(), - OpenBankingUtils.getSoftwareEnvironmentFromSSA(softwareStatement), keyManagerName); - - JsonElement amKeyMapResponse = callPost(keyMapURL, keyMapPayload.toString(), - GatewayConstants.BEARER_TAG.concat(token)); - if (amKeyMapResponse == null) { - log.error("Error while mapping keys to AM app"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - //delete SP created for calling dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader); - //delete AM application - callDelete(urlMap.get(GatewayConstants.APP_CREATE_URL).toString() - .concat("/").concat(amApplicationCreateResponse.getAsJsonObject() - .get(applicationIdParam).getAsString()), GatewayConstants.BEARER_TAG.concat(token)); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - //get list of published APIs - JsonElement publishedAPIsResponse = callGet(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString(), - GatewayConstants.BEARER_TAG.concat(token), "", ""); - if (publishedAPIsResponse == null) { - log.error("Error while retrieving published APIs"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - //delete SP created for calling dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader); - //delete AM application - callDelete(urlMap.get(GatewayConstants.APP_CREATE_URL).toString() - .concat("/").concat(amApplicationCreateResponse.getAsJsonObject() - .get(applicationIdParam).getAsString()), GatewayConstants.BEARER_TAG.concat(token)); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - - List apiIDList = new ArrayList<>(); - if (regulatoryAPIs != null) { - if (StringUtils.isEmpty(softwareStatement)) { - apiIDList = filterRegulatoryAPIs(regulatoryAPIs, publishedAPIsResponse.getAsJsonObject() - .get(OpenBankingConstants.API_LIST).getAsJsonArray(), Collections.emptyList()); - } else { - apiIDList = filterRegulatoryAPIs(regulatoryAPIs, publishedAPIsResponse.getAsJsonObject() - .get(OpenBankingConstants.API_LIST).getAsJsonArray(), getRolesFromSSA(softwareStatement)); - } - } else { - log.warn("No regulatory APIs configured. Application will be subscribed to all published APIs"); - //subscribe to all APIs if there are no configured regulatory APIs - for (JsonElement apiInfo : publishedAPIsResponse.getAsJsonObject().get("list").getAsJsonArray()) { - apiIDList.add(apiInfo.getAsJsonObject().get("id").getAsString()); - } - } - //subscribe to apis - JsonArray subscribeAPIsPayload = getAPISubscriptionPayload(amApplicationCreateResponse - .getAsJsonObject().get(applicationIdParam).getAsString(), apiIDList); - JsonElement subscribeAPIsResponse = callPost(urlMap.get(GatewayConstants.API_SUBSCRIBE_URL).toString(), - subscribeAPIsPayload.toString(), "Bearer ".concat(token)); - if (subscribeAPIsResponse == null) { - log.error("Error while subscribing to APIs"); - String clientId = createdDCRAppDetails.get(clientIdParam).getAsString(); - //delete service provider - callDelete(fullBackEndURL.concat("/").concat(clientId), basicAuthHeader); - //delete SP created for calling dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader); - //delete AM application - callDelete(urlMap.get(GatewayConstants.APP_CREATE_URL).toString() - .concat("/").concat(amApplicationCreateResponse.getAsJsonObject() - .get(applicationIdParam).getAsString()), GatewayConstants.BEARER_TAG.concat(token)); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - return; - } - - //delete IAM application used to invoke am rest endpoints - if (!callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(amRestAPIInvokeClientId), basicAuthHeader)) { - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - } - - } catch (IOException | OpenBankingException | URISyntaxException | ParseException e) { - log.error("Error occurred while creating application", e); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - } - } - - /** - * Method to handle response for DCR PUT requests. - * - * @param obapiResponseContext OB response context object - * @param basicAuthHeader Basic authentication header for accessing the DCR endpoint. - * @param regulatoryAPIs A map containing regulatory API names and the related authorized roles - */ - private void postProcessResponseForUpdate(OBAPIResponseContext obapiResponseContext, String basicAuthHeader, - Map> regulatoryAPIs) { - - JsonParser jsonParser = new JsonParser(); - JsonObject createdDCRAppDetails = ((JsonObject) jsonParser.parse(obapiResponseContext - .getResponsePayload())); - try { - JsonObject dcrPayload = getIAMDCRPayload(createdDCRAppDetails.get("software_id").getAsString()); - JsonElement registrationResponse = callPost(urlMap.get(GatewayConstants.IAM_DCR_URL).toString(), - dcrPayload.toString(), basicAuthHeader); - if (registrationResponse == null) { - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - //call token endpoint to retrieve a token for invoking the devportal REST apis - String clientId = registrationResponse.getAsJsonObject().get(clientIdParam).getAsString(); - String authHeaderForTokenRequest = GatewayUtils.getBasicAuthHeader(clientId, - registrationResponse.getAsJsonObject().get(clientSecret).getAsString()); - - JsonElement tokenResponse = getToken(authHeaderForTokenRequest, - urlMap.get(GatewayConstants.TOKEN_URL).toString(), clientId); - if (tokenResponse == null || tokenResponse.getAsJsonObject().get("access_token") == null) { - log.error("Error while creating tokens"); - //delete SP created to call dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - String token = tokenResponse.getAsJsonObject().get("access_token").getAsString(); - - String applicationName = getApplicationName(obapiResponseContext.getResponsePayload(), - GatewayDataHolder.getInstance().getOpenBankingConfigurationService().getConfigurations()); - if (StringUtils.isEmpty(applicationName)) { - log.error("Error while retrieving application name during update"); - //delete SP created to call dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - //call application get endpoint to retrieve the application id - JsonElement applicationSearchResponse = - callGet(urlMap.get(GatewayConstants.APP_CREATE_URL).toString(), - GatewayConstants.BEARER_TAG.concat(token), "query", applicationName); - if (applicationSearchResponse == null) { - log.error("Error while searching for created application during update"); - //delete SP created to call dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - String applicationId = applicationSearchResponse.getAsJsonObject().get("list").getAsJsonArray().get(0) - .getAsJsonObject().get(applicationIdParam).getAsString(); - - //get list of subscribed APIs - JsonElement subscribedAPIsResponse = callGet(urlMap.get(GatewayConstants.API_GET_SUBSCRIBED).toString(), - GatewayConstants.BEARER_TAG.concat(token), "applicationId", applicationId); - if (subscribedAPIsResponse == null) { - log.error("Error while retrieving subscribed APIs"); - //delete SP created to call dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - List subscribedAPIIdList = new ArrayList<>(); - for (JsonElement subscribedAPI : subscribedAPIsResponse.getAsJsonObject().get("list") - .getAsJsonArray()) { - String apiId = subscribedAPI.getAsJsonObject().get("apiId").getAsString(); - subscribedAPIIdList.add(apiId); - } - - //get software statement from dcr app details - String softwareStatement = createdDCRAppDetails.has(OpenBankingConstants.SOFTWARE_STATEMENT) ? - createdDCRAppDetails.get(OpenBankingConstants.SOFTWARE_STATEMENT).getAsString() : null; - if (StringUtils.isNotEmpty(softwareStatement)) { - final JsonArray subscribedAPIs = subscribedAPIsResponse.getAsJsonObject() - .get("list").getAsJsonArray(); - //check whether the ssa still contains the roles related to the subscribed APIs and unsubscribe if not - Optional.of(getRolesFromSSA(softwareStatement)) - .map(ssaRoles -> getUnAuthorizedAPIs(subscribedAPIs, regulatoryAPIs, ssaRoles)) - .flatMap(unAuthorizedApis -> unAuthorizedApis.stream() - .map(unAuthorizedApi -> String.format("%s/%s", - urlMap.get(GatewayConstants.API_GET_SUBSCRIBED).toString(), unAuthorizedApi)) - .filter(endpoint -> isSubscriptionDeletionFailed(endpoint, GatewayConstants.BEARER_TAG - .concat(token))) - .findAny()) - .ifPresent(endpoint -> { - log.error("Error while unsubscribing from API: " + endpoint); - //delete SP created to call dev portal REST APIs - try { - callDelete(String.format("%s/%s", urlMap.get(GatewayConstants.IAM_DCR_URL).toString(), - clientId), basicAuthHeader); - } catch (OpenBankingException | IOException e) { - handleInternalServerError(obapiResponseContext, - OpenBankingErrorCodes.REGISTRATION_INTERNAL_ERROR); - } - }); - } - //subscribe to new APIs if new roles were added to the SSA - //get list of published APIs - JsonElement publishedAPIsResponse = callGet(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString(), - GatewayConstants.BEARER_TAG.concat(token), "", ""); - if (publishedAPIsResponse == null) { - log.error("Error while retrieving published APIs"); - //delete SP created to call dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - List apiIDList = new ArrayList<>(); - if (StringUtils.isEmpty(softwareStatement)) { - filterRegulatoryAPIs(regulatoryAPIs, publishedAPIsResponse.getAsJsonObject() - .get(OpenBankingConstants.API_LIST).getAsJsonArray(), Collections.emptyList()); - } else { - filterRegulatoryAPIs(regulatoryAPIs, publishedAPIsResponse.getAsJsonObject() - .get(OpenBankingConstants.API_LIST).getAsJsonArray(), getRolesFromSSA(softwareStatement)); - } - - List newApisListToSubscribe = getNewAPIsToSubscribe(apiIDList, subscribedAPIIdList); - if (!newApisListToSubscribe.isEmpty()) { - JsonArray subscribeAPIsPayload = getAPISubscriptionPayload(applicationId, newApisListToSubscribe); - JsonElement subscribeAPIsResponse = callPost(urlMap.get(GatewayConstants.API_SUBSCRIBE_URL) - .toString(), subscribeAPIsPayload.toString(), "Bearer ".concat(token)); - if (subscribeAPIsResponse == null) { - log.error("Error while subscribing to APIs"); - //delete SP created to call dev portal REST APIs - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader); - handleInternalServerError(obapiResponseContext, - OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - return; - } - } - //delete IAM application used to invoke am rest endpoints - if (!callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/") - .concat(clientId), basicAuthHeader)) { - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - } - } catch (ParseException | IOException | URISyntaxException | OpenBankingException e) { - log.error("Error occurred while creating application", e); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTRATION_UPDATE_ERROR); - } - } - - - /** - * Method to handle response for DCR DELETE requests. - * - * @param obapiResponseContext OB response context object - * @param basicAuthHeader Basic authentication header for accessing the DCR endpoint. - */ - private void postProcessResponseForDelete(OBAPIResponseContext obapiResponseContext, String basicAuthHeader) { - - try { - JsonObject dcrPayload = getIAMDCRPayload(obapiResponseContext.getApiRequestInfo().getConsumerKey()); - JsonElement registrationResponse = callPost(urlMap.get(GatewayConstants.IAM_DCR_URL).toString(), - dcrPayload.toString(), basicAuthHeader); - if (registrationResponse == null) { - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - return; - } - - //call token endpoint to retrieve a token for invoking the devportal REST apis - String clientId = registrationResponse.getAsJsonObject().get(clientIdParam).getAsString(); - String authHeaderForTokenRequest = GatewayUtils.getBasicAuthHeader(clientId, - registrationResponse.getAsJsonObject().get(clientSecret).getAsString()); - - JsonElement tokenResponse = getToken(authHeaderForTokenRequest, - urlMap.get(GatewayConstants.TOKEN_URL).toString(), clientId); - if (tokenResponse == null || tokenResponse.getAsJsonObject().get("access_token") == null) { - log.error("Error while creating tokens during delete"); - //delete IAM application used to invoke am rest endpoints - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/").concat(clientId), - basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - return; - } - String token = tokenResponse.getAsJsonObject().get("access_token").getAsString(); - - //get application id of the sent request - String cacheKey = obapiResponseContext.getApiRequestInfo().getConsumerKey() - .concat(GatewayConstants.AM_APP_NAME_CACHEKEY); - String applicationName = GatewayDataHolder.getGatewayCache() - .getFromCache(GatewayCacheKey.of(cacheKey)).toString(); - - //Adding applicationName to contextProps for use in next steps - Map contextProps = obapiResponseContext.getContextProps(); - contextProps.put("AppName", applicationName); - obapiResponseContext.setContextProps(contextProps); - - //call application get endpoint to retrieve the application id - JsonElement applicationSearchResponse = - callGet(urlMap.get(GatewayConstants.APP_CREATE_URL).toString(), - GatewayConstants.BEARER_TAG.concat(token), "query", applicationName); - if (applicationSearchResponse == null) { - log.error("Error while searching application during delete"); - //delete IAM application used to invoke am rest endpoints - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/").concat(clientId), - basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - return; - } - - String applicationId = applicationSearchResponse.getAsJsonObject().get("list").getAsJsonArray().get(0) - .getAsJsonObject().get(applicationIdParam).getAsString(); - - if (!callDelete(urlMap.get(GatewayConstants.APP_CREATE_URL).toString() - .concat("/").concat(applicationId), GatewayConstants.BEARER_TAG.concat(token))) { - log.error("Error while deleting AM application"); - //delete IAM application used to invoke am rest endpoints - callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/").concat(clientId), - basicAuthHeader); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - return; - } - - //delete IAM application used to invoke am rest endpoints - if (!callDelete(urlMap.get(GatewayConstants.IAM_DCR_URL).toString().concat("/").concat(clientId), - basicAuthHeader)) { - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - } - } catch (IOException | OpenBankingException | URISyntaxException e) { - log.error("Error occurred while deleting application", e); - handleInternalServerError(obapiResponseContext, OpenBankingErrorCodes.REGISTATION_DELETE_ERROR); - } - } - - private JsonObject getIAMDCRPayload(String uniqueId) { - - JsonObject jsonObject = new JsonObject(); - JsonElement jsonElement = new JsonArray(); - /* Concatenating the unique id (software id/client id) to the rest api invoking SP name to avoid - issues in parallel requests - */ - String restApiInvokerName = "AM_RESTAPI_INVOKER_".concat(uniqueId); - ((JsonArray) jsonElement).add("client_credentials"); - jsonObject.addProperty("client_name", restApiInvokerName); - jsonObject.add("grant_types", jsonElement); - return jsonObject; - } - - private JsonObject getAppCreatePayload(String applicationName) { - - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("name", applicationName); - jsonObject.addProperty("throttlingPolicy", "Unlimited"); - return jsonObject; - - } - - private JsonObject getKeyMapPayload(String consumerKey, String consumerSecret, String keyType, - String keyManagerName) { - - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("consumerKey", consumerKey); - jsonObject.addProperty("consumerSecret", consumerSecret); - jsonObject.addProperty("keyType", keyType); - jsonObject.addProperty("keyManager", keyManagerName); - return jsonObject; - - } - - private JsonArray getAPISubscriptionPayload(String applicationId, List apiIdList) { - - JsonArray jsonArray = new JsonArray(); - for (String apiID : apiIdList) { - JsonObject apiInfo = new JsonObject(); - apiInfo.addProperty(applicationIdParam, applicationId); - apiInfo.addProperty("apiId", apiID); - apiInfo.addProperty("throttlingPolicy", "Unlimited"); - jsonArray.add(apiInfo); - } - return jsonArray; - } - - @Generated(message = "Excluding since it requires an Http response") - private JsonElement getResponse(HttpResponse response) throws IOException { - - HttpEntity entity = response.getEntity(); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || - response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { - String responseStr = EntityUtils.toString(entity); - JsonParser parser = new JsonParser(); - return parser.parse(responseStr); - - } else { - String error = String.format("Error while invoking rest api : %s %s", - response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); - log.error(error); - return null; - } - - } - - @Generated(message = "Excluding from test coverage since it is an HTTP call") - protected JsonElement callPost(String endpoint, String payload, String authenticationHeader) - throws IOException, OpenBankingException { - - try (CloseableHttpClient httpClient = HTTPClientUtils.getHttpsClient()) { - HttpPost httpPost = new HttpPost(endpoint); - StringEntity entity = new StringEntity(payload); - httpPost.setEntity(entity); - httpPost.setHeader(GatewayConstants.ACCEPT, GatewayConstants.JSON_CONTENT_TYPE); - httpPost.setHeader(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - httpPost.setHeader(HttpHeaders.AUTHORIZATION, authenticationHeader); - CloseableHttpResponse httpResponse = httpClient.execute(httpPost); - return getResponse(httpResponse); - } - } - - @Generated(message = "Excluding from test coverage since it is an HTTP call") - protected JsonElement getToken(String authHeader, String url, String clientId) throws IOException, JSONException, - OpenBankingException { - - try (CloseableHttpClient client = HTTPClientUtils.getHttpsClient()) { - HttpPost request = new HttpPost(url); - List params = new ArrayList<>(); - params.add(new BasicNameValuePair("grant_type", "client_credentials")); - params.add(new BasicNameValuePair("scope", "apim:subscribe apim:api_key apim:app_manage " + - "apim:sub_manage openid")); - //params.add(new BasicNameValuePair("client_id", clientId)); - request.setEntity(new UrlEncodedFormEntity(params)); - request.addHeader(HTTPConstants.HEADER_AUTHORIZATION, authHeader); - HttpResponse response = client.execute(request); - if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { - log.error("Obtaining access token failed with status code: " + - response.getStatusLine().getStatusCode()); - return new JsonObject(); - } - return getResponse(response); - } - } - - /** - * Filters the regulatory APIs based on the given software roles. - * - * @param regulatoryAPIs A map containing regulatory API names and their allowed roles - * @param publishedAPIs The list of published APIs as JSON array - * @param softwareRoles The list of software roles provided in the request - * @return A list of API IDs that the application is authorized to access - */ - protected List filterRegulatoryAPIs(Map> regulatoryAPIs, JsonArray publishedAPIs, - List softwareRoles) { - - List filteredAPIs = new ArrayList<>(); - for (JsonElement publishedAPIInfo : publishedAPIs) { - String publishedAPIName = publishedAPIInfo.getAsJsonObject().get(OpenBankingConstants.API_NAME) - .getAsString(); - if (regulatoryAPIs.containsKey(publishedAPIName)) { - List allowedRolesForAPI = regulatoryAPIs.get(publishedAPIName); - // Check if no specific roles are configured for the API or if software roles contain any of the - // allowed roles - if (allowedRolesForAPI.isEmpty() || allowedRolesForAPI.stream().anyMatch(softwareRoles::contains)) { - filteredAPIs.add(publishedAPIInfo.getAsJsonObject().get(OpenBankingConstants.API_ID).getAsString()); - } - } - } - return filteredAPIs; - } - - @Generated(message = "Excluding from test coverage since it is an HTTP call") - protected JsonElement callGet(String endpoint, String authHeader, String queryParamKey, String paramValue) - throws IOException, OpenBankingException, URISyntaxException { - - try (CloseableHttpClient httpClient = HTTPClientUtils.getHttpsClient()) { - HttpGet httpGet = new HttpGet(endpoint); - List nameValuePairs = new ArrayList(); - if (StringUtils.isNotEmpty(queryParamKey)) { - nameValuePairs.add(new BasicNameValuePair(queryParamKey, paramValue)); - URI uri = new URIBuilder(httpGet.getURI()).addParameters(nameValuePairs).build(); - ((HttpRequestBase) httpGet).setURI(uri); - } - httpGet.setHeader("Accept", "application/json"); - httpGet.setHeader(HttpHeaders.AUTHORIZATION, authHeader); - CloseableHttpResponse restAPIResponse = httpClient.execute(httpGet); - return getResponse(restAPIResponse); - } - } - - private void handleInternalServerError(OBAPIResponseContext obapiResponseContext, String message) { - - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError(OpenBankingErrorCodes.SERVER_ERROR_CODE, - "Internal server error", message, OpenBankingErrorCodes.SERVER_ERROR_CODE); - ArrayList executorErrors = obapiResponseContext.getErrors(); - executorErrors.add(error); - obapiResponseContext.setError(true); - obapiResponseContext.setErrors(executorErrors); - - } - - private void handleRequestInternalServerError(OBAPIRequestContext obapiResponseContext, String message) { - - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError(OpenBankingErrorCodes.SERVER_ERROR_CODE, - "Internal server error", message, OpenBankingErrorCodes.SERVER_ERROR_CODE); - ArrayList executorErrors = obapiResponseContext.getErrors(); - executorErrors.add(error); - obapiResponseContext.setError(true); - obapiResponseContext.setErrors(executorErrors); - - } - - @Generated(message = "Excluding from test coverage since it is an HTTP call") - protected boolean callDelete(String endpoint, String authHeader) throws OpenBankingException, IOException { - - try (CloseableHttpClient httpClient = HTTPClientUtils.getHttpsClient()) { - HttpDelete httpDelete = new HttpDelete(endpoint); - httpDelete.setHeader(HttpHeaders.AUTHORIZATION, authHeader); - CloseableHttpResponse appDeletedResponse = httpClient.execute(httpDelete); - int status = appDeletedResponse.getStatusLine().getStatusCode(); - return (status == 204 || status == 200); - } - } - - /** - * Check if the deletion of subscription at a given endpoint failed. - * - * @param endpoint The URL of the endpoint where the subscription deletion is attempted - * @param authHeader The authorization header to be used in the HTTP request - * @return True if the subscription deletion fails or an exception occurs, false otherwise - */ - protected boolean isSubscriptionDeletionFailed(String endpoint, String authHeader) { - - try { - return !callDelete(endpoint, GatewayConstants.BEARER_TAG.concat(authHeader)); - } catch (OpenBankingException | IOException e) { - return true; - } - } - - private void handleBadRequestError(OBAPIRequestContext obapiRequestContext, String message) { - - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError("Bad request", - "invalid_client_metadata", message, "400"); - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - obapiRequestContext.setError(true); - obapiRequestContext.setErrors(executorErrors); - - } - - @Generated(message = "Excluding from unit tests since there is an external http call") - private void validateRequestSignature(String payload, OBAPIRequestContext obapiRequestContext) - throws ParseException, JOSEException, BadJOSEException, MalformedURLException, - OpenBankingExecutorException { - - String jwksEndpointName = GatewayDataHolder.getInstance().getOpenBankingConfigurationService() - .getConfigurations().get(OpenBankingConstants.JWKS_ENDPOINT_NAME).toString(); - //decode request jwt - JSONObject decodedSSA; - JSONObject decodedRequest = JWTUtils.decodeRequestJWT(payload, "body"); - - //Check whether decodedRequest is null - if (decodedRequest == null) { - throw new OpenBankingExecutorException("invalid_client_metadata", OpenBankingErrorCodes.BAD_REQUEST_CODE, - "Provided jwt is malformed and cannot be decoded"); - } - - //Check whether the SSA exists and decode the SSA - if (decodedRequest.containsKey(OpenBankingConstants.SOFTWARE_STATEMENT) && - decodedRequest.getAsString(OpenBankingConstants.SOFTWARE_STATEMENT) != null) { - decodedSSA = JWTUtils.decodeRequestJWT(decodedRequest - .getAsString(OpenBankingConstants.SOFTWARE_STATEMENT), "body"); - } else { - //Throwing an exception whn SSA is not found - throw new OpenBankingExecutorException("invalid_client_metadata", OpenBankingErrorCodes.BAD_REQUEST_CODE, - "Required parameter software statement cannot be null"); - } - - //validate request signature - String jwksEndpoint = decodedSSA.getAsString(jwksEndpointName); - SignedJWT signedJWT = SignedJWT.parse(payload); - String alg = signedJWT.getHeader().getAlgorithm().getName(); - JWTUtils.validateJWTSignature(payload, jwksEndpoint, alg); - obapiRequestContext.setModifiedPayload(decodedRequest.toJSONString()); - Map requestHeaders = obapiRequestContext.getMsgInfo().getHeaders(); - requestHeaders.remove("Content-Type"); - Map addedHeaders = obapiRequestContext.getAddedHeaders(); - addedHeaders.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - obapiRequestContext.setAddedHeaders(addedHeaders); - obapiRequestContext.getMsgInfo().setHeaders(requestHeaders); - } - - /** - * Extract roles from SSA. - * - * @param softwareStatement software statement extracted from request payload - * @return list of roles - * @throws ParseException - */ - public List getRolesFromSSA(String softwareStatement) throws ParseException { - - List softwareRoleList = new ArrayList<>(); - // decode software statement and get payload - JSONObject softwareStatementBody = JWTUtils.decodeRequestJWT(softwareStatement, "body"); - Object softwareRolesStr = softwareStatementBody.get(OpenBankingConstants.SOFTWARE_ROLES); - if (softwareRolesStr instanceof JSONArray) { - JSONArray softwareRoles = (JSONArray) softwareRolesStr; - for (Object role : softwareRoles) { - softwareRoleList.add(role.toString()); - } - } else if (softwareRolesStr instanceof String) { - softwareRoleList = Arrays.asList(softwareRolesStr.toString().split(" ")); - } - return softwareRoleList; - } - - protected String getApplicationName(String responsePayload, Map configurations) - throws ParseException { - - JsonParser jsonParser = new JsonParser(); - JsonObject createdDCRAppDetails = ((JsonObject) jsonParser.parse(responsePayload)); - String softwareStatement = createdDCRAppDetails.has(OpenBankingConstants.SOFTWARE_STATEMENT) ? - createdDCRAppDetails.get(OpenBankingConstants.SOFTWARE_STATEMENT).getAsString() : null; - boolean isSoftwareIdAppName = Boolean.parseBoolean(configurations - .get(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME).toString()); - String applicationNameKey = configurations.get(OpenBankingConstants.DCR_APPLICATION_NAME_KEY).toString(); - - // If a software statement is not provided, get the software id directly from created app details - if (StringUtils.isEmpty(softwareStatement)) { - if (isSoftwareIdAppName) { - return createdDCRAppDetails.get(OpenBankingConstants.SOFTWARE_ID).getAsString(); - } - } else { - JSONObject softwareStatementBody = JWTUtils.decodeRequestJWT(softwareStatement, - OpenBankingConstants.JWT_BODY); - if (isSoftwareIdAppName) { - //get software id form the software statement - return softwareStatementBody.get(OpenBankingConstants.SOFTWARE_ID).toString(); - } else if (softwareStatementBody.containsKey(applicationNameKey)) { - return softwareStatementBody.get(applicationNameKey).toString(); - } - } - return createdDCRAppDetails.get(applicationNameKey).getAsString(); - } - - protected List getUnAuthorizedAPIs(JsonArray subscribedAPIs, Map> configuredAPIs, - List allowedRoles) { - - List apisToUnsubscribe = new ArrayList<>(); - for (JsonElement apiName : subscribedAPIs) { - for (Map.Entry> entry : configuredAPIs.entrySet()) { - if (entry.getKey().equals(apiName.getAsJsonObject().get("apiInfo").getAsJsonObject().get("name") - .getAsString())) { - List allowedRolesForAPI = entry.getValue(); - boolean allowedAPI = false; - for (String allowedRole : allowedRolesForAPI) { - if (allowedRoles.contains(allowedRole)) { - allowedAPI = true; - break; - } - } - if (!allowedAPI) { - apisToUnsubscribe.add(apiName.getAsJsonObject().get("subscriptionId").getAsString()); - } - } - } - } - return apisToUnsubscribe; - } - - protected List getNewAPIsToSubscribe(List filteredAPIs, List subscribedAPIs) { - - List apisToSubscribe = new ArrayList<>(); - for (String publishedAPI : filteredAPIs) { - if (!subscribedAPIs.contains(publishedAPI)) { - apisToSubscribe.add(publishedAPI); - } - } - return apisToSubscribe; - } - - protected JsonElement createServiceProvider(String basicAuthHeader, String softwareId) - throws IOException, OpenBankingException { - - JsonObject dcrPayload = getIAMDCRPayload(softwareId); - return callPost(urlMap.get(GatewayConstants.IAM_DCR_URL).toString(), - dcrPayload.toString(), basicAuthHeader); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/exception/OpenBankingExecutorException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/exception/OpenBankingExecutorException.java deleted file mode 100644 index 9b14ddf8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/exception/OpenBankingExecutorException.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.exception; - -/** - * Open Banking executor exception class. - */ -public class OpenBankingExecutorException extends Exception { - - private String errorCode; - private String errorPayload; - - public OpenBankingExecutorException(String message, String errorCode, String errorPayload) { - - super(message); - this.errorCode = errorCode; - this.errorPayload = errorPayload; - } - - public OpenBankingExecutorException(String message, Throwable cause) { - - super(message, cause); - } - - public OpenBankingExecutorException(String message) { - super(message); - } - - public OpenBankingExecutorException(Throwable cause, String errorCode, String errorPayload) { - - super(cause); - this.errorCode = errorCode; - this.errorPayload = errorPayload; - } - - public OpenBankingExecutorException(String message, Throwable cause, String errorCode, String errorPayload) { - - super(message, cause); - this.errorCode = errorCode; - this.errorPayload = errorPayload; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - - public String getErrorPayload() { - - return errorPayload; - } - - public void setErrorPayload(String errorPayload) { - - this.errorPayload = errorPayload; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/api/resource/access/validation/APIResourceAccessValidationExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/api/resource/access/validation/APIResourceAccessValidationExecutor.java deleted file mode 100644 index b808fe96..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/api/resource/access/validation/APIResourceAccessValidationExecutor.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.api.resource.access.validation; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * API Resource Access Validation executor. - * This executor validates the grant type. - */ -public class APIResourceAccessValidationExecutor implements OpenBankingGatewayExecutor { - - private static final Log log = LogFactory.getLog(APIResourceAccessValidationExecutor.class); - - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Generated(message = "Ignoring since all cases are covered from other unit tests") - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - // Skip the executor if previous executors failed. - if (obapiRequestContext.isError()) { - return; - } - - // Get allowed security definitions - List allowedOAuthFlows = GatewayUtils.getAllowedOAuthFlows(obapiRequestContext); - - // Return if the end point is not secured - if (allowedOAuthFlows.isEmpty()) { - log.debug("Requested resource does not require authentication."); - return; - } - - // Retrieve grant types of the access token - Map transportHeaders = obapiRequestContext.getMsgInfo().getHeaders(); - try { - String bearerTokenPayload = GatewayUtils.getBearerTokenPayload(transportHeaders); - String tokenType = GatewayUtils.getTokenType(bearerTokenPayload); - - //validation - GatewayUtils.validateGrantType(tokenType, allowedOAuthFlows); - } catch (OpenBankingExecutorException e) { - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError(e.getErrorCode(), e.getMessage(), - e.getErrorPayload(), OpenBankingErrorCodes.UNAUTHORIZED_CODE); - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - obapiRequestContext.setError(true); - obapiRequestContext.setErrors(executorErrors); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/common/reporting/data/executor/CommonReportingDataExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/common/reporting/data/executor/CommonReportingDataExecutor.java deleted file mode 100644 index 67dd3263..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/common/reporting/data/executor/CommonReportingDataExecutor.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.common.reporting.data.executor; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.time.Instant; -import java.util.Map; - -/** - * Common Reporting Data Executor. - */ -public class CommonReportingDataExecutor implements OpenBankingGatewayExecutor { - - private static final Log log = LogFactory.getLog(CommonReportingDataExecutor.class); - - private static final String CLIENT_USER_AGENT = "User-Agent"; - private static final String USER_AGENT = "userAgent"; - private static final String TIMESTAMP = "timestamp"; - private static final String ELECTED_RESOURCE = "electedResource"; - private static final String RESPONSE_PAYLOAD_SIZE = "responsePayloadSize"; - private static final String HTTP_METHOD = "httpMethod"; - private static final String STATUS_CODE = "statusCode"; - private static final String CONSENT_ID = "consentId"; - private static final String CONSUMER_ID = "consumerId"; - private static final String API_NAME = "apiName"; - private static final String API_SPEC_VERSION = "apiSpecVersion"; - private static final String CLIENT_ID = "clientId"; - private static final String MESSAGE_ID = "messageId"; - private static final String NAME_TAG = "_name"; - - /** - * Method to handle pre request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - Map analyticsData = obapiRequestContext.getAnalyticsData(); - - String httpMethod = obapiRequestContext.getMsgInfo().getHttpMethod(); - analyticsData.put(HTTP_METHOD, httpMethod); - - Map headers = obapiRequestContext.getMsgInfo().getHeaders(); - - String userAgent = headers.get(CLIENT_USER_AGENT); - analyticsData.put(USER_AGENT, userAgent); - - String electedResource = obapiRequestContext.getMsgInfo().getElectedResource(); - analyticsData.put(ELECTED_RESOURCE, electedResource); - - String apiName = getApiName(obapiRequestContext); - - analyticsData.put(API_NAME, apiName); - - String apiSpecVersion = obapiRequestContext.getApiRequestInfo().getVersion(); - analyticsData.put(API_SPEC_VERSION, apiSpecVersion); - - analyticsData.put(MESSAGE_ID, obapiRequestContext.getMsgInfo().getMessageId()); - analyticsData.put(TIMESTAMP, Instant.now().getEpochSecond()); - - // Add analytics data to a map - obapiRequestContext.setAnalyticsData(analyticsData); - } - - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - Map analyticsData = obapiRequestContext.getAnalyticsData(); - String consentId = obapiRequestContext.getConsentId(); - analyticsData.put(CONSENT_ID, consentId); - analyticsData.put(CLIENT_ID, obapiRequestContext.getApiRequestInfo().getConsumerKey()); - analyticsData.put(CONSUMER_ID, obapiRequestContext.getApiRequestInfo().getUsername()); - - // Add analytics data to a map - obapiRequestContext.setAnalyticsData(analyticsData); - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - Map analyticsData = obapiResponseContext.getAnalyticsData(); - - analyticsData.put(STATUS_CODE, obapiResponseContext.getStatusCode()); - - String payload = obapiResponseContext.getModifiedPayload() != null ? - obapiResponseContext.getModifiedPayload() : obapiResponseContext.getResponsePayload(); - long responsePayloadSize = payload != null ? payload.length() : 0; - analyticsData.put(RESPONSE_PAYLOAD_SIZE, responsePayloadSize); - - // Add data to analytics data map - obapiResponseContext.setAnalyticsData(analyticsData); - - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to get api name from cache. - * @param obapiRequestContext ob api request context - * @return api name - */ - @Generated(message = "Ignoring tests since this method is used to get name from cache") - protected String getApiName(OBAPIRequestContext obapiRequestContext) { - - String apiName; - String apiNameCacheKey = obapiRequestContext.getApiRequestInfo().getApiId() + NAME_TAG; - Object cacheObject = GatewayDataHolder.getGatewayCache().getFromCache(GatewayCacheKey.of(apiNameCacheKey)); - - if (cacheObject == null) { - apiName = obapiRequestContext.getOpenAPI().getInfo().getTitle(); - GatewayDataHolder.getGatewayCache().addToCache(GatewayCacheKey.of(apiNameCacheKey), apiName); - } else { - apiName = (String) cacheObject; - } - return apiName; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/consent/ConsentEnforcementExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/consent/ConsentEnforcementExecutor.java deleted file mode 100644 index 8ccb1415..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/consent/ConsentEnforcementExecutor.java +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.consent; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.json.JSONObject; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** - * Consent Enforcement executor. - */ -public class ConsentEnforcementExecutor implements OpenBankingGatewayExecutor { - - protected static final String ERROR_TITLE = "Consent Enforcement Error"; - protected static final String HEADERS_TAG = "headers"; - protected static final String BODY_TAG = "body"; - protected static final String CONTEXT_TAG = "context"; - protected static final String RESOURCE_TAG = "resource"; - protected static final String ELECTED_RESOURCE_TAG = "electedResource"; - protected static final String HTTP_METHOD = "httpMethod"; - protected static final String CONSENT_ID_TAG = "consentId"; - protected static final String USER_ID_TAG = "userId"; - protected static final String CLIENT_ID_TAG = "clientId"; - protected static final String RESOURCE_PARAMS = "resourceParams"; - private static final Log log = LogFactory.getLog(ConsentEnforcementExecutor.class); - private static final GatewayDataHolder dataHolder = GatewayDataHolder.getInstance(); - private static final String INFO_HEADER_TAG = "Account-Request-Information"; - private static final String IS_VALID = "isValid"; - private static final String ERROR_CODE = "errorCode"; - private static final String ERROR_MESSAGE = "errorMessage"; - private static final String HTTP_CODE = "httpCode"; - private static final String MODIFIED_PAYLOAD = "modifiedPayload"; - private static final String CONSENT_INFO = "consentInformation"; - private static volatile String consentValidationEndpoint; - private static volatile Key key; - - private static String getValidationEndpoint() { - - if (consentValidationEndpoint == null) { - synchronized (ConsentEnforcementExecutor.class) { - if (consentValidationEndpoint == null) { - consentValidationEndpoint = dataHolder - .getOpenBankingConfigurationService().getConfigurations() - .get(GatewayConstants.CONSENT_VALIDATION_ENDPOINT_TAG).toString(); - } - } - } - return consentValidationEndpoint; - - } - - /** - * Method to obtain signing key. - * - * @return Key as an Object. - */ - @SuppressFBWarnings("PATH_TRAVERSAL_IN") - // Suppressed content - dataHolder.getKeyStoreLocation() - // Suppression reason - False Positive : Keystore location is obtained from deployment.toml. So it can be marked - // as a trusted filepath - // Suppressed warning count - 1 - protected static Key getJWTSigningKey() { - - if (key == null) { - synchronized (ConsentEnforcementExecutor.class) { - if (key == null) { - try (FileInputStream is = new FileInputStream(dataHolder.getKeyStoreLocation())) { - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(is, dataHolder.getKeyStorePassword()); - key = keystore.getKey(dataHolder.getKeyAlias(), dataHolder.getKeyPassword().toCharArray()); - } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException - | UnrecoverableKeyException e) { - log.error("Error occurred while retrieving private key from keystore ", e); - } - } - } - } - return key; - } - - /** - * Method to handle request. - * - * @param obapiRequestContext OB request context object - */ - @Generated(message = "Unit testable components are covered") - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } - - /** - * Method to handle response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - protected String generateJWT(String payload) { - - return Jwts.builder() - .setPayload(payload) - .signWith(SignatureAlgorithm.RS512, getJWTSigningKey()) - .compact(); - } - - /** - * Method to invoke consent validation service when the JWT payload is provided. - * - * @param enforcementJWTPayload JWT Payload - * @return Response as a String - * @throws IOException When failed to invoke the validation endpoint or failed to parse the response. - */ - @Generated(message = "Ignoring from unit tests since this method require calling external component to function") - private String invokeConsentValidationService(String enforcementJWTPayload) throws IOException, - OpenBankingException { - - HttpPost httpPost = new HttpPost(getValidationEndpoint()); - StringEntity params; - params = new StringEntity(enforcementJWTPayload); - httpPost.setEntity(params); - httpPost.setHeader(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JWT_CONTENT_TYPE); - String userName = GatewayUtils.getAPIMgtConfig(GatewayConstants.API_KEY_VALIDATOR_USERNAME); - String password = GatewayUtils.getAPIMgtConfig(GatewayConstants.API_KEY_VALIDATOR_PASSWORD); - httpPost.setHeader(GatewayConstants.AUTH_HEADER, GatewayUtils.getBasicAuthHeader(userName, password)); - HttpResponse response = GatewayDataHolder.getHttpClient().execute(httpPost); - InputStream in = response.getEntity().getContent(); - return IOUtils.toString(in, String.valueOf(StandardCharsets.UTF_8)); - } - - /** - * Method to handle errors. - * - * @param obapiRequestContext API Context - * @param errorCode Error Code - * @param errorMessage Error Message - * @param httpCode HTTP status code ( in 4XX range) - */ - protected void handleError(OBAPIRequestContext obapiRequestContext, String errorCode, String errorMessage, - String httpCode) { - - obapiRequestContext.setError(true); - ArrayList errors = obapiRequestContext.getErrors(); - errors.add(new OpenBankingExecutorError(errorCode, ERROR_TITLE, errorMessage, httpCode)); - obapiRequestContext.setErrors(errors); - obapiRequestContext.addContextProperty(GatewayConstants.ERROR_STATUS_PROP, httpCode); - } - - /** - * Method to create validation payload. - * - * @param requestHeaders Request headers of original request - * @param requestPayload Request payload of original request - * @return JSON Object with added attributes. - */ - protected JSONObject createValidationRequestPayload(Map requestHeaders, String requestPayload, - Map additionalParams) { - - JSONObject validationRequest = new JSONObject(); - JSONObject headers = new JSONObject(); - requestHeaders.forEach(headers::put); - validationRequest.put(HEADERS_TAG, headers); - /*requestContextDTO.getMsgInfo().getPayloadHandler().consumeAsString() method sets the request payload as a - null string, hence adding string null check to the validation*/ - if (requestPayload != null && !requestPayload.isEmpty() && !requestPayload.equals("null")) { - //This assumes all input payloads are in Content-Type : Application/JSON - validationRequest.put(BODY_TAG, new JSONObject(requestPayload)); - } - additionalParams.forEach(validationRequest::put); - return validationRequest; - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - // Consent ID is required for consent enforcement. If the consent ID is null, we are assume this is a - // pre-consent creation call. Therefore consent enforcement is not required. - if (obapiRequestContext.isError() || obapiRequestContext.getConsentId() == null) { - return; - } - - Map requestHeaders = obapiRequestContext.getMsgInfo().getHeaders(); - Map additionalParams = new HashMap<>(); - additionalParams.put(ELECTED_RESOURCE_TAG, obapiRequestContext.getMsgInfo().getElectedResource()); - additionalParams.put(CONSENT_ID_TAG, obapiRequestContext.getConsentId()); - additionalParams.put(USER_ID_TAG, obapiRequestContext.getApiRequestInfo().getUsername()); - additionalParams.put(CLIENT_ID_TAG, obapiRequestContext.getApiRequestInfo().getConsumerKey()); - additionalParams.put(RESOURCE_PARAMS, getResourceParamMap(obapiRequestContext)); - - JSONObject validationRequest; - if (StringUtils.isNotBlank(obapiRequestContext.getModifiedPayload())) { - validationRequest = createValidationRequestPayload(requestHeaders, - obapiRequestContext.getModifiedPayload(), additionalParams); - } else { - validationRequest = createValidationRequestPayload(requestHeaders, - obapiRequestContext.getRequestPayload(), additionalParams); - } - String enforcementJWTPayload = generateJWT(validationRequest.toString()); - JSONObject jsonResponse; - try { - String response = invokeConsentValidationService(enforcementJWTPayload); - jsonResponse = new JSONObject(response); - } catch (IOException | OpenBankingException e) { - handleError(obapiRequestContext, OpenBankingErrorCodes.CONSENT_VALIDATION_REQUEST_FAILURE, e.getMessage(), - OpenBankingErrorCodes.SERVER_ERROR_CODE); - return; - } - - boolean isValid = (boolean) jsonResponse.get(IS_VALID); - if (!isValid) { - String errorCode = jsonResponse.get(ERROR_CODE).toString(); - String errorMessage = jsonResponse.get(ERROR_MESSAGE).toString(); - String httpCode = jsonResponse.get(HTTP_CODE).toString(); - obapiRequestContext.setError(true); - handleError(obapiRequestContext, errorCode, errorMessage, httpCode); - return; - } else if (!jsonResponse.isNull(MODIFIED_PAYLOAD)) { - Object modifiedPayloadObj = jsonResponse.get(MODIFIED_PAYLOAD); - if (modifiedPayloadObj != null) { - obapiRequestContext.setModifiedPayload(modifiedPayloadObj.toString()); - } - } else if (!jsonResponse.isNull(CONSENT_INFO)) { - Object consentInformationObj = jsonResponse.get(CONSENT_INFO); - if (consentInformationObj != null) { - requestHeaders.put(INFO_HEADER_TAG, consentInformationObj.toString()); - obapiRequestContext.setAddedHeaders(requestHeaders); - } - } - } - - /** - * Method to construct resource parameter map to invoke the validation service. - * - * @param obapiRequestContext - * @return A Map containing resource path(ex: /aisp/accounts/{AccountId}?queryParam=urlEncodedQueryParamValue), - * http method and context(ex: /open-banking/v3.1/aisp) - */ - private Map getResourceParamMap(OBAPIRequestContext obapiRequestContext) { - - Map resourceMap = new HashMap(); - resourceMap.put(RESOURCE_TAG, obapiRequestContext.getMsgInfo().getResource()); - resourceMap.put(HTTP_METHOD, obapiRequestContext.getMsgInfo().getHttpMethod()); - resourceMap.put(CONTEXT_TAG, obapiRequestContext.getApiRequestInfo().getContext()); - - return resourceMap; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/error/handler/OBDefaultErrorHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/error/handler/OBDefaultErrorHandler.java deleted file mode 100644 index 5ffd258c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/error/handler/OBDefaultErrorHandler.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.error.handler; - -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import org.apache.http.HttpStatus; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -/** - * Default Executor to handle gateway errors. - */ -public class OBDefaultErrorHandler implements OpenBankingGatewayExecutor { - - private static final String ERRORS_TAG = "errors"; - private static final String STATUS_CODE = "statusCode"; - private static final String RESPONSE_PAYLOAD_SIZE = "responsePayloadSize"; - - /** - * Method to handle pre request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - handleRequestError(obapiRequestContext); - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - handleRequestError(obapiRequestContext); - } - - /** - * Method to handle pre response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - handleResponseError(obapiResponseContext); - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - handleResponseError(obapiResponseContext); - } - - private void handleRequestError(OBAPIRequestContext obapiRequestContext) { - - if (!obapiRequestContext.isError()) { - return; - } - JSONObject payload = new JSONObject(); - ArrayList errors = obapiRequestContext.getErrors(); - JSONArray errorList = getErrorJSON(errors); - HashSet statusCodes = new HashSet<>(); - - for (OpenBankingExecutorError error : errors) { - statusCodes.add(error.getHttpStatusCode()); - } - - payload.put(ERRORS_TAG, errorList); - if (errorList.length() != 0) { - obapiRequestContext.setModifiedPayload(payload.toString()); - Map addedHeaders = obapiRequestContext.getAddedHeaders(); - addedHeaders.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - obapiRequestContext.setAddedHeaders(addedHeaders); - } - int statusCode; - if (obapiRequestContext.getContextProps().containsKey(GatewayConstants.ERROR_STATUS_PROP)) { - statusCode = Integer.parseInt(obapiRequestContext.getContextProperty(GatewayConstants.ERROR_STATUS_PROP)); - } else if (isAnyClientErrors(statusCodes)) { - statusCode = HttpStatus.SC_BAD_REQUEST; - } else { - statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; - } - obapiRequestContext.addContextProperty(GatewayConstants.ERROR_STATUS_PROP, - String.valueOf(statusCode)); - - // Add error data to analytics map - Map analyticsData = obapiRequestContext.getAnalyticsData(); - analyticsData.put(STATUS_CODE, statusCode); - analyticsData.put(RESPONSE_PAYLOAD_SIZE, (long) payload.toString().length()); - obapiRequestContext.setAnalyticsData(analyticsData); - } - - private void handleResponseError(OBAPIResponseContext obapiResponseContext) { - - if (!obapiResponseContext.isError()) { - return; - } - JSONObject payload = new JSONObject(); - ArrayList errors = obapiResponseContext.getErrors(); - JSONArray errorList = getErrorJSON(errors); - HashSet statusCodes = new HashSet<>(); - - for (OpenBankingExecutorError error : errors) { - statusCodes.add(error.getHttpStatusCode()); - } - - payload.put(ERRORS_TAG, errorList); - obapiResponseContext.setModifiedPayload(payload.toString()); - Map addedHeaders = obapiResponseContext.getAddedHeaders(); - addedHeaders.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - obapiResponseContext.setAddedHeaders(addedHeaders); - int statusCode; - if (obapiResponseContext.getContextProps().containsKey(GatewayConstants.ERROR_STATUS_PROP)) { - statusCode = Integer.parseInt(obapiResponseContext.getContextProperty(GatewayConstants.ERROR_STATUS_PROP)); - } else if (isAnyClientErrors(statusCodes)) { - statusCode = HttpStatus.SC_BAD_REQUEST; - } else { - statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; - } - obapiResponseContext.addContextProperty(GatewayConstants.ERROR_STATUS_PROP, - String.valueOf(statusCode)); - - // Add error data to analytics map - Map analyticsData = obapiResponseContext.getAnalyticsData(); - analyticsData.put(STATUS_CODE, statusCode); - analyticsData.put(RESPONSE_PAYLOAD_SIZE, (long) payload.toString().length()); - obapiResponseContext.setAnalyticsData(analyticsData); - } - - private JSONArray getErrorJSON(List errors) { - - JSONArray errorList = new JSONArray(); - for (OpenBankingExecutorError error : errors) { - JSONObject errorObj = new JSONObject(); - errorObj.put("Code", error.getCode()); - errorObj.put("Title", error.getTitle()); - errorObj.put("Message", error.getMessage()); - Map links = error.getLinks(); - if (links != null && links.size() > 0) { - JSONObject linksObj = new JSONObject(); - links.forEach(linksObj::put); - errorObj.put("Links", linksObj); - } - errorList.put(errorObj); - } - return errorList; - } - - private boolean isAnyClientErrors(HashSet statusCodes) { - - for (String statusCode : statusCodes) { - if (statusCode.startsWith("4")) { - return true; - } - } - return false; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/CertRevocationValidationExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/CertRevocationValidationExecutor.java deleted file mode 100644 index f6ba7956..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/CertRevocationValidationExecutor.java +++ /dev/null @@ -1,260 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.mtls.cert.validation.executor; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.cache.CertificateRevocationCache; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.executor.service.CertValidationService; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.List; -import java.util.Optional; - -/** - * This executor will be used to validate the certificate revocation (CRL and OCSP validation) of the client - * certificate during a mutual tls session. The immediate issuer of the client certificate must be present in the - * truststore to continue with the validation. - */ -public class CertRevocationValidationExecutor implements OpenBankingGatewayExecutor { - - private static final Log LOG = LogFactory.getLog(CertRevocationValidationExecutor.class); - - @Generated(message = "Ignoring since all cases are covered from other unit tests") - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - LOG.info("Starting certificate revocation validation process"); - - // Skip the executor if previous executors failed. - if (obapiRequestContext.isError()) { - return; - } - - try { - Certificate[] clientCerts = obapiRequestContext.getClientCertsLatest(); - // enforcement executor validates the certificate presence - if (clientCerts != null && clientCerts.length > 0) { - Optional transportCert = - CertificateValidationUtils.convertCertToX509Cert(clientCerts[0]); - - if (!transportCert.isPresent()) { - LOG.error("Invalid mutual TLS request. Client certificate is invalid"); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.INVALID_MTLS_CERT_CODE, - "Invalid mutual TLS request. Client certificate is invalid", - "", OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } else { - X509Certificate transportCertificate = transportCert.get(); - if (CertificateUtils.isExpired(transportCertificate)) { - LOG.error("Certificate with the serial number " + - transportCertificate.getSerialNumber() + " issued by the CA " + - transportCertificate.getIssuerDN().toString() + " is expired"); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.EXPIRED_MTLS_CERT_CODE, - "Invalid mutual TLS request. Client certificate is expired", - "Certificate with the serial number " + - transportCertificate.getSerialNumber() + " issued by the CA " + - transportCertificate.getIssuerDN().toString() + " is expired", - OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } else { - LOG.debug("Client certificate expiry validation completed successfully"); - if (isCertRevoked(transportCertificate)) { - LOG.error("Invalid mutual TLS request. Client certificate is revoked"); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.REVOKED_MTLS_CERT_CODE, - "Invalid mutual TLS request. Client certificate is revoked", - "", OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } else { - LOG.debug("Certificate revocation validation success"); - } - } - } - } - } catch (CertificateValidationException e) { - LOG.error("Unable to validate the client certificate, caused by ", e); - - //catch errors and set to context - CertificateValidationUtils.handleExecutorErrors(e, obapiRequestContext); - } catch (CertificateEncodingException e) { - LOG.error("Unable to generate the client certificate thumbprint, caused by ", e); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.INVALID_MTLS_CERT_CODE, - "Unable to generate the client certificate thumbprint", - "", OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - //catch errors and set to context - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } catch (CertificateException e) { - String errorMsg = "Error occurred while converting the client certificate to X509Certificate "; - LOG.error(errorMsg, e); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.INVALID_MTLS_CERT_CODE, errorMsg, - e.getMessage(), OpenBankingErrorCodes.UNAUTHORIZED_CODE); - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - // Do not need to handle the response - } - - /** - * Checks the certificate validity of a given certificate. For this validation, the immediate issuer - * of the peer certificate must be present in the trust store. - * JSONObject jsonObject; - * - * @param peerCertificate peer certificate - * @return validity of the certificate - * @throws CertificateValidationException when an error occurs while validating the certificate - */ - private boolean isCertRevoked(X509Certificate peerCertificate) - throws CertificateValidationException, CertificateEncodingException { - - // Initializing certificate cache and cache key - CertificateRevocationCache certificateRevocationCache = CertificateRevocationCache.getInstance(); - // Generating the certificate thumbprint to use as cache key - String certificateValidationCacheKeyStr = DigestUtils.sha256Hex(peerCertificate.getEncoded()); - GatewayCacheKey certificateValidationCacheKey = - GatewayCacheKey.of(certificateValidationCacheKeyStr); - - // Executing certificate revocation process or retrieve last status from cache - if (certificateRevocationCache.getFromCache(certificateValidationCacheKey) != null) { - // previous result is present in cache, return result - return !certificateRevocationCache.getFromCache(certificateValidationCacheKey); - } else { - final boolean result = isCertRevocationSuccess(peerCertificate); - if (result) { - // Adding result to cache - certificateRevocationCache.addToCache(certificateValidationCacheKey, true); - return false; - } - } - return true; - } - - private boolean isCertRevocationSuccess(X509Certificate peerCertificate) { - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = TPPCertValidatorDataHolder.getInstance(); - - Integer certificateRevocationValidationRetryCount = - tppCertValidatorDataHolder.getCertificateRevocationValidationRetryCount(); - - int connectTimeout = tppCertValidatorDataHolder.getConnectTimeout(); - int connectionRequestTimeout = tppCertValidatorDataHolder.getConnectionRequestTimeout(); - int socketTimeout = tppCertValidatorDataHolder.getSocketTimeout(); - - boolean isValid; - // Check certificate revocation status. - if (tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()) { - LOG.debug("Client certificate revocation validation is enabled"); - - // Skip certificate revocation validation if the certificate is self-signed. - if (peerCertificate.getSubjectDN().getName().equals(peerCertificate.getIssuerDN().getName())) { - if (LOG.isDebugEnabled()) { - LOG.debug("Client certificate is self signed. Hence, excluding the certificate revocation" + - " validation"); - } - return true; - } - - /* - * Skip certificate revocation validation if the certificate issuer is listed to exclude from - * revocation validation in open-banking.xml under - * CertificateManagement.RevocationValidationExcludedIssuers configuration. - * - * This option can be used to skip certificate revocation validation for certificates which have been - * issued by a trusted locally generated CA. - */ - List revocationValidationExcludedIssuers = - tppCertValidatorDataHolder.getCertificateRevocationValidationExcludedIssuers(); - if (revocationValidationExcludedIssuers.contains(peerCertificate.getIssuerDN().getName())) { - if (LOG.isDebugEnabled()) { - LOG.debug("The issuer of the client certificate has been configured to exclude from " + - "certificate revocation validation. Hence, excluding the certificate " + - "revocation validation"); - } - return true; - } - - // Get issuer certificate from the truststore to continue with the certificate validation. - X509Certificate issuerCertificate; - try { - issuerCertificate = CertificateValidationUtils - .getIssuerCertificateFromTruststore(peerCertificate); - } catch (CertificateValidationException e) { - LOG.error("Issuer certificate retrieving failed for client certificate with" + - " serial number " + peerCertificate.getSerialNumber() + " issued by the CA " + - peerCertificate.getIssuerDN().toString(), e); - return false; - } - - isValid = CertValidationService.getInstance().verify(peerCertificate, issuerCertificate, - certificateRevocationValidationRetryCount, connectTimeout, connectionRequestTimeout, socketTimeout); - } else { - isValid = true; - } - - LOG.debug("Stored certificate validation status in cache"); - - return isValid; - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/MTLSEnforcementExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/MTLSEnforcementExecutor.java deleted file mode 100644 index fa5d0efa..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/MTLSEnforcementExecutor.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.mtls.cert.validation.executor; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Optional; - -/** - * Mutual TLS Enforcement Executor - * Enforces whether the Request is sent with MTLS cert as a header. - */ -public class MTLSEnforcementExecutor implements OpenBankingGatewayExecutor { - - private static final Log LOG = LogFactory.getLog(MTLSEnforcementExecutor.class); - - @Generated(message = "Ignoring since all cases are covered from other unit tests") - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - LOG.info("Starting mutual TLS enforcement process"); - - // Skip the executor if previous executors failed. - if (obapiRequestContext.isError()) { - return; - } - - Certificate[] clientCerts = obapiRequestContext.getClientCertsLatest(); - if (clientCerts != null && clientCerts.length > 0) { - Optional transportCert = Optional.empty(); - try { - transportCert = CertificateValidationUtils.convertCertToX509Cert(clientCerts[0]); - } catch (CertificateException e) { - String errorMsg = "Error occurred while converting the client certificate to X509Certificate "; - LOG.error(errorMsg, e); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.INVALID_MTLS_CERT_CODE, errorMsg, - e.getMessage(), OpenBankingErrorCodes.UNAUTHORIZED_CODE); - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } - - if (transportCert.isPresent()) { - LOG.debug("Mutual TLS enforcement success"); - } else { - LOG.error(GatewayConstants.CLIENT_CERTIFICATE_INVALID); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.INVALID_MTLS_CERT_CODE, GatewayConstants.INVALID_CLIENT, - GatewayConstants.CLIENT_CERTIFICATE_INVALID, OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } - } else { - LOG.error(GatewayConstants.CLIENT_CERTIFICATE_MISSING); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.MISSING_MTLS_CERT_CODE, GatewayConstants.INVALID_CLIENT, - GatewayConstants.CLIENT_CERTIFICATE_MISSING, OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } - - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - // Do not need to handle the response - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/selfcare/portal/UserPermissionValidationExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/selfcare/portal/UserPermissionValidationExecutor.java deleted file mode 100644 index 1336f90f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/selfcare/portal/UserPermissionValidationExecutor.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.selfcare.portal; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * UserPermissionValidationExecutor. - *

- * Validates access token scopes against users - */ -public class UserPermissionValidationExecutor implements OpenBankingGatewayExecutor { - - private static final Log LOG = LogFactory.getLog(UserPermissionValidationExecutor.class); - - @Generated(message = "Ignoring since all cases are covered from other unit tests") - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - try { - // Skip the executor if previous executors failed. - if (obapiRequestContext.isError()) { - return; - } - - String authToken = obapiRequestContext.getMsgInfo().getHeaders().get(HttpHeaders.AUTHORIZATION); - JSONObject tokenBody = JWTUtils.decodeRequestJWT(authToken.replace("Bearer ", ""), "body"); - String tokenScopes = tokenBody.getAsString("scope"); - - if (!isCustomerCareOfficer(tokenScopes)) { - // user is not a customer care officer - Optional optUserId = getUserIdsFromQueryParams(obapiRequestContext.getMsgInfo().getResource()); - String tokenSubject = GatewayUtils.getUserNameWithTenantDomain(tokenBody.getAsString("sub")); - if (!optUserId.isPresent() || !isUserIdMatchesTokenSub(optUserId.get(), tokenSubject)) { - // token subject and user id do not match, invalid request - final String errorMsg = "Invalid self care portal request received. " + - "UserId and token subject do not match."; - LOG.error(errorMsg + " userIDs: " + optUserId.orElse(" ") + " sub: " + tokenSubject); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.SCP_USER_VALIDATION_FAILED_CODE, "Unauthorized Request", errorMsg, - OpenBankingErrorCodes.UNAUTHORIZED_CODE); - - obapiRequestContext.setError(true); - - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - obapiRequestContext.setErrors(executorErrors); - - Map contextProps = new HashMap<>(); - contextProps.put(GatewayConstants.ERROR_STATUS_PROP, OpenBankingErrorCodes.UNAUTHORIZED_CODE); - obapiRequestContext.setContextProps(contextProps); - } - } - } catch (ParseException e) { - final String errorMsg = "Error occurred while validating self care portal user permissions"; - - LOG.error(errorMsg + ". Caused by, ", e); - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.SCP_USER_VALIDATION_FAILED_CODE, e.getMessage(), errorMsg, - OpenBankingErrorCodes.BAD_REQUEST_CODE); - - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - - obapiRequestContext.setError(true); - obapiRequestContext.setErrors(executorErrors); - } - - } - - @Generated(message = "Ignoring since empty") - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - // do not need to handle - } - - @Generated(message = "Ignoring since empty") - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - // do not need to handle - } - - @Generated(message = "Ignoring since empty") - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - // do not need to handle - } - - /** - * Method to extract userID from the request URL. - * - * @param url requested URL - * @return Optional String: if userID found return userID, else return empty - */ - protected Optional getUserIdsFromQueryParams(String url) { - if (StringUtils.isNotEmpty(url) && url.contains("?")) { - final String queryParams = url.split("\\?")[1]; - final String[] queryParamPairs = queryParams.split("&"); - - for (String pair : queryParamPairs) { - if (pair.contains("userIDs") || pair.contains("userID")) { - final String[] userIds = pair.split("="); - if (userIds.length > 1) { // to prevent indexOutOfBoundException - return Optional.of(GatewayUtils.getUserNameWithTenantDomain(userIds[1])); - } - } - } - } - return Optional.empty(); - } - - /** - * Method to match customer care officer scopes. - * - * @param scopes scopes received from access token - * @return if customer care officer scope found return true else false - */ - protected boolean isCustomerCareOfficer(String scopes) { - if (StringUtils.isNotEmpty(scopes)) { - return scopes.contains(GatewayConstants.CUSTOMER_CARE_OFFICER_SCOPE); - } - return false; - } - - /** - * Method to match user id and token subject. - * - * @param userId received from query parameter - * @param tokenSub received from access token body - * @return if user id matches with token subject return true else false - */ - protected boolean isUserIdMatchesTokenSub(String userId, String tokenSub) { - if (StringUtils.isNotEmpty(tokenSub)) { - return tokenSub.equalsIgnoreCase(userId); - } - return false; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/APITPPValidationExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/APITPPValidationExecutor.java deleted file mode 100644 index af4b24e9..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/APITPPValidationExecutor.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.tpp.validation.executor; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.TPPValidationException; -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.executor.service.CertValidationService; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.security.SecurityRequirement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * TPP validation handler used to validate the TPP status using external validation - * services for regular API requests. - */ -public class APITPPValidationExecutor implements OpenBankingGatewayExecutor { - - private static final String GET = "GET"; - private static final String POST = "POST"; - private static final String PUT = "PUT"; - private static final String PATCH = "PATCH"; - private static final String DELETE = "DELETE"; - private static final Log log = LogFactory.getLog(APITPPValidationExecutor.class); - - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - // Do not need to handle the response - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Generated(message = "Ignoring since all cases are covered from other unit tests") - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - // Skip the executor if previous executors failed. - if (obapiRequestContext.isError()) { - return; - } - - try { - Certificate[] clientCerts = obapiRequestContext.getClientCertsLatest(); - if (clientCerts != null && clientCerts.length > 0) { - Optional transportCert = - CertificateValidationUtils.convertCertToX509Cert(clientCerts[0]); - - // Only Do Validation if Mutual TLS is used. - if (transportCert.isPresent()) { - - // extracting scopes from api swagger - final PathItem electedPath = obapiRequestContext.getOpenAPI().getPaths() - .get(obapiRequestContext.getMsgInfo().getElectedResource()); - final String httpMethod = obapiRequestContext.getMsgInfo().getHttpMethod(); - - final Set scopes = extractScopesFromSwaggerAPI(electedPath, httpMethod); - - // retrieving allowed scopes from open-banking.xml - final Map> allowedScopes = GatewayDataHolder.getInstance() - .getOpenBankingConfigurationService().getAllowedScopes(); - - List requiredPSD2Roles = getRolesFromScopes(allowedScopes, scopes); - - if (requiredPSD2Roles.isEmpty()) { - throw new TPPValidationException("No roles found associated with the request. Hence, cannot " + - "continue with TPP validation"); - } - - if (CertValidationService.getInstance().validateTppRoles(transportCert.get(), requiredPSD2Roles)) { - log.debug("TPP validation service returned a success response"); - } else { - log.error("TPP validation service returned invalid TPP status"); - throw new TPPValidationException("TPP validation service returned invalid TPP status"); - } - } // cert validation executor validates the certificate validity - } // enforcement executor validates the certificate presence - } catch (TPPValidationException | CertificateValidationException e) { - final String errorMsg = "Error occurred while validating the TPP status "; - log.error(errorMsg, e); - - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.TPP_VALIDATION_FAILED_CODE, - errorMsg, e.getMessage(), OpenBankingErrorCodes.FORBIDDEN_CODE); - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } catch (CertificateException e) { - String errorMsg = "Error occurred while converting the client certificate to X509Certificate "; - log.error(errorMsg, e); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.TPP_VALIDATION_FAILED_CODE, errorMsg, - e.getMessage(), OpenBankingErrorCodes.FORBIDDEN_CODE); - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } - } - - private List getRolesFromScopes(Map> allowedScopes, Set scopes) { - List requiredPSD2Roles = new ArrayList<>(); - - Set distinctRoles = new HashSet<>(); - - for (String scope : scopes) { - for (Map.Entry> allowedScopeEntry : allowedScopes.entrySet()) { - if (scope.equalsIgnoreCase(allowedScopeEntry.getKey())) { - distinctRoles.addAll(allowedScopeEntry.getValue()); - } - } - - } - - for (String distinctRole : distinctRoles) { - requiredPSD2Roles.add(PSD2RoleEnum.fromValue(distinctRole)); - } - - return requiredPSD2Roles; - } - - private Set extractScopesFromSwaggerAPI(PathItem electedPath, String httpMethod) { - - List securityRequirements = null; - Set scopes = new HashSet<>(); - - if (GET.equalsIgnoreCase(httpMethod)) { - securityRequirements = electedPath.getGet().getSecurity(); - } else if (POST.equalsIgnoreCase(httpMethod)) { - securityRequirements = electedPath.getPost().getSecurity(); - } else if (PUT.equalsIgnoreCase(httpMethod)) { - securityRequirements = electedPath.getPut().getSecurity(); - } else if (PATCH.equalsIgnoreCase(httpMethod)) { - securityRequirements = electedPath.getPatch().getSecurity(); - } else if (DELETE.equalsIgnoreCase(httpMethod)) { - securityRequirements = electedPath.getDelete().getSecurity(); - } - - if (securityRequirements != null) { - for (SecurityRequirement securityRequirement : securityRequirements) { - for (Map.Entry> securityRequirementEntry : securityRequirement.entrySet()) { - scopes.addAll(securityRequirementEntry.getValue()); - } - } - } - return scopes; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/DCRTPPValidationExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/DCRTPPValidationExecutor.java deleted file mode 100644 index 6f4ab744..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/DCRTPPValidationExecutor.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.tpp.validation.executor; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.TPPValidationException; -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.executor.service.CertValidationService; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.JSONValue; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * TPP validation handler used to validate the TPP status using external validation services - * for DCR API requests. - */ -public class DCRTPPValidationExecutor implements OpenBankingGatewayExecutor { - - private static final String BODY = "body"; - private static final String GET_METHOD_TYPE = "GET"; - private static final String DELETE_METHOD_TYPE = "DELETE"; - private static final String SOFTWARE_ROLES = "software_roles"; - private static final String SOFTWARE_STATEMENT = "software_statement"; - - private static final Log log = LogFactory.getLog(DCRTPPValidationExecutor.class); - - @Generated(message = "Ignoring since all cases are covered from other unit tests") - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - // Skip the executor if previous executors failed. - if (obapiRequestContext.isError()) { - return; - } - - try { - Certificate[] clientCerts = obapiRequestContext.getClientCertsLatest(); - if (clientCerts != null && clientCerts.length > 0) { - Optional transportCert = - CertificateValidationUtils.convertCertToX509Cert(clientCerts[0]); - - // Only Do Validation if Mutual TLS is used. - if (transportCert.isPresent()) { - - String httpMethod = obapiRequestContext.getMsgInfo().getHttpMethod(); - - // During DCR request, skip validation if the method is GET or DELETE as the application roles - // cannot be updated through GET or DELETE. - // Since there is no SSA during these calls, we cannot find the applicable roles as well. - if (GET_METHOD_TYPE.equals(httpMethod) || DELETE_METHOD_TYPE.equals(httpMethod)) { - return; - } - - String softwareStatement = getSSAFromPayload(obapiRequestContext.getRequestPayload()); - List requiredPSD2Roles = getRolesFromSSA(softwareStatement); - - if (requiredPSD2Roles.isEmpty()) { - throw new TPPValidationException("No roles found associated with the request. Hence, cannot " + - "continue with TPP validation"); - } - - if (CertValidationService.getInstance().validateTppRoles(transportCert.get(), requiredPSD2Roles)) { - log.debug("TPP validation service returned a success response"); - } else { - log.error("TPP validation service returned invalid TPP status"); - throw new TPPValidationException("TPP validation service returned invalid TPP status"); - } - } // cert validation executor validates the certificate validity - } // enforcement executor validates the certificate presence - } catch (TPPValidationException | CertificateValidationException | ParseException e) { - final String errorMsg = "Error occurred while validating the TPP status "; - log.error(errorMsg, e); - - //catch errors and set to context - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.TPP_VALIDATION_FAILED_CODE, - e.getMessage(), errorMsg, OpenBankingErrorCodes.FORBIDDEN_CODE); - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } catch (CertificateException e) { - String errorMsg = "Error occurred while converting the client certificate to X509Certificate "; - log.error(errorMsg, e); - OpenBankingExecutorError error = new OpenBankingExecutorError( - OpenBankingErrorCodes.TPP_VALIDATION_FAILED_CODE, errorMsg, - e.getMessage(), OpenBankingErrorCodes.FORBIDDEN_CODE); - CertificateValidationUtils.handleExecutorErrors(error, obapiRequestContext); - } - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - // Do not need to handle the response - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } - - private String getSSAFromPayload(String requestPayload) throws ParseException { - // decode request body and get payload - JSONObject requestBody = JWTUtils.decodeRequestJWT(requestPayload, BODY); - // extract software statement - return requestBody.getAsString(SOFTWARE_STATEMENT); - } - - /** - * Extract PSD2 roles from SSA. - * - * @param softwareStatement software statement extracted from request payload - * @return list of PSD2RoleEnum - * @throws TPPValidationException when an error occurs when generating PSD2 roles list - */ - public List getRolesFromSSA(String softwareStatement) throws TPPValidationException { - - List requiredPSD2Roles = new ArrayList<>(); - try { - // decode software statement and get payload - JSONObject softwareStatementBody = JWTUtils.decodeRequestJWT(softwareStatement, BODY); - - String softwareRolesStr = softwareStatementBody.getAsString(SOFTWARE_ROLES); - - if (StringUtils.isNotBlank(softwareRolesStr) && softwareRolesStr.contains("[")) { - JSONArray softwareRoles = (JSONArray) JSONValue.parseStrict(softwareRolesStr); - - softwareRoles.stream() - .map(softwareRole -> PSD2RoleEnum.fromValue((String) softwareRole)) - .filter(Objects::nonNull) - .forEach(requiredPSD2Roles::add); - } else { - log.error("Invalid SSA software roles received. Expected array of software roles. Received: " - + softwareRolesStr); - } - } catch (net.minidev.json.parser.ParseException | ParseException e) { - log.error("Error while parsing the message to json", e); - throw new TPPValidationException("Error while parsing the message to json", e); - - } - - return requiredPSD2Roles; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsRequestSignatureHandlingExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsRequestSignatureHandlingExecutor.java deleted file mode 100644 index f300e722..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsRequestSignatureHandlingExecutor.java +++ /dev/null @@ -1,627 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.jws; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.ECDSAVerifier; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKMatcher; -import com.nimbusds.jose.jwk.JWKSelector; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.jwk.KeyOperation; -import com.nimbusds.jose.jwk.KeyUse; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jose.util.Base64URL; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.identity.retriever.JWKRetriever; -import com.wso2.openbanking.accelerator.common.identity.retriever.sp.CommonServiceProviderRetriever; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import javax.ws.rs.HttpMethod; - -/** - * Class to handle JWS Signature validation for requests. - */ -public class JwsRequestSignatureHandlingExecutor implements OpenBankingGatewayExecutor { - - private static final Log log = LogFactory.getLog(JwsRequestSignatureHandlingExecutor.class); - private static final String B64_CLAIM_KEY = "b64"; - private static final String XML_DECLARATION = "\n"; - private static final String DOT_SYMBOL = "."; - - private String xWso2ApiVersion = null; - private String xWso2ApiType = null; - private String signatureHeaderName = getSignatureHeaderName(); - - /** - * Method to handle pre request. - * - * @param obapiRequestContext OB request context object - */ - @Override - @Generated(message = "Excluded from code coverage since it is covered by other methods") - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - @Generated(message = "Excluded from code coverage since it is covered by other methods") - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - if (obapiRequestContext.isError()) { - return; - } - - String messageID = obapiRequestContext.getMsgInfo().getMessageId(); - - log.info(String.format("Executing JwsSignatureHandlingExecutor postProcessRequest for request %s", messageID)); - - if (StringUtils.isEmpty(getXWso2ApiVersion())) { - setXWso2ApiVersion(obapiRequestContext.getApiRequestInfo().getVersion()); - } - - if (StringUtils.isEmpty(getXWso2ApiType())) { - setXWso2ApiType(obapiRequestContext.getApiRequestInfo().getContext()); - } - - // Retrieve headers and payload. - Map requestHeaders = obapiRequestContext.getMsgInfo().getHeaders(); - - Boolean isApplicable = preProcessValidation(obapiRequestContext, requestHeaders); - if (!isApplicable) { - return; - } - - Optional payload = Optional.empty(); - - if (requestHeaders.containsKey(GatewayConstants.CONTENT_TYPE_TAG)) { - if (requestHeaders.get(GatewayConstants.CONTENT_TYPE_TAG).contains(GatewayConstants.TEXT_XML_CONTENT_TYPE) - || requestHeaders.get(GatewayConstants.CONTENT_TYPE_TAG).contains( - GatewayConstants.APPLICATION_XML_CONTENT_TYPE)) { - try { - payload = Optional.of(GatewayUtils.getXMLPayloadToSign(obapiRequestContext.getMsgInfo() - .getPayloadHandler().consumeAsString())); - } catch (Exception e) { - GatewayUtils.handleRequestInternalServerError(obapiRequestContext, - "Internal Server Error, Unable to process Payload", - OpenBankingErrorCodes.SERVER_ERROR_CODE); - } - } else { - payload = Optional.ofNullable(obapiRequestContext.getRequestPayload()); - } - } else { - payload = Optional.ofNullable(obapiRequestContext.getRequestPayload()); - } - - // If the payload can be parsed. - if (log.isDebugEnabled()) { - log.debug(String.format("Request %s is Applicable for JWS Validation", messageID)); - } - - - // Retrieve consumer key from headers. - Optional clientID = Optional.ofNullable(obapiRequestContext.getApiRequestInfo().getConsumerKey()); - // Retrieve x-jws-signature from headers. - String jwsSignature = requestHeaders.get(signatureHeaderName); - // Retrieve context properties. - Map contextProps = obapiRequestContext.getContextProps(); - - // The sent header value should not be empty. - if (StringUtils.isEmpty(jwsSignature)) { - log.error(OpenBankingErrorCodes.EXECUTOR_JWS_SIGNATURE_NOT_FOUND); - handleJwsSignatureErrors(obapiRequestContext, "Empty JWS Signature", - OpenBankingErrorCodes.INVALID_SIGNATURE_CODE); - return; - } - - // Adding jws signature to the context properties - contextProps.put(signatureHeaderName, jwsSignature); - obapiRequestContext.setContextProps(contextProps); - // Now JWS Signature is part of the context properties of the req object. - - if (clientID.isPresent()) { - if (payload.isPresent() && !payload.get().matches("\"\"")) { - if (log.isDebugEnabled()) { - log.debug(String.format("Built ClientID %s for request", clientID.get())); - log.debug("Payload extracted from request"); - } - - boolean verified = false; - try { - verified = validateMessageSignature(clientID.get(), jwsSignature, obapiRequestContext, - payload.get()); - } catch (OpenBankingException | OpenBankingExecutorException e) { - log.error("Unable to validate message signature for the client ID " + clientID.get(), e); - handleJwsSignatureErrors(obapiRequestContext, e.getMessage(), - OpenBankingErrorCodes.INVALID_SIGNATURE_CODE); - return; - } - if (!verified) { - log.error("Signature validation failed for the client ID " + clientID.get()); - handleJwsSignatureErrors(obapiRequestContext, "Invalid JWS Signature", - OpenBankingErrorCodes.INVALID_SIGNATURE_CODE); - } - } else { - if (HttpMethod.POST.equals(obapiRequestContext.getMsgInfo().getMessageId()) || - HttpMethod.PUT.equals(obapiRequestContext.getMsgInfo().getMessageId())) { - handleJwsSignatureErrors(obapiRequestContext, "Request payload cannot be empty", - OpenBankingErrorCodes.MISSING_REQUEST_PAYLOAD); - } - } - } - } - - /** - * Method to validate if the request mandates to execute JWS Signature Validation. - * - * @param obapiRequestContext OB request context object - * @param requestHeaders OB request header Map - */ - @Generated(message = "Removed from unit test coverage since Common module is required") - public Boolean preProcessValidation(OBAPIRequestContext obapiRequestContext, Map requestHeaders) { - // Return if the request contains an error. - // Check mandated apis at toolkit level. - return !obapiRequestContext.isError() && OpenBankingConfigParser.getInstance().isJwsSignatureValidationEnabled() - && !HttpMethod.GET.equals(obapiRequestContext.getMsgInfo().getHttpMethod()) - && !HttpMethod.DELETE.equals(obapiRequestContext.getMsgInfo().getHttpMethod()); - } - - /** - * Method to handle pre response. - * - * @param obapiResponseContext OB response context object - */ - - @Override - @Generated(message = "Excluded from code coverage since it is covered by other methods") - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - @Generated(message = "Excluded from code coverage since it is covered by other methods") - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Claims to be validated in JWS header. - * - * @param obapiRequestContext OB request context object - * @param claims jose header claims - * @param appName application name - * @param jwksURI jwksUrl in URL format - * @return boolean - */ - public boolean validateClaims(OBAPIRequestContext obapiRequestContext, - JWSHeader claims, String appName, String jwksURI) { - // Implemented in toolkit level. - - // RSA PSS & EC digital signature algorithms are allowed. - List allowedSigningAlgorithms = OpenBankingConfigParser.getInstance().getJwsRequestSigningAlgorithms(); - - if (!allowedSigningAlgorithms.contains(claims.getAlgorithm().getName())) { - log.error("The " + claims.getAlgorithm().getName() + " algorithm is not supported" + - " by the Solution"); - handleJwsSignatureErrors(obapiRequestContext, "The " + claims.getAlgorithm() - .getName() + " algorithm is not supported by the Solution", - OpenBankingErrorCodes.INVALID_SIGNATURE_CODE); - } - return true; - } - - /** - * Method to validate JWS Signature. - * - * @param clientID client ID of the Application - * @param detachedContentJws JWS in header - * @param obapiRequestContext OB Request context - * @param payload HTTP request payload - * @return boolean - */ - - @Generated(message = "Excluded from code coverage since method includes accessing jwks_uri") - private boolean validateMessageSignature(String clientID, String detachedContentJws, - OBAPIRequestContext obapiRequestContext, String payload) - throws OpenBankingExecutorException, OpenBankingException { - - // Convert Detached JWS into standard JWS. - String reconstructedJws; - try { - reconstructedJws = this.reconstructJws(detachedContentJws, payload); - } catch (OpenBankingExecutorException e) { - log.error("Unable to reconstruct JWS", e); - throw new OpenBankingExecutorException("Malformed JWS Signature", e); - } - - JWSVerifier verifier = null; - JWSObject jwsObject; - RSAKey rsaKey = null; - ECKey ecKey = null; - - // Parse JWSObject to retrieve headers. - try { - jwsObject = JWSObject.parse(reconstructedJws); - } catch (ParseException e) { - log.error("Unable to parse JWS signature" , e); - throw new OpenBankingExecutorException("Unable to parse JWS signature", e); - } - - // Retrieve JWK set - String jwksURI; - String appName = null; - try { - appName = (new CommonServiceProviderRetriever()).getAppPropertyFromSPMetaData(clientID, "software_id"); - } catch (OpenBankingException e) { - log.error("Error while retrieving the app name", e); - throw new OpenBankingExecutorException("Error while retrieving the app name", e); - } - - try { - jwksURI = getJwksUrl(clientID); - - // Get JWKSet from cache or retrieve from onDemand retriever - JWKSet jwkSet = getJwkSet(jwksURI, appName); - - // Get public key from JWK used for signing. - try { - JWK key = retrievePublicKey(jwkSet, jwsObject); - // Public key of the Signing certificate is retrieved - Available 1 key with use:"Sig" - if (key != null) { - X509Certificate x509Certificate = key.getParsedX509CertChain().get(0); - // kty: "RSA" - if (key.getKeyType().getValue().equals("RSA")) { - rsaKey = RSAKey.parse(x509Certificate); - //kty: "EC" - } else if (key.getKeyType().getValue().equals("EC")) { - ecKey = ECKey.parse(x509Certificate); - //log error if the kty is not supported for the allowed signing alg. - } else { - String errorMessage = String.format("The kty %s of the Key is not supported", - key.getKeyType().getValue()); - log.error(errorMessage); - throw new OpenBankingExecutorException(errorMessage); - } - } else { - log.error("Public key of the signing certificate not found in JWK set"); - throw new OpenBankingExecutorException("Public key of the signing certificate not found in JWK " + - "set"); - } - } catch (JOSEException e) { - log.error("Certificate not valid", e); - throw new OpenBankingExecutorException("Certificate not valid", e); - } - - } catch (OpenBankingException e) { - log.error("Unable to validate JWS Signature retrieving public key", e); - throw new OpenBankingExecutorException("Unable to validate JWS Signature retrieving public key", e); - } - - // Validating "iss" , "tan", "alg", "kid" - boolean areClaimsValid = validateClaims(obapiRequestContext, jwsObject.getHeader(), appName, jwksURI); - - try { - - - JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(jwsObject.getHeader().getAlgorithm().getName()); - - Set criticalParameters = new HashSet<>(Arrays.asList(differedCriticalClaims())); - - if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm)) { - // Define JWSVerifier for JWS signed with RSA Signing alg. - verifier = new RSASSAVerifier( - rsaKey != null ? rsaKey.toRSAPublicKey() : null, criticalParameters); - } else if (JWSAlgorithm.Family.EC.contains(jwsAlgorithm)) { - // Define JWSVerifier for JWS signed with EC Signing alg. - verifier = new ECDSAVerifier( - ecKey != null ? ecKey.toECPublicKey() : null, criticalParameters); - } else { - String errorMessage = "The " + jwsObject.getHeader().getAlgorithm().getName() + " algorithm is not " + - "supported by the Solution"; - log.error(errorMessage); - throw new OpenBankingExecutorException(errorMessage); - - } - - } catch (JOSEException e) { - log.error("Invalid Signing Algorithm" , e); - throw new OpenBankingExecutorException("Invalid JWS Signature,signed with invalid " + - "algorithm", e); - } - - // If claims are verified, verify signature. - // Since asymmetric alg is used, the signature can be verified using public key only. - - boolean verified; - - if (areClaimsValid) { - try { - // Check if payload is b64 encoded or un-encoded - if (isB64HeaderVerifiable(jwsObject)) { - // b64=true - verified = jwsObject.verify(verifier); - } else { - // b64=false - // Produces the signature with un-encoded payload. - // which is the encoded header + ".." + the encoded signature - String[] jwsParts = StringUtils.split(detachedContentJws, DOT_SYMBOL); - - JWSHeader header = JWSHeader.parse(new Base64URL(jwsParts[0])); - Base64URL signature = new Base64URL(jwsParts[1]); - verified = verifier.verify(header, getSigningInput(header, payload), signature); - } - if (verified) { - return true; - } - } catch (JOSEException e) { - log.error("Unable to verify JWS signature", e); - throw new OpenBankingExecutorException("Unable to verify JWS signature", e); - } catch (ParseException e) { - log.error("Error occurred while parsing the JWS Header", e); - throw new OpenBankingExecutorException("Error occurred while parsing the JWS Header", e); - } - } - return false; - } - - /** - * Method to reconstruct a detached JWS with encoded payload. - * - * @param jwsSignature Detached JWS - * @param payload HTTP request payload - * @return boolean - */ - private String reconstructJws(String jwsSignature, String payload) throws OpenBankingExecutorException { - - // GET requests and DELETE requests will not need message signing. - if (StringUtils.isEmpty(payload)) { - throw new OpenBankingExecutorException("Payload is required for JWS reconstruction"); - } - - String[] jwsParts = jwsSignature.split("\\."); - - if (log.isDebugEnabled()) { - log.debug(String.format("Found %d parts in JWS for reconstruction", jwsParts.length)); - } - - // Add Base64Url encoded payload. - if (jwsParts.length == 3) { - jwsParts[1] = Base64URL.encode(payload).toString(); - - // Reconstruct JWS with `.` deliminator - return String.join(DOT_SYMBOL, jwsParts); - } else if (jwsParts.length == 5) { - throw new OpenBankingExecutorException("Not supported for signed and encrypted JWTs."); - } - - throw new OpenBankingExecutorException("Required number of parts not found in JWS for reconstruction"); - } - - /** - * If the b64 header is not available or is true, it is verifiable. - * - * @param jwsObject The reconstructed jws object parsed from x-jws-signature - * @return Boolean - */ - private boolean isB64HeaderVerifiable(JWSObject jwsObject) { - - JWSHeader jwsHeader = jwsObject.getHeader(); - Object b64Value = jwsHeader.getCustomParam(B64_CLAIM_KEY); - return b64Value != null ? ((Boolean) b64Value) : true; - } - - /** - * Method to retrieve payload from File Payment Upload requests. - * - * @param header - * @param jwsPayload - * @return signing input - */ - private byte[] getSigningInput(JWSHeader header, String jwsPayload) { - - String combinedInput = header.toBase64URL().toString() + DOT_SYMBOL + jwsPayload; - return combinedInput.getBytes(StandardCharsets.UTF_8); - } - - /** - * Method to handle errors in JWS Signature validation. - * - * @param obapiRequestContext OB request context object - * @param message error message - */ - public void handleJwsSignatureErrors( - OBAPIRequestContext obapiRequestContext, String message, String errorCode) { - - OpenBankingExecutorError error = new OpenBankingExecutorError(errorCode, - OpenBankingErrorCodes.JWS_SIGNATURE_HANDLE_ERROR, message, OpenBankingErrorCodes.BAD_REQUEST_CODE); - setErrorsToRequestContext(obapiRequestContext, error); - } - - public void setErrorsToRequestContext(OBAPIRequestContext obapiRequestContext, OpenBankingExecutorError error) { - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - obapiRequestContext.setError(true); - obapiRequestContext.setErrors(executorErrors); - } - - /** - * Method to retrieve JWKS Url from service Provider properties. - * @param clientID - * @return - * @throws OpenBankingException - */ - @Generated(message = "Excluded from code coverage since method includes service call") - private String getJwksUrl(String clientID) throws OpenBankingException { - - String jwksURI; - try { - jwksURI = (new CommonServiceProviderRetriever()).getAppPropertyFromSPMetaData(clientID, "jwksURI"); - if (jwksURI == null) { - throw new OpenBankingException("The JWK set URL must not be null"); - } - } catch (OpenBankingException e) { - log.error("JWKS URL is not found", e); - throw new OpenBankingException("The JWKS_URI is not found for client ID " + clientID, e); - } - return jwksURI; - } - - /** - * Method to retrieve the JWKSet from JWKS URI. - * - * @param jwksURI - * @param appName - * @return - * @throws OpenBankingException - */ - @Generated(message = "Excluded from code coverage since method includes accessing jwks_uri") - private JWKSet getJwkSet(String jwksURI, String appName) throws OpenBankingException { - JWKSet jwkSet; - try { - jwkSet = new JWKRetriever().getJWKSet(new URL(jwksURI), appName); - } catch (MalformedURLException e) { - log.error("Provided JWKS URL is malformed", e); - throw new OpenBankingException("The provided JWKS_URI is malformed", e); - } - - return jwkSet; - } - - /** - * Method to retrieve the public key from JWKSet. - * - * @param jwkSet - * @param jwsObject - * @return - */ - @Generated(message = "Excluded from code coverage since method includes accessing JWKSet") - private JWK retrievePublicKey(JWKSet jwkSet, JWSObject jwsObject) { - - JWK key = null; - // First get the key with given kid, use as sig and operation as verify from the list. - JWKMatcher keyMatcherWithKidUseAndOperation = - new JWKMatcher.Builder().keyID(jwsObject.getHeader().getKeyID()) - .keyUse(KeyUse.SIGNATURE) - .keyOperation(KeyOperation.VERIFY) - .build(); - List jwkList = new JWKSelector(keyMatcherWithKidUseAndOperation).select(jwkSet); - - if (jwkList.isEmpty()) { - // If empty, then get the key with given kid and use as sig from the list. - JWKMatcher keyMatcherWithKidAndUse = new JWKMatcher.Builder() - .keyID(jwsObject.getHeader().getKeyID()) - .keyUse(KeyUse.SIGNATURE).build(); - jwkList = new JWKSelector(keyMatcherWithKidAndUse).select(jwkSet); - - if (jwkList.isEmpty()) { - // fail over defaults to ->, then get the key with given kid. - JWKMatcher keyMatcherWithKid = new JWKMatcher.Builder().keyID(jwsObject.getHeader().getKeyID()).build(); - jwkList = new JWKSelector(keyMatcherWithKid).select(jwkSet); - } - } - - if (jwkList.isEmpty()) { - log.error("No matching KID found to retrieve public key in JWK set"); - } else { - key = jwkList.get(0); - } - - return key; - } - - /** - * Differed critical parameters for validation. - * - * @return list of critical claims - */ - public String[] differedCriticalClaims() { - // Implemented at toolkit level - - return new String[0]; - } - - public void setXWso2ApiVersion(String xWso2ApiVersion) { - - this.xWso2ApiVersion = xWso2ApiVersion; - } - - public String getXWso2ApiVersion() { - - return this.xWso2ApiVersion; - } - - public String getXWso2ApiType() { - - return xWso2ApiType; - } - - public void setXWso2ApiType(String xWso2ApiType) { - - this.xWso2ApiType = xWso2ApiType; - } - - // If the header name is different at toolkit level, - // this method need to override. - public String getSignatureHeaderName() { - - return "x-jws-signature"; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsResponseSignatureHandlingExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsResponseSignatureHandlingExecutor.java deleted file mode 100644 index cdbf3f92..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsResponseSignatureHandlingExecutor.java +++ /dev/null @@ -1,256 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.jws; - -import com.nimbusds.jose.JOSEException; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Executor class for Signing Responses. - * @deprecated - * Use {@link com.wso2.openbanking.accelerator.gateway.handler.JwsResponseSignatureHandler} instead. - */ -@Deprecated -public class JwsResponseSignatureHandlingExecutor implements OpenBankingGatewayExecutor { - - private static final Log log = LogFactory.getLog(JwsResponseSignatureHandlingExecutor.class); - - private String xWso2ApiVersion = null; - private String xWso2ApiType = null; - private String signatureHeaderName = getSignatureHeaderName(); - - @Generated(message = "Excluding from unit tests since it is covered by other methods") - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - if (obapiRequestContext.isError()) { - appendJwsSignatureToRequestContext(obapiRequestContext); - } - } - - @Generated(message = "Excluding from unit tests since it is covered by other methods") - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - if (obapiRequestContext.isError()) { - appendJwsSignatureToRequestContext(obapiRequestContext); - } - } - - /** - * Method to handle pre-process response. - * - * @param obapiResponseContext OB response context object - */ - @Generated(message = "Excluding from unit tests since it is covered by other methods") - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - appendJwsSignatureToResponseContext(obapiResponseContext); - } - - @Generated(message = "Excluding from unit tests since it is covered by other methods") - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - appendJwsSignatureToResponseContext(obapiResponseContext); - } - - /** - * Provide the child classes to decide whether the signature generation is required for requestPath. - * - * @param obapiRequestContext OB response Object - * @return boolean returns if request needs to be signed - */ - @Generated(message = "Excluding from unit tests since there is a call to a method in Common Module") - public boolean isApplicableForRequestPath(OBAPIRequestContext obapiRequestContext) { - - return OpenBankingConfigParser.getInstance().isJwsResponseSigningEnabled(); - } - - /** - * Provide the child classes to decide whether the signature generation is required for error scenarios. - * - * @param obapiResponseContext OB response Object - * @return boolean returns if request needs to be signed - */ - @Generated(message = "Excluding from unit tests since there is a call to a method in Common Module") - public boolean isApplicableForResponsePath(OBAPIResponseContext obapiResponseContext) { - - return OpenBankingConfigParser.getInstance().isJwsResponseSigningEnabled(); - } - - /** - * Method to Generate JWS signature. - * - * @param payloadString - * @return - */ - public String generateJWSSignature(Optional payloadString) - throws OpenBankingExecutorException, JOSEException { - - String jwsSignatureHeader = null; - if (payloadString.isPresent() && StringUtils.isNotBlank(payloadString.get())) { - HashMap criticalParameters = getCriticalHeaderParameters(); - jwsSignatureHeader = GatewayUtils.constructJWSSignature(payloadString.get(), criticalParameters); - } else { - log.debug("Signature cannot be generated as the payload is invalid or authentication context is not " + - "available"); - } - return jwsSignatureHeader; - } - - /** - * HashMap to be returned with crit header keys and values. - * can be extended at toolkit level. - * - * @return HashMap crit header parameters - */ - public HashMap getCriticalHeaderParameters() { - - return new HashMap<>(); - } - - @Generated(message = "Excluding from unit test coverage") - public void setXWso2ApiVersion(String xWso2ApiVersion) { - - this.xWso2ApiVersion = xWso2ApiVersion; - } - - @Generated(message = "Excluding from unit test coverage") - public String getXWso2ApiVersion() { - - return this.xWso2ApiVersion; - } - - @Generated(message = "Excluding from unit test coverage") - public String getXWso2ApiType() { - - return xWso2ApiType; - } - - @Generated(message = "Excluding from unit test coverage") - public void setXWso2ApiType(String xWso2ApiType) { - - this.xWso2ApiType = xWso2ApiType; - } - - /** - * Method to change the expected request header name containing the JWS. - */ - public String getSignatureHeaderName() { - - return "x-jws-signature"; - } - - /** - * Method to append Jws Signature To Request Context. - * @param obapiRequestContext - */ - @Generated(message = "Excluding from unit tests since it is covered by other methods") - private void appendJwsSignatureToRequestContext(OBAPIRequestContext obapiRequestContext) { - - setXWso2ApiVersion(obapiRequestContext.getApiRequestInfo().getVersion()); - setXWso2ApiType(obapiRequestContext.getApiRequestInfo().getContext()); - - String messageID = obapiRequestContext.getMsgInfo().getMessageId(); - - if (!isApplicableForRequestPath(obapiRequestContext)) { - if (log.isDebugEnabled()) { - log.debug(String.format( - "Signature generation is not applicable for this response " + - "with message id : %s", messageID)); - } - return; - } else { - if (log.isDebugEnabled()) { - log.debug(String.format( - "Generating signature for the response " + - "with message id : %s", messageID)); - } - // Retrieve headers and payload. - try { - Map responseHeaders = obapiRequestContext.getMsgInfo().getHeaders(); - Optional payload = GatewayUtils.extractRequestPayload(obapiRequestContext, - obapiRequestContext.getMsgInfo().getHeaders()); - responseHeaders.put(signatureHeaderName, generateJWSSignature(payload)); - obapiRequestContext.setAddedHeaders(responseHeaders); - } catch (OpenBankingException | OpenBankingExecutorException | JOSEException e) { - log.error("Unable to sign response", e); - GatewayUtils.handleRequestInternalServerError(obapiRequestContext, - "Internal Server Error, Unable to sign the response", - OpenBankingErrorCodes.SERVER_ERROR_CODE); - } - } - } - - /** - * Method to append Jws Signature To Response Context. - * @param obapiResponseContext - */ - @Generated(message = "Excluding from unit tests since it is covered by other methods") - private void appendJwsSignatureToResponseContext(OBAPIResponseContext obapiResponseContext) { - - setXWso2ApiVersion(obapiResponseContext.getApiRequestInfo().getVersion()); - setXWso2ApiType(obapiResponseContext.getApiRequestInfo().getContext()); - - String messageID = obapiResponseContext.getMsgInfo().getMessageId(); - - if (!isApplicableForResponsePath(obapiResponseContext)) { - if (log.isDebugEnabled()) { - log.debug(String.format( - "Signature generation is not applicable for this response " + - "with message id : %s", messageID)); - } - return; - } else { - if (log.isDebugEnabled()) { - log.debug(String.format( - "Generating signature for the response " + - "with message id : %s", messageID)); - } - // Retrieve headers and payload. - try { - Map responseHeaders = obapiResponseContext.getMsgInfo().getHeaders(); - Optional payload = GatewayUtils.extractResponsePayload(obapiResponseContext, - obapiResponseContext.getMsgInfo().getHeaders()); - responseHeaders.put(signatureHeaderName, generateJWSSignature(payload)); - obapiResponseContext.setAddedHeaders(responseHeaders); - } catch (OpenBankingException | OpenBankingExecutorException | - JOSEException e) { - log.error("Unable to sign response", e); - GatewayUtils.handleResponseInternalServerError(obapiResponseContext, - "Internal Server Error, Unable to sign the response", - OpenBankingErrorCodes.SERVER_ERROR_CODE); - } - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OBAPIRequestContext.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OBAPIRequestContext.java deleted file mode 100644 index 0ab7eb3b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OBAPIRequestContext.java +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.model; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import io.swagger.parser.OpenAPIParser; -import io.swagger.v3.oas.models.OpenAPI; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONException; -import org.json.JSONObject; -import org.wso2.carbon.apimgt.common.gateway.dto.APIRequestInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; - -import java.io.UnsupportedEncodingException; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import javax.security.cert.X509Certificate; - -/** - * Open Banking executor request context. - */ -public class OBAPIRequestContext extends RequestContextDTO { - - private static final Log log = LogFactory.getLog(OBAPIRequestContext.class); - private final RequestContextDTO requestContextDTO; - private Map contextProps; - private String modifiedPayload; - private String requestPayload; - private Map addedHeaders; - private boolean isError; - private ArrayList errors; - private String consentId; - private Map analyticsData; - private OpenAPI openAPI; - - public OBAPIRequestContext(RequestContextDTO requestContextDTO, - Map contextProps, Map analyticsData) { - - this.requestContextDTO = requestContextDTO; - this.addedHeaders = new HashMap<>(); - this.errors = new ArrayList<>(); - this.contextProps = contextProps; - this.analyticsData = analyticsData; - - Map headers = requestContextDTO.getMsgInfo().getHeaders(); - String authHeader = headers.get(GatewayConstants.AUTH_HEADER); - if (authHeader != null && !authHeader.isEmpty() && - GatewayUtils.isValidJWTToken(authHeader.replace(GatewayConstants.BEARER_TAG, ""))) { - this.consentId = extractConsentID(authHeader); - } - - String apiId = requestContextDTO.getApiRequestInfo().getApiId(); - Object cacheObject = GatewayDataHolder.getGatewayCache() - .getFromCache(GatewayCacheKey.of(apiId)); - if (cacheObject == null) { - String swaggerDefinition = GatewayUtils.getSwaggerDefinition(apiId); - OpenAPIParser parser = new OpenAPIParser(); - this.openAPI = parser.readContents(swaggerDefinition, null, null).getOpenAPI(); - GatewayDataHolder.getGatewayCache().addToCache(GatewayCacheKey.of(apiId), this.openAPI); - } else { - this.openAPI = (OpenAPI) cacheObject; - } - if (requestContextDTO.getMsgInfo().getHeaders().get(GatewayConstants.CONTENT_TYPE_TAG) != null) { - String contentType = requestContextDTO.getMsgInfo().getHeaders().get(GatewayConstants.CONTENT_TYPE_TAG); - String httpMethod = requestContextDTO.getMsgInfo().getHttpMethod(); - String errorMessage = "Request Content-Type header does not match any allowed types"; - if (contentType.startsWith(GatewayConstants.JWT_CONTENT_TYPE) || contentType.startsWith(GatewayConstants - .JOSE_CONTENT_TYPE)) { - try { - this.requestPayload = GatewayUtils.getTextPayload(requestContextDTO.getMsgInfo().getPayloadHandler() - .consumeAsString()); - } catch (Exception e) { - log.error(String.format("Failed to read the text payload from request. %s", e.getMessage())); - handleContentTypeErrors(OpenBankingErrorCodes.INVALID_CONTENT_TYPE, errorMessage); - } - } else if (GatewayUtils.isEligibleRequest(contentType, httpMethod)) { - try { - this.requestPayload = requestContextDTO.getMsgInfo().getPayloadHandler().consumeAsString(); - } catch (Exception e) { - log.error(String.format("Failed to read the payload from request. %s", e.getMessage())); - handleContentTypeErrors(OpenBankingErrorCodes.INVALID_CONTENT_TYPE, errorMessage); - } - } else { - this.requestPayload = null; - } - } - } - - public String getModifiedPayload() { - - return modifiedPayload; - } - - public void setModifiedPayload(String modifiedPayload) { - - this.modifiedPayload = modifiedPayload; - } - - public Map getAddedHeaders() { - - return addedHeaders; - } - - public void setAddedHeaders(Map addedHeaders) { - - this.addedHeaders = addedHeaders; - } - - public Map getContextProps() { - - return contextProps; - } - - public void setContextProps(Map contextProps) { - - this.contextProps = contextProps; - } - - public boolean isError() { - - return isError; - } - - public void setError(boolean error) { - - isError = error; - } - - public ArrayList getErrors() { - - return errors; - } - - public void setErrors( - ArrayList errors) { - - this.errors = errors; - } - - public String getConsentId() { - - return consentId; - } - - public void setConsentId(String consentId) { - - this.consentId = consentId; - } - - public OpenAPI getOpenAPI() { - - return openAPI; - } - - public void setOpenAPI(OpenAPI openAPI) { - - this.openAPI = openAPI; - } - - public Map getAnalyticsData() { - - return analyticsData; - } - - public void setAnalyticsData(Map analyticsData) { - - this.analyticsData = analyticsData; - } - - @Override - public MsgInfoDTO getMsgInfo() { - - return requestContextDTO.getMsgInfo(); - } - - @Override - public APIRequestInfoDTO getApiRequestInfo() { - - return requestContextDTO.getApiRequestInfo(); - } - - @Override - public X509Certificate[] getClientCerts() { - - return requestContextDTO.getClientCerts(); - } - - @Override - public Certificate[] getClientCertsLatest() { - return requestContextDTO.getClientCertsLatest(); - } - - public String getRequestPayload() { - - return requestPayload; - } - - private String extractConsentID(String jwtToken) { - - String consentIdClaim = null; - try { - if (!jwtToken.contains(GatewayConstants.BASIC_TAG)) { - jwtToken = jwtToken.replace(GatewayConstants.BEARER_TAG, ""); - JSONObject jwtClaims = GatewayUtils.decodeBase64(GatewayUtils.getPayloadFromJWT(jwtToken)); - String consentIdClaimName = - GatewayDataHolder.getInstance().getOpenBankingConfigurationService().getConfigurations() - .get(GatewayConstants.CONSENT_ID_CLAIM_NAME).toString(); - if (!jwtClaims.isNull(consentIdClaimName) && - !jwtClaims.getString(consentIdClaimName).isEmpty()) { - consentIdClaim = jwtClaims.getString(consentIdClaimName); - } - } - } catch (UnsupportedEncodingException | JSONException | IllegalArgumentException e) { - log.error(String.format("Failed to retrieve the consent ID from JWT claims. %s", e.getMessage())); - } - return consentIdClaim; - } - - public void addContextProperty(String key, String value) { - - this.contextProps.put(key, value); - } - - public String getContextProperty(String key) { - - return this.contextProps.get(key); - } - - private void handleContentTypeErrors(String errorCode, String errorMessage) { - OpenBankingExecutorError error = new OpenBankingExecutorError(errorCode, - OpenBankingErrorCodes.UNSUPPORTED_MEDIA_TYPE, errorMessage, - OpenBankingErrorCodes.UNSUPPORTED_MEDIA_TYPE_CODE); - - this.isError = true; - this.errors.add(error); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OBAPIResponseContext.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OBAPIResponseContext.java deleted file mode 100644 index 2ca398bf..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OBAPIResponseContext.java +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.model; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.json.JSONObject; -import org.json.XML; -import org.wso2.carbon.apimgt.common.gateway.dto.APIRequestInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.ResponseContextDTO; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** - * Open Banking executor response context. - */ -public class OBAPIResponseContext extends ResponseContextDTO { - - private static final Log log = LogFactory.getLog(OBAPIResponseContext.class); - private ResponseContextDTO responseContextDTO; - private Map contextProps; - private String responsePayload; - private String modifiedPayload; - private Map addedHeaders; - private boolean isError; - private ArrayList errors; - private Map analyticsData; - - public OBAPIResponseContext(ResponseContextDTO responseContextDTO, Map contextProps, - Map analyticsData) { - - this.responseContextDTO = responseContextDTO; - this.contextProps = contextProps; - this.errors = new ArrayList<>(); - this.analyticsData = analyticsData; - this.addedHeaders = new HashMap<>(); - if (responseContextDTO.getMsgInfo().getHeaders().get(GatewayConstants.CONTENT_TYPE_TAG) != null) { - String contentType = responseContextDTO.getMsgInfo().getHeaders().get(GatewayConstants.CONTENT_TYPE_TAG); - String httpMethod = responseContextDTO.getMsgInfo().getHttpMethod(); - String errorMessage = "Request Content-Type header does not match any allowed types"; - if (contentType.startsWith(GatewayConstants.JWT_CONTENT_TYPE)) { - try { - this.responsePayload = GatewayUtils.getTextPayload(responseContextDTO.getMsgInfo() - .getPayloadHandler().consumeAsString()); - } catch (Exception e) { - log.error(String.format("Failed to read the text payload from response. %s", e.getMessage())); - handleContentTypeErrors(OpenBankingErrorCodes.INVALID_CONTENT_TYPE, errorMessage); - } - } else if (GatewayUtils.isEligibleResponse(contentType, httpMethod) && - HttpStatus.SC_NO_CONTENT != responseContextDTO.getStatusCode()) { - try { - this.responsePayload = responseContextDTO.getMsgInfo().getPayloadHandler().consumeAsString(); - if (contentType.contains(GatewayConstants.JSON_CONTENT_TYPE) && - this.responsePayload.contains("soapenv:Body")) { - JSONObject soapPayload = XML.toJSONObject(responseContextDTO.getMsgInfo().getPayloadHandler() - .consumeAsString()).getJSONObject("soapenv:Body"); - if (soapPayload.has("jsonObject")) { - this.responsePayload = soapPayload.getJSONObject("jsonObject").toString(); - } else { - this.responsePayload = null; - } - } - } catch (Exception e) { - log.error(String.format("Failed to read the payload from response. %s", e.getMessage())); - handleContentTypeErrors(OpenBankingErrorCodes.INVALID_CONTENT_TYPE, errorMessage); - } - } else { - this.responsePayload = null; - } - } - } - - public String getModifiedPayload() { - - return modifiedPayload; - } - - public void setModifiedPayload(String modifiedPayload) { - - this.modifiedPayload = modifiedPayload; - } - - public Map getAddedHeaders() { - - return addedHeaders; - } - - public void setAddedHeaders(Map addedHeaders) { - - this.addedHeaders = addedHeaders; - } - - public Map getContextProps() { - - return contextProps; - } - - public void setContextProps(Map contextProps) { - - this.contextProps = contextProps; - } - - public boolean isError() { - - return isError; - } - - public void setError(boolean error) { - - isError = error; - } - - public ArrayList getErrors() { - - return errors; - } - - public void setErrors( - ArrayList errors) { - - this.errors = errors; - } - - public Map getAnalyticsData() { - - return analyticsData; - } - - public void setAnalyticsData(Map analyticsData) { - - this.analyticsData = analyticsData; - } - - @Override - public APIRequestInfoDTO getApiRequestInfo() { - - return this.responseContextDTO.getApiRequestInfo(); - } - - @Override - public int getStatusCode() { - - return responseContextDTO.getStatusCode(); - } - - @Override - public MsgInfoDTO getMsgInfo() { - - return responseContextDTO.getMsgInfo(); - } - - public String getResponsePayload() { - - return responsePayload; - } - - public void addContextProperty(String key, String value) { - - this.contextProps.put(key, value); - } - - public String getContextProperty(String key) { - - return this.contextProps.get(key); - } - - private void handleContentTypeErrors(String errorCode, String errorMessage) { - OpenBankingExecutorError error = new OpenBankingExecutorError(errorCode, - OpenBankingErrorCodes.UNSUPPORTED_MEDIA_TYPE, errorMessage, - OpenBankingErrorCodes.UNSUPPORTED_MEDIA_TYPE_CODE); - - this.isError = true; - this.errors.add(error); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OpenBankingExecutorError.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OpenBankingExecutorError.java deleted file mode 100644 index efcf22a3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/OpenBankingExecutorError.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.model; - -import java.util.Map; - -/** - * Error model for Open Banking executors. - */ -public class OpenBankingExecutorError { - - private String code; - private String title; - private String message; - private String httpStatusCode; - private Map links; - - public OpenBankingExecutorError() {} - - public OpenBankingExecutorError(String errorCode) { - this.code = errorCode; - } - - - public OpenBankingExecutorError(String code, String title, String message, String httpStatusCode) { - this.code = code; - this.title = title; - this.message = message; - this.httpStatusCode = httpStatusCode; - } - - public OpenBankingExecutorError(String code, String title, String message, String httpStatusCode, - Map links) { - this.code = code; - this.title = title; - this.message = message; - this.httpStatusCode = httpStatusCode; - this.links = links; - } - - public String getCode() { - - return code; - } - - public void setCode(String code) { - - this.code = code; - } - - public String getTitle() { - - return title; - } - - public void setTitle(String title) { - - this.title = title; - } - - public String getMessage() { - - return message; - } - - public void setMessage(String message) { - - this.message = message; - } - - public String getHttpStatusCode() { - - return httpStatusCode; - } - - public void setHttpStatusCode(String httpStatusCode) { - - this.httpStatusCode = httpStatusCode; - } - - public Map getLinks() { - - return links; - } - - public void setLinks(Map links) { - - this.links = links; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/RevocationStatus.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/RevocationStatus.java deleted file mode 100644 index cb1a27c4..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/model/RevocationStatus.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.executor.model; - -/** - * This is used to get Revocation Status message. - */ -public enum RevocationStatus { - - GOOD("Good"), UNKNOWN("Unknown"), REVOKED("Revoked"); - private String message; - - RevocationStatus(String message) { - - this.message = message; - } - - /** - * Get revocation status message. - * - * @return status message - */ - public String getMessage() { - - return message; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/CRLValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/CRLValidator.java deleted file mode 100644 index 47cf1a26..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/CRLValidator.java +++ /dev/null @@ -1,383 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.revocation; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.x509.CRLDistPoint; -import org.bouncycastle.asn1.x509.DistributionPoint; -import org.bouncycastle.asn1.x509.DistributionPointName; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * This is used to verify whether a certificate is revoked or not by using the Certificate Revocation List published - * by the CA. - */ -public class CRLValidator implements RevocationValidator { - - private static final Log log = LogFactory.getLog(CRLValidator.class); - - private final int retryCount; - private static int httpConnectTimeout; - private static int httpConnectionRequestTimeout; - private static int httpSocketTimeout; - - public CRLValidator(int retryCount) { - - this.retryCount = retryCount; - } - - - public CRLValidator(int retryCount, int httpConnectTimeout, int httpConnectionRequestTimeout, - int httpSocketTimeout) { - - this.retryCount = retryCount; - CRLValidator.httpConnectTimeout = httpConnectTimeout; - CRLValidator.httpConnectionRequestTimeout = httpConnectionRequestTimeout; - CRLValidator.httpSocketTimeout = httpSocketTimeout; - } - - /** - * Extracts all CRL distribution point URLs from the "CRL Distribution Point" extension in a X.509 certificate. - * If CRL distribution point extension or CRL Urls are unavailable, throw an exception. - * - * @param cert X509 certificate - * @return List of CRL Urls in the certificate - * @throws CertificateValidationException certificateValidationException - */ - public static List getCRLUrls(X509Certificate cert) throws CertificateValidationException { - - List crlUrls; - byte[] crlDPExtensionValue = getCRLDPExtensionValue(cert); - if (crlDPExtensionValue == null) { - throw new CertificateValidationException("Certificate with serial num:" + cert.getSerialNumber() - + " doesn't have CRL Distribution points"); - } - CRLDistPoint distPoint = getCrlDistPoint(crlDPExtensionValue); - crlUrls = getCrlUrlsFromDistPoint(distPoint); - - if (crlUrls.isEmpty()) { - throw new CertificateValidationException("Cannot get CRL urls from certificate with serial num:" + - cert.getSerialNumber()); - } - return crlUrls; - } - - /** - * Get revocation status of a certificate using CRL Url. - * - * @param peerCert peer certificate - * @param retryCount retry count to connect to CRL Url and get the CRL - * @param crlUrls List of CRL Urls - * @param certificateRevocationProxyEnabled whether certificate revocation proxy enabled in the config - * @param certificateRevocationProxyHost certificate revocation proxy host - * @param certificateRevocationProxyPort certificate revocation proxy port - * @return Revocation status of the certificate - * @throws CertificateValidationException certificateValidationException - */ - public static RevocationStatus getCRLRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert, - int retryCount, List crlUrls, - boolean certificateRevocationProxyEnabled, - String certificateRevocationProxyHost, - int certificateRevocationProxyPort) - throws CertificateValidationException { - - // Check with distributions points in the list one by one. if one fails go to the other. - for (String crlUrl : crlUrls) { - if (log.isDebugEnabled()) { - log.debug("Trying to get CRL for URL: " + crlUrl); - } - X509CRL x509CRL = downloadCRLFromWeb(crlUrl, retryCount, peerCert, issuerCert, - certificateRevocationProxyEnabled, certificateRevocationProxyHost, certificateRevocationProxyPort); - if (x509CRL != null) { - return getRevocationStatusFromCRL(x509CRL, peerCert); - } - } - throw new CertificateValidationException("Cannot check revocation status with the certificate"); - } - - /** - * **************************************** - * Util methods for CRL Validation. - * **************************************** - */ - - private static boolean isValidX509Crl(X509CRL x509CRL, X509Certificate peerCert, X509Certificate issuerCert) - throws CertificateValidationException { - - Date currentDate = CertificateValidationUtils.getNewDate(); - Date nextUpdate = x509CRL.getNextUpdate(); - boolean isValid = false; - - if (isValidX509CRLFromIssuer(x509CRL, peerCert, issuerCert)) { - isValid = isValidX509CRLFromNextUpdate(x509CRL, currentDate, nextUpdate); - } - return isValid; - } - - private static boolean isValidX509CRLFromIssuer(X509CRL x509CRL, X509Certificate peerCert, - X509Certificate issuerCert) - throws CertificateValidationException { - - if (!peerCert.getIssuerDN().equals(x509CRL.getIssuerDN())) { - throw new CertificateValidationException("X509 CRL is not valid. Issuer DN in the peer " + - "certificate: " + peerCert.getIssuerDN() + " does not match with the Issuer DN in the X509 CRL: " + - x509CRL.getIssuerDN()); - } - - // Verify the signature of the CRL. - try { - x509CRL.verify(issuerCert.getPublicKey()); - return true; - } catch (CRLException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | - SignatureException e) { - throw new CertificateValidationException("CRL signature cannot be verified", e); - } - } - - private static boolean isValidX509CRLFromNextUpdate(X509CRL x509CRL, Date currentDate, Date nextUpdate) - throws CertificateValidationException { - - if (nextUpdate != null) { - if (log.isDebugEnabled()) { - log.debug("Validating the next update date: " + nextUpdate.toString() + " with the current date: " + - currentDate.toString()); - } - if (currentDate.before(x509CRL.getNextUpdate())) { - return true; - } else { - throw new CertificateValidationException("X509 CRL is not valid. Next update date: " + - nextUpdate.toString() + " is before the current date: " + currentDate.toString()); - } - } else { - log.debug("Couldn't validate the X509 CRL, next update date is not available."); - } - return false; - } - - private static X509CRL downloadCRLFromWeb(String crlURL, int retryCount, X509Certificate peerCert, - X509Certificate issuerCert, boolean certificateRevocationProxyEnabled, - String certificateRevocationProxyHost, int certificateRevocationProxyPort) - throws CertificateValidationException { - - X509CRL x509CRL = null; - if (log.isDebugEnabled()) { - log.debug("Certificate revocation check proxy enabled: " + certificateRevocationProxyEnabled); - } - try (CloseableHttpClient client = HTTPClientUtils.getHttpsClient()) { - - HttpGet httpGet = new HttpGet(crlURL); - if (certificateRevocationProxyEnabled) { - log.debug("Setting certificate revocation proxy started."); - if (certificateRevocationProxyHost == null || certificateRevocationProxyHost.trim().isEmpty()) { - String message = "Certificate revocation proxy server host is not configured. Please do set the " + - "'CertificateManagement -> CertificateRevocationProxy -> ProxyHost' file"; - log.error(message); - throw new CertificateValidationException(message); - } - if (log.isDebugEnabled()) { - log.debug("Certificate revocation proxy: " + certificateRevocationProxyHost + ":" + - certificateRevocationProxyPort); - } - HttpHost proxy = new HttpHost(certificateRevocationProxyHost, certificateRevocationProxyPort); - RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); - httpGet.setConfig(config); - log.debug("Setting certificate revocation proxy finished."); - } - - // adding request timeout configurations - RequestConfig timeoutRequestConfig; - if (httpGet.getConfig() == null) { - httpGet.setConfig(RequestConfig.custom().build()); - } - timeoutRequestConfig = RequestConfig.copy(httpGet.getConfig()) - .setConnectTimeout(httpConnectTimeout) - .setConnectionRequestTimeout(httpConnectionRequestTimeout) - .setSocketTimeout(httpSocketTimeout) - .build(); - httpGet.setConfig(timeoutRequestConfig); - // add debug logs - if (log.isDebugEnabled()) { - log.debug("CRL request timeout configurations: " + "httpConnectTimeout: " + httpConnectTimeout + - ", httpConnectionRequestTimeout: " + httpConnectionRequestTimeout + ", httpSocketTimeout: " + - httpSocketTimeout); - } - - HttpResponse httpResponse = client.execute(httpGet); - //Check errors in response: - if (httpResponse.getStatusLine().getStatusCode() / 100 != 2) { - throw new CertificateValidationException("Error getting crl response." + - "Response code is " + httpResponse.getStatusLine().getStatusCode()); - } - InputStream in = httpResponse.getEntity().getContent(); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509CRL x509CRLDownloaded = (X509CRL) cf.generateCRL(in); - if (log.isDebugEnabled()) { - log.debug("CRL is downloaded from CRL Url: " + crlURL); - } - - if (isValidX509Crl(x509CRLDownloaded, peerCert, issuerCert)) { - x509CRL = x509CRLDownloaded; - } - } catch (MalformedURLException e) { - throw new CertificateValidationException("CRL Url is malformed", e); - } catch (IOException e) { - if (retryCount == 0) { - throw new CertificateValidationException("Cant reach the CRL Url: " + crlURL, e); - } else { - if (log.isDebugEnabled()) { - log.debug("Cant reach CRL Url: " + crlURL + ". Retrying to connect - attempt " + retryCount); - } - return downloadCRLFromWeb(crlURL, --retryCount, peerCert, issuerCert, - certificateRevocationProxyEnabled, certificateRevocationProxyHost, - certificateRevocationProxyPort); - } - } catch (CertificateException e) { - throw new CertificateValidationException("Error when generating certificate factory.", e); - } catch (CRLException e) { - throw new CertificateValidationException("Cannot generate X509CRL from the stream data", e); - } catch (OpenBankingException e) { - throw new CertificateValidationException("Error when creating http client.", e); - } - return x509CRL; - } - - private static RevocationStatus getRevocationStatusFromCRL(X509CRL x509CRL, X509Certificate peerCert) { - - if (x509CRL.isRevoked(peerCert)) { - return RevocationStatus.REVOKED; - } else { - return RevocationStatus.GOOD; - } - } - - private static byte[] getCRLDPExtensionValue(X509Certificate cert) { - - //DER-encoded octet string of the extension value for CRLDistributionPoints identified by the passed-in oid - return cert.getExtensionValue(Extension.cRLDistributionPoints.getId()); - } - - private static CRLDistPoint getCrlDistPoint(byte[] crlDPExtensionValue) throws CertificateValidationException { - - //crlDPExtensionValue is encoded in ASN.1 format - //DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690, 2002, specification. - //ASN.1 encoding rules can be used to encode any data object into a binary file. Read the object in octets. - CRLDistPoint distPoint; - try (ASN1InputStream crlDPEx = new ASN1InputStream(crlDPExtensionValue); - ASN1InputStream asn1InOctets = - new ASN1InputStream(((DEROctetString) (crlDPEx).readObject()).getOctets())) { - //Get Input stream in octets - ASN1Primitive crlDERObject = asn1InOctets.readObject(); - distPoint = CRLDistPoint.getInstance(crlDERObject); - } catch (IOException e) { - throw new CertificateValidationException("Cannot read certificate to get CRL urls", e); - } - return distPoint; - } - - private static List getCrlUrlsFromDistPoint(CRLDistPoint distPoint) { - - List crlUrls = new ArrayList<>(); - //Loop through ASN1Encodable DistributionPoints - for (DistributionPoint dp : distPoint.getDistributionPoints()) { - //get ASN1Encodable DistributionPointName - DistributionPointName dpn = dp.getDistributionPoint(); - if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { - //Create ASN1Encodable General Names - GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); - // Look for a URI - for (GeneralName genName : genNames) { - if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { - //DERIA5String contains an ascii string. - //A IA5String is a restricted character string type in the ASN.1 notation - String url = DERIA5String.getInstance(genName.getName()).getString().trim(); - crlUrls.add(url); - } - } - } - } - return crlUrls; - } - - /** - * Checks revocation status (Good, Revoked) of the peer certificate. - * - * @param peerCert peer certificate - * @param issuerCert issuer certificate of the peer - * @return revocation status of the peer certificate - * @throws CertificateValidationException certificateValidationException - */ - @Override - public RevocationStatus checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert) - throws CertificateValidationException { - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = TPPCertValidatorDataHolder.getInstance(); - - final boolean isCertificateRevocationProxyEnabled = tppCertValidatorDataHolder - .isCertificateRevocationProxyEnabled(); - final int certificateRevocationProxyPort = tppCertValidatorDataHolder - .getCertificateRevocationProxyPort(); - final String certificateRevocationProxyHost = tppCertValidatorDataHolder - .getCertificateRevocationProxyHost(); - - List crlUrls = getCRLUrls(peerCert); - return getCRLRevocationStatus(peerCert, issuerCert, retryCount, crlUrls, isCertificateRevocationProxyEnabled, - certificateRevocationProxyHost, certificateRevocationProxyPort); - } - - @Override - public int getRetryCount() { - - return retryCount; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/OCSPValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/OCSPValidator.java deleted file mode 100644 index 8f0269b1..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/OCSPValidator.java +++ /dev/null @@ -1,416 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.revocation; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.impl.client.CloseableHttpClient; -import org.bouncycastle.asn1.ASN1IA5String; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers; -import org.bouncycastle.asn1.ocsp.OCSPResponseStatus; -import org.bouncycastle.asn1.x509.AccessDescription; -import org.bouncycastle.asn1.x509.AuthorityInformationAccess; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.ocsp.BasicOCSPResp; -import org.bouncycastle.cert.ocsp.CertificateID; -import org.bouncycastle.cert.ocsp.CertificateStatus; -import org.bouncycastle.cert.ocsp.OCSPException; -import org.bouncycastle.cert.ocsp.OCSPReq; -import org.bouncycastle.cert.ocsp.OCSPReqBuilder; -import org.bouncycastle.cert.ocsp.OCSPResp; -import org.bouncycastle.cert.ocsp.SingleResp; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.operator.DigestCalculatorProvider; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.security.Security; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -/** - * This is used to verify a certificate is revoked or not by using the Online Certificate Status Protocol published - * by the CA. - */ -public class OCSPValidator implements RevocationValidator { - - private static final Log log = LogFactory.getLog(OCSPValidator.class); - - private static final String BC = "BC"; - private final int retryCount; - private static int httpConnectTimeout; - private static int httpConnectionRequestTimeout; - private static int httpSocketTimeout; - - public OCSPValidator(int retryCount) { - - this.retryCount = retryCount; - } - - public OCSPValidator(int retryCount, int httpConnectTimeout, int httpConnectionRequestTimeout, - int httpSocketTimeout) { - - this.retryCount = retryCount; - OCSPValidator.httpConnectTimeout = httpConnectTimeout; - OCSPValidator.httpConnectionRequestTimeout = httpConnectionRequestTimeout; - OCSPValidator.httpSocketTimeout = httpSocketTimeout; - } - - /** - * Authority Information Access (AIA) is a non-critical extension in an X509 Certificate. This contains the - * URL of the OCSP endpoint if one is available. - * - * @param cert is the certificate - * @return a list of URLs in AIA extension of the certificate which will hopefully contain an OCSP endpoint - * @throws CertificateValidationException certificateValidationException - */ - public static List getAIALocations(X509Certificate cert) throws CertificateValidationException { - - List ocspUrlList; - byte[] aiaExtensionValue = getAiaExtensionValue(cert); - if (aiaExtensionValue == null) { - throw new CertificateValidationException("Certificate with serial num: " + - cert.getSerialNumber() + " doesn't have Authority Information Access points"); - } - AuthorityInformationAccess authorityInformationAccess = getAuthorityInformationAccess(aiaExtensionValue); - ocspUrlList = getOcspUrlsFromAuthorityInfoAccess(authorityInformationAccess); - - if (ocspUrlList.isEmpty()) { - throw new CertificateValidationException("Cant get OCSP urls from certificate with serial num: " + - cert.getSerialNumber()); - } - - return ocspUrlList; - } - - /** - * This method generates an OCSP Request to be sent to an OCSP endpoint. - * - * @param issuerCert is the Certificate of the Issuer of the peer certificate we are interested in - * @param serialNumber of the peer certificate - * @return generated OCSP request - * @throws CertificateValidationException certificateRevocationValidationException - */ - private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) - throws CertificateValidationException { - - // Add provider BC - Security.addProvider(new BouncyCastleProvider()); - try { - - byte[] issuerCertEnc = issuerCert.getEncoded(); - X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc); - DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); - - // CertID structure is used to uniquely identify certificates that are the subject of - // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560 - CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, - serialNumber); - - // basic request generation with nonce - OCSPReqBuilder builder = new OCSPReqBuilder(); - builder.addRequest(id); - - // create details for nonce extension. The nonce extension is used to bind a request to a response to - // prevent replay attacks. As the name implies, the nonce value is something that the client should only - // use once within a reasonably small period. - BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); - - // create the request Extension - builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, - new DEROctetString(nonce.toByteArray())))); - - return builder.build(); - } catch (CertificateEncodingException | IOException | OCSPException | OperatorCreationException e) { - throw new CertificateValidationException("Cannot generate OSCP Request with the given certificate with " + - "serial num: " + serialNumber, e); - } - } - - /** - * Get revocation status of a certificate using OCSP Url. - * - * @param peerCert peer certificate - * @param issuerCert issuer certificate of peer - * @param retryCount retry count to connect to OCSP Url and get the OCSP response - * @param locations AIA locations - * @param certificateRevocationProxyEnabled whether certificate revocation proxy enabled in the config - * @param certificateRevocationProxyHost certificate revocation proxy host - * @param certificateRevocationProxyPort certificate revocation proxy port - * @return Revocation status of the certificate - * @throws CertificateValidationException certificateValidationException - */ - public static RevocationStatus getOCSPRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert, - int retryCount, List locations, - boolean certificateRevocationProxyEnabled, - String certificateRevocationProxyHost, - int certificateRevocationProxyPort) - throws CertificateValidationException { - - OCSPReq request = generateOCSPRequest(issuerCert, peerCert.getSerialNumber()); - for (String serviceUrl : locations) { - SingleResp[] responses; - try { - if (log.isDebugEnabled()) { - log.debug("Trying to get OCSP Response from : " + serviceUrl); - } - OCSPResp ocspResponse = getOCSPResponse(serviceUrl, request, retryCount, - certificateRevocationProxyEnabled, certificateRevocationProxyHost, - certificateRevocationProxyPort); - if (OCSPResponseStatus.SUCCESSFUL != ocspResponse.getStatus()) { - log.debug("OCSP Response is not successfully received."); - continue; - } - - BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); - responses = (basicResponse == null) ? null : basicResponse.getResponses(); - } catch (OCSPException | CertificateValidationException e) { - // On any error, consider the other AIA locations as well. - log.debug("Certificate revocation check failed due to an exception", e); - continue; - } - - if (responses != null && responses.length == 1) { - return getRevocationStatusFromOCSP(responses[0]); - } - } - throw new CertificateValidationException("Cant get Revocation Status from OCSP using any of the OCSP Urls " + - "for certificate with serial num:" + peerCert.getSerialNumber()); - } - - private static List getOcspUrlsFromAuthorityInfoAccess(AuthorityInformationAccess - authorityInformationAccess) { - - List ocspUrlList = new ArrayList<>(); - AccessDescription[] accessDescriptions; - if (authorityInformationAccess != null) { - accessDescriptions = authorityInformationAccess.getAccessDescriptions(); - for (AccessDescription accessDescription : accessDescriptions) { - - GeneralName gn = accessDescription.getAccessLocation(); - if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) { - ASN1IA5String str = ASN1IA5String.getInstance(gn.getName()); - String accessLocation = str.getString(); - ocspUrlList.add(accessLocation); - } - } - } - return ocspUrlList; - } - - private static AuthorityInformationAccess getAuthorityInformationAccess(byte[] aiaExtensionValue) - throws CertificateValidationException { - - AuthorityInformationAccess authorityInformationAccess; - try (ASN1InputStream asn1InputStream = - new ASN1InputStream(((DEROctetString) - (new ASN1InputStream(new ByteArrayInputStream(aiaExtensionValue)).readObject())) - .getOctets())) { - authorityInformationAccess = AuthorityInformationAccess.getInstance(asn1InputStream.readObject()); - } catch (IOException e) { - throw new CertificateValidationException("Cannot read certificate to get OSCP urls", e); - } - return authorityInformationAccess; - } - - private static byte[] getAiaExtensionValue(X509Certificate cert) { - - //Gets the DER-encoded OCTET string for the extension value for Authority information access Points - return cert.getExtensionValue(Extension.authorityInfoAccess.getId()); - } - - /** - * Gets an ASN.1 encoded OCSP response (as defined in RFC 2560) from the given service URL. Currently supports - * only HTTP. - * - * @param serviceUrl URL of the OCSP endpoint. - * @param request an OCSP request object. - * @param certificateRevocationProxyEnabled whether certificate revocation proxy enabled in the config - * @param certificateRevocationProxyHost certificate revocation proxy host - * @param certificateRevocationProxyPort certificate revocation proxy port - * @return OCSP response encoded in ASN.1 structure. - * @throws CertificateValidationException certificateValidationException - */ - private static OCSPResp getOCSPResponse(String serviceUrl, OCSPReq request, int retryCount, - boolean certificateRevocationProxyEnabled, - String certificateRevocationProxyHost, - int certificateRevocationProxyPort) - throws CertificateValidationException { - - OCSPResp ocspResp = null; - if (log.isDebugEnabled()) { - log.debug("Certificate revocation check proxy enabled: " + certificateRevocationProxyEnabled); - } - try (CloseableHttpClient client = HTTPClientUtils.getHttpsClient()) { - HttpPost httpPost = new HttpPost(serviceUrl); - - if (certificateRevocationProxyEnabled) { - log.debug("Setting certificate revocation proxy started."); - if (certificateRevocationProxyHost == null || certificateRevocationProxyHost.trim().isEmpty()) { - String message = "Certificate revocation proxy server host is not configured. Please do set the " + - "'CertificateManagement -> CertificateRevocationProxy -> ProxyHost' file"; - log.error(message); - throw new CertificateValidationException(message); - } - - if (log.isDebugEnabled()) { - log.debug("Certificate revocation proxy: " + certificateRevocationProxyHost + ":" + - certificateRevocationProxyPort); - } - HttpHost proxy = new HttpHost(certificateRevocationProxyHost, certificateRevocationProxyPort); - RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); - httpPost.setConfig(config); - log.debug("Setting certificate revocation proxy finished."); - } - - // adding request timeout configurations - RequestConfig timeoutRequestConfig; - if (httpPost.getConfig() == null) { - httpPost.setConfig(RequestConfig.custom().build()); - } - timeoutRequestConfig = RequestConfig.copy(httpPost.getConfig()) - .setConnectTimeout(httpConnectTimeout) - .setConnectionRequestTimeout(httpConnectionRequestTimeout) - .setSocketTimeout(httpSocketTimeout) - .build(); - httpPost.setConfig(timeoutRequestConfig); - // add debug logs - if (log.isDebugEnabled()) { - log.debug("OCSP request timeout configurations: " + "httpConnectTimeout: " + httpConnectTimeout + - ", httpConnectionRequestTimeout: " + httpConnectionRequestTimeout + ", httpSocketTimeout: " + - httpSocketTimeout); - } - - setRequestProperties(request.getEncoded(), httpPost); - HttpResponse httpResponse = client.execute(httpPost); - - //Check errors in response, if response status code is not 200 (success) range, throws exception - // eg: if response code is 200 (success) or 201 (accepted) return true, - // if response code is 404 (not found) or 500 throw exception - if (httpResponse.getStatusLine().getStatusCode() / 100 != 2) { - throw new CertificateValidationException("Error getting ocsp response." + - "Response code is " + httpResponse.getStatusLine().getStatusCode()); - } - InputStream in = httpResponse.getEntity().getContent(); - ocspResp = new OCSPResp(in); - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug("Certificate revocation check failed due to an exception", e); - } - if (retryCount == 0) { - throw new CertificateValidationException("Cannot get ocspResponse from url: " - + serviceUrl, e); - } else { - log.info("Cant reach URI: " + serviceUrl + ". Retrying to connect - attempt " + retryCount); - return getOCSPResponse(serviceUrl, request, --retryCount, certificateRevocationProxyEnabled, - certificateRevocationProxyHost, certificateRevocationProxyPort); - } - } catch (OpenBankingException e) { - throw new CertificateValidationException("Error when creating http client.", e); - } - return ocspResp; - } - - private static void setRequestProperties(byte[] message, HttpPost httpPost) { - - httpPost.addHeader(CertificateValidationUtils.HTTP_CONTENT_TYPE, - CertificateValidationUtils.HTTP_CONTENT_TYPE_OCSP); - httpPost.addHeader(CertificateValidationUtils.HTTP_ACCEPT, - CertificateValidationUtils.HTTP_ACCEPT_OCSP); - - httpPost.setEntity(new ByteArrayEntity(message, - ContentType.create(CertificateValidationUtils.CONTENT_TYPE))); - } - - private static RevocationStatus getRevocationStatusFromOCSP(SingleResp resp) - throws CertificateValidationException { - - Object status = resp.getCertStatus(); - if (status == CertificateStatus.GOOD) { - return RevocationStatus.GOOD; - } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) { - return RevocationStatus.REVOKED; - } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) { - return RevocationStatus.UNKNOWN; - } - throw new CertificateValidationException("Cant recognize Certificate Status"); - } - - /** - * Check revocation status (Good, Revoked, Unknown) of the peer certificate. - * - * @param peerCert peer certificate - * @param issuerCert issuer certificate of the peer - * @return revocation status of the peer certificate - * @throws CertificateValidationException certificateValidationException - */ - @Override - public RevocationStatus checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert) - throws CertificateValidationException { - - if (issuerCert == null) { - throw new CertificateValidationException("Issuer Certificate is not available for " + - "OCSP validation"); - } - List locations = getAIALocations(peerCert); - if (log.isDebugEnabled()) { - log.debug("Peer certificate AIA locations: " + locations); - } - TPPCertValidatorDataHolder tppCertValidatorDataHolder = TPPCertValidatorDataHolder.getInstance(); - - final boolean isCertificateRevocationProxyEnabled = tppCertValidatorDataHolder - .isCertificateRevocationProxyEnabled(); - final int certificateRevocationProxyPort = tppCertValidatorDataHolder - .getCertificateRevocationProxyPort(); - final String certificateRevocationProxyHost = tppCertValidatorDataHolder - .getCertificateRevocationProxyHost(); - - return getOCSPRevocationStatus(peerCert, issuerCert, retryCount, locations, isCertificateRevocationProxyEnabled - , certificateRevocationProxyHost, certificateRevocationProxyPort); - } - - @Override - public int getRetryCount() { - - return retryCount; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/RevocationValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/RevocationValidator.java deleted file mode 100644 index fa8f707f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/RevocationValidator.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.executor.revocation; - - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; - -import java.security.cert.X509Certificate; - -/** - * This interface needs to be implemented by any certificate revocation validator. - */ -public interface RevocationValidator { - - /** - * Checks revocation status of the peer certificate. - * - * @param peerCert peer certificate - * @param issuerCert issuer certificate - * @return revocation status - * @throws CertificateValidationException when an error occurs while checking the revocation status - */ - RevocationStatus checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert) - throws CertificateValidationException; - - /** - * Get revocation validator retry count. - * - * @return validator retry count - */ - int getRetryCount(); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/CertValidationService.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/CertValidationService.java deleted file mode 100644 index 84897229..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/CertValidationService.java +++ /dev/null @@ -1,245 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.TPPValidationException; -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.CertificateContent; -import com.wso2.openbanking.accelerator.common.util.eidas.certificate.extractor.CertificateContentExtractor; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.cache.TppValidationCache; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; -import com.wso2.openbanking.accelerator.gateway.executor.revocation.RevocationValidator; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * CertRevocationValidation Service class is responsible for validating client certificates. - */ -public class CertValidationService { - - private static final Log log = LogFactory.getLog(CertValidationService.class); - private static CertValidationService certValidationService; - - private CertValidationService() { - - } - - /** - * Singleton getInstance method to create only one object. - * - * @return CertValidationService object - */ - public static synchronized CertValidationService getInstance() { - if (certValidationService == null) { - certValidationService = new CertValidationService(); - } - - return certValidationService; - } - - - /** - * Validate the certificate revocation status. - * - * @param peerCertificate X509Certificate - * @param issuerCertificate X509Certificate - * @return true if the certificate is not revoked - * @deprecated use {@link #verify(X509Certificate, X509Certificate, int, int, int, int)} instead - */ - @Deprecated - public boolean verify(X509Certificate peerCertificate, X509Certificate issuerCertificate, int retryCount) { - - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(); - RevocationValidatorFactory revocationValidatorFactory = new RevocationValidatorFactory(); - Map revocationValidators = openBankingConfigParser.getCertificateRevocationValidators(); - - // OCSP validation is checked first as it is faster than the CRL validation. Moving to CRL validation - // only if an error occurs during the OCSP validation. - RevocationValidator[] validators = revocationValidators - .entrySet() - .stream() - .sorted(Map.Entry.comparingByKey()) - .map(Map.Entry::getValue) - .map(type -> revocationValidatorFactory.getValidator(type, retryCount)) - .filter(Objects::nonNull) - .toArray(RevocationValidator[]::new); - - for (RevocationValidator validator : validators) { - RevocationStatus revocationStatus = isRevoked(validator, peerCertificate, issuerCertificate); - if (RevocationStatus.GOOD == revocationStatus) { - return true; - } else if (RevocationStatus.REVOKED == revocationStatus) { - return false; - } - } - log.error("Unable to verify certificate revocation information"); - return false; - } - - /** - * Validate the certificate revocation status. - * - * @param peerCertificate X509Certificate - * @param issuerCertificate X509Certificate - * @param retryCount retry count - * @param connectTimeout connect timeout - * @param connectionRequestTimeout connection request timeout - * @param socketTimeout socket timeout - * @return true if the certificate is not revoked - */ - public boolean verify(X509Certificate peerCertificate, X509Certificate issuerCertificate, int retryCount, - int connectTimeout, int connectionRequestTimeout, int socketTimeout) { - - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(); - RevocationValidatorFactory revocationValidatorFactory = new RevocationValidatorFactory(); - Map revocationValidators = openBankingConfigParser.getCertificateRevocationValidators(); - - // OCSP validation is checked first as it is faster than the CRL validation. Moving to CRL validation - // only if an error occurs during the OCSP validation. - RevocationValidator[] validators = revocationValidators - .entrySet() - .stream() - .sorted(Map.Entry.comparingByKey()) - .map(Map.Entry::getValue) - .map(type -> revocationValidatorFactory.getValidator(type, retryCount, connectTimeout, - connectionRequestTimeout, socketTimeout)) - .filter(Objects::nonNull) - .toArray(RevocationValidator[]::new); - - for (RevocationValidator validator : validators) { - RevocationStatus revocationStatus = isRevoked(validator, peerCertificate, issuerCertificate); - if (RevocationStatus.GOOD == revocationStatus) { - return true; - } else if (RevocationStatus.REVOKED == revocationStatus) { - return false; - } - } - log.error("Unable to verify certificate revocation information"); - return false; - } - - private RevocationStatus isRevoked(RevocationValidator validator, X509Certificate peerCertificate, - X509Certificate issuerCertificate) { - - if (log.isDebugEnabled()) { - log.debug("X509 Certificate validation with " + validator.getClass().getSimpleName()); - } - try { - return validator.checkRevocationStatus(peerCertificate, issuerCertificate); - } catch (CertificateValidationException e) { - log.warn("Unable to validate certificate revocation with " + - validator.getClass().getSimpleName(), e); - return RevocationStatus.UNKNOWN; - } - } - - public boolean validateTppRoles(X509Certificate tppCertificate, List requiredPSD2Roles) - throws TPPValidationException, CertificateValidationException { - - if (TPPCertValidatorDataHolder.getInstance().isTppValidationEnabled()) { - - String tppValidationServiceImplClassPath = - TPPCertValidatorDataHolder.getInstance().getTPPValidationServiceImpl(); - if (StringUtils.isNotBlank(tppValidationServiceImplClassPath)) { - TPPValidationService tppValidationService = - TPPCertValidatorDataHolder.getInstance().getTppValidationService(); - - if (tppValidationService != null) { - - // Initializing certificate cache and cache key - TppValidationCache tppValidationServiceCache = TppValidationCache.getInstance(); - String tppValidationCacheKeyStr = tppValidationService.getCacheKey(tppCertificate, - requiredPSD2Roles, Collections.emptyMap()); - GatewayCacheKey tppValidationCacheKey = GatewayCacheKey.of(tppValidationCacheKeyStr); - - // Executing TPP role validation process or retrieve last status from cache - if (tppValidationServiceCache.getFromCache(tppValidationCacheKey) != null) { - // previous result is present in cache, return result - return tppValidationServiceCache.getFromCache(tppValidationCacheKey); - } else { - final boolean result = tppValidationService - .validate(tppCertificate, requiredPSD2Roles, Collections.emptyMap()); - if (result) { - // Adding result to cache - tppValidationServiceCache.addToCache(tppValidationCacheKey, true); - return true; - } - } - } else { - throw new TPPValidationException( - "Unable to find the implementation class for TPP validation service"); - } - } else { - throw new TPPValidationException("TPP validation service " + - "class implementation is empty"); - } - } else if (TPPCertValidatorDataHolder.getInstance().isPsd2RoleValidationEnabled()) { - return isRequiredRolesMatchWithScopes(tppCertificate, requiredPSD2Roles); - } else { - throw new TPPValidationException("Both TPP validation and PSD2 role validation services are disabled"); - } - return false; - } - - /** - * Validate whether the psd2 roles match with the scopes. - * - * @param tppCertificate eidas certificate with roles - * @param requiredPSD2Roles client requested roles - * @return true if all required values are present in the certificate - */ - private boolean isRequiredRolesMatchWithScopes(X509Certificate tppCertificate - , List requiredPSD2Roles) throws CertificateValidationException, TPPValidationException { - - - // Extract the certContent from the eidas certificate (i.e. roles, authorization number, etc) - CertificateContent certContent = CertificateContentExtractor.extract(tppCertificate); - - if (log.isDebugEnabled()) { - log.debug("The TPP is requesting roles: " + requiredPSD2Roles); - log.debug("Provided PSD2 eIDAS certificate" + - " contains the role: " + certContent.getPspRoles()); - } - - // Validate whether the eIDAS certificate contains the required roles that matches with the token scopes. - for (PSD2RoleEnum requiredRole : requiredPSD2Roles) { - if (!certContent.getPspRoles().contains(requiredRole.name())) { - // Return false if any one of the roles that are bound to the scope is not present in the PSD2 - // role list of the client eIDAS certificate. - final String errorMsg = "The PSD2 eIDAS certificate does not contain the required role " - + requiredRole.toString(); - - log.error(errorMsg); - throw new TPPValidationException(errorMsg); - } - } - return true; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/RevocationValidatorFactory.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/RevocationValidatorFactory.java deleted file mode 100644 index ee6d5c1c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/RevocationValidatorFactory.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.service; - -import com.wso2.openbanking.accelerator.gateway.executor.revocation.CRLValidator; -import com.wso2.openbanking.accelerator.gateway.executor.revocation.OCSPValidator; -import com.wso2.openbanking.accelerator.gateway.executor.revocation.RevocationValidator; - -/** - * RevocationValidatorFactory is used to get a object of type RevocationValidator. - */ -public class RevocationValidatorFactory { - - private static final String OCSP_VALIDATOR = "OCSP"; - private static final String CRL_VALIDATOR = "CRL"; - - - /** - * Get a object of type RevocationValidator. - * - * @param validatorType name of the required RevocationValidator type - * @param retryCount retry count to connect to revocation validator endpoint and get the response - * @return RevocationValidator type object (OCSP/CRL) - * @deprecated use {@link #getValidator(String, int, int, int, int)} instead - */ - @Deprecated - public RevocationValidator getValidator(String validatorType, int retryCount) { - if (OCSP_VALIDATOR.equalsIgnoreCase(validatorType)) { - return new OCSPValidator(retryCount); - } else if (CRL_VALIDATOR.equalsIgnoreCase(validatorType)) { - return new CRLValidator(retryCount); - } else { - return null; - } - } - - /** - * Get a object of type RevocationValidator. - * - * @param validatorType name of the required RevocationValidator type. - * @param retryCount retry count to connect to revocation validator endpoint and get the response. - * @param connectTimeout timeout for connecting to revocation validator endpoint. - * @param connectionRequestTimeout timeout for getting a connection from the connection manager. - * @param socketTimeout timeout for getting the response from the revocation validator endpoint. - * @return - */ - public RevocationValidator getValidator(String validatorType, int retryCount, int connectTimeout, - int connectionRequestTimeout, int socketTimeout) { - if (OCSP_VALIDATOR.equalsIgnoreCase(validatorType)) { - return new OCSPValidator(retryCount, connectTimeout, connectionRequestTimeout, socketTimeout); - } else if (CRL_VALIDATOR.equalsIgnoreCase(validatorType)) { - return new CRLValidator(retryCount, connectTimeout, connectionRequestTimeout, socketTimeout); - } else { - return null; - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/TPPValidationService.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/TPPValidationService.java deleted file mode 100644 index 866cc711..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/service/TPPValidationService.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.executor.service; - -import com.wso2.openbanking.accelerator.common.exception.TPPValidationException; -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; - -import java.security.cert.X509Certificate; -import java.util.List; -import java.util.Map; - -/** - * Manager interface to be used for TPP validation using external services. - */ -public interface TPPValidationService { - - /** - * Validate the status of a TPP. - * - * @param peerCertificate Certificate of the TPP - * @param requiredPSD2Roles Roles that are required to be validated with the TPP validation service according to - * the current flow - * @param metadata Metadata information - * @return - * @throws TPPValidationException - */ - boolean validate(X509Certificate peerCertificate, - List requiredPSD2Roles, Map metadata) - throws TPPValidationException; - - /** - * Get the cache key used for the caching the response. Implementation should return an appropriate ID that is - * unique to the API flow. - * - * @param peerCertificate Certificate of the TPP - * @param requiredPSD2Roles Roles that are required to be validated with the TPP validation service according to - * the current flow - * @param metadata Metadata information - * @return - * @throws TPPValidationException - */ - String getCacheKey(X509Certificate peerCertificate, - List requiredPSD2Roles, Map metadata) - throws TPPValidationException; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/util/CertificateValidationUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/util/CertificateValidationUtils.java deleted file mode 100644 index f1238d1e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/executor/util/CertificateValidationUtils.java +++ /dev/null @@ -1,300 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.util; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.InvalidKeyException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Date; -import java.util.Enumeration; -import java.util.Optional; - -/** - * Utility class containing certificate util methods. - */ -public class CertificateValidationUtils { - - public static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; - public static final String END_CERT = "-----END CERTIFICATE-----"; - public static final String X509_CERT_INSTANCE_NAME = "X.509"; - public static final String HTTP_CONTENT_TYPE = "Content-Type"; - public static final String HTTP_CONTENT_TYPE_OCSP = "application/ocsp-request"; - public static final String HTTP_ACCEPT = "Accept"; - public static final String HTTP_ACCEPT_OCSP = "application/ocsp-response"; - public static final String CONTENT_TYPE = "application/json"; - public static final String TRUSTSTORE_LOCATION_CONF_KEY = "Security.TrustStore.Location"; - public static final String TRUSTSTORE_PASS_CONF_KEY = "Security.TrustStore.Password"; - private static final Log LOG = LogFactory.getLog(CertificateValidationUtils.class); - private static KeyStore trustStore = null; - - private CertificateValidationUtils() { - // Adding a private constructor to hide the implicit public one. - } - - /** - * @deprecated use com.wso2.openbanking.accelerator.common.util.CertificateUtils.isExpired() instead - */ - @Deprecated - public static boolean isExpired(X509Certificate peerCertificate) { - try { - peerCertificate.checkValidity(); - } catch (CertificateException e) { - LOG.error("Certificate with the serial number " + - peerCertificate.getSerialNumber() + " issued by the CA " + - peerCertificate.getIssuerDN().toString() + " is expired. Caused by, " + e.getMessage()); - return true; - } - return false; - } - - /** - * Get issuer certificate from the truststore. - * - * @param peerCertificate peer certificate - * @return certificate issuer of the peer certificate - * @throws CertificateValidationException when unable to validate the certificate - */ - public static X509Certificate getIssuerCertificateFromTruststore(X509Certificate peerCertificate) - throws CertificateValidationException { - - KeyStore loadedTrustStore = getTrustStore(); - if (loadedTrustStore == null) { - throw new CertificateValidationException("Client truststore has not been initialized"); - } - - return retrieveCertificateFromTruststore(peerCertificate, loadedTrustStore); - - } - - /** - * Get the truststore. This methods needs to be synchronized with the loadTrustStore() method - * - * @return instance of the truststore - */ - public static synchronized KeyStore getTrustStore() { - return trustStore; - } - - /** - * Get certificate from truststore. - * - * @param peerCertificate peer certificate - * @param loadedTrustStore truststore - * @return certificate retrieved from truststore - * @throws CertificateValidationException when unable to validate the certificate - */ - public static X509Certificate retrieveCertificateFromTruststore( - X509Certificate peerCertificate, KeyStore loadedTrustStore) throws CertificateValidationException { - - Enumeration enumeration; - java.security.cert.X509Certificate certificate; - try { - // Get aliases of all the certificates in the truststore. - enumeration = loadedTrustStore.aliases(); - } catch (KeyStoreException e) { - throw new CertificateValidationException("Error while retrieving aliases from keystore", e); - } - - // As there is no any specific way to query the issuer certificate from the truststore, public keys of all the - // certificates in the truststore are validated against the signature of the peer certificate to identify the - // issuer. - if (enumeration != null) { - while (enumeration.hasMoreElements()) { - String alias = null; - try { - alias = (String) enumeration.nextElement(); - certificate = (java.security.cert.X509Certificate) loadedTrustStore.getCertificate(alias); - } catch (KeyStoreException e) { - throw new CertificateValidationException("Unable to read the certificate from truststore with " + - "the alias: " + alias, e); - } - try { - peerCertificate.verify(certificate.getPublicKey()); - LOG.debug("Valid issuer certificate found in the client truststore"); - return certificate; - } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | - NoSuchProviderException | SignatureException e) { - // Unable to verify the signature. Check with the next certificate. - } - } - } else { - throw new CertificateValidationException("Unable to read the certificate aliases from the truststore"); - } - throw new CertificateValidationException("Unable to find the immediate issuer from the truststore of the " + - "certificate with the serial number " + peerCertificate.getSerialNumber() + " issued by the CA " + - peerCertificate.getIssuerDN().toString()); - } - - /** - * Loads the Truststore. - * - * @param trustStorePassword truststore password - */ - @SuppressFBWarnings("PATH_TRAVERSAL_IN") - // Suppressed content - Files.newInputStream(Paths.get(trustStorePath))) - // Suppression reason - False Positive : trustStorePath is obtained from deployment.toml. So it can be marked - // as a trusted filepath - // Suppressed warning count - 1 - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - public static synchronized void loadTrustStore(char[] trustStorePassword) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - - String trustStorePath = ServerConfiguration.getInstance() - .getFirstProperty(CertificateValidationUtils.TRUSTSTORE_LOCATION_CONF_KEY); - try (InputStream inputStream = Files.newInputStream(Paths.get(trustStorePath))) { - trustStore = KeyStore.getInstance(OpenBankingConstants.TRUSTSTORE_CONF_TYPE_DEFAULT); - trustStore.load(inputStream, trustStorePassword); - } - } - - - /** - * Loads the Truststore. - * - * This method is deprecated as it allows custom absolute file paths which could result in - * path traversal attacks. Do not use this method unless the custom path is trusted. - * @param trustStorePath truststore path - * @param trustStorePassword truststore password - */ - @SuppressFBWarnings("PATH_TRAVERSAL_IN") - // Suppressed content - dataHolder.getKeyStoreLocation() - // Suppression reason - False Positive : Keystore location is obtained from deployment.toml. So it can be marked - // as a trusted filepath - // Suppressed warning count - 1 - @Deprecated - public static synchronized void loadTrustStore(String trustStorePath, char[] trustStorePassword) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - - try (InputStream inputStream = Files.newInputStream(Paths.get(trustStorePath))) { - trustStore = KeyStore.getInstance(OpenBankingConstants.TRUSTSTORE_CONF_TYPE_DEFAULT); - trustStore.load(inputStream, trustStorePassword); - } - } - - public static void handleExecutorErrors(CertificateValidationException e - , OBAPIRequestContext obapiRequestContext) { - OpenBankingExecutorError error = new OpenBankingExecutorError(e.getErrorCode(), e.getMessage(), - e.getErrorPayload(), OpenBankingErrorCodes.UNAUTHORIZED_CODE); - handleExecutorErrors(error, obapiRequestContext); - } - - public static void handleExecutorErrors(OpenBankingExecutorError error - , OBAPIRequestContext obapiRequestContext) { - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - - obapiRequestContext.setError(true); - obapiRequestContext.setErrors(executorErrors); - } - - /** - * Convert javax.security.cert.X509Certificate to java.security.cert.X509Certificate. - * - * @param cert the certificate to be converted - * @return java.security.cert.X509Certificate type certificate - * @deprecated use convertCert(javax.security.cert.X509Certificate cert) method instead. - */ - @Deprecated - public static Optional convert(javax.security.cert.X509Certificate cert) { - - try { - return convertCert(cert); - } catch (CertificateException e) { - // Not logging the errors again as it is done in the convertCert method - return Optional.empty(); - } - } - - /** - * Convert javax.security.cert.X509Certificate to java.security.cert.X509Certificate - * This method will also handle the exceptions that could occur in the process of converting the certificate. - * Will be having the above convert method as well as it is a public method and will deprecate it gradually. - * - * @param cert the certificate to be converted - * @return java.security.cert.X509Certificate type certificate - * @throws CertificateException - */ - public static Optional convertCert(javax.security.cert.X509Certificate cert) - throws CertificateException { - - if (cert != null) { - try { - byte[] encoded = cert.getEncoded(); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encoded); - java.security.cert.CertificateFactory certificateFactory - = java.security.cert.CertificateFactory.getInstance(X509_CERT_INSTANCE_NAME); - return Optional.of((java.security.cert.X509Certificate) certificateFactory.generateCertificate( - byteArrayInputStream)); - } catch (javax.security.cert.CertificateEncodingException e) { - String errorMsg = "Error while decoding the certificate "; - LOG.error(errorMsg, e); - throw new CertificateException(errorMsg, e); - } catch (java.security.cert.CertificateException e) { - String errorMsg = "Error while generating the certificate "; - LOG.error(errorMsg, e); - throw new CertificateException(errorMsg, e); - } - } else { - return Optional.empty(); - } - } - - /** - * Converts java.security.cert.Certificate to java.security.cert.X509Certificate. - * - * @param certificate java.security.cert.Certificate which needs conversion - * @return java.security.cert.X509Certificate - * @throws CertificateException thrown if an error occurs while converting - */ - public static Optional convertCertToX509Cert(Certificate certificate) - throws CertificateException { - - CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_INSTANCE_NAME); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certificate.getEncoded()); - return Optional.of((X509Certificate) cf.generateCertificate(byteArrayInputStream)); - } - - public static Date getNewDate() { - return new Date(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/handler/GatewayClientAuthenticationHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/handler/GatewayClientAuthenticationHandler.java deleted file mode 100644 index 0ffe6650..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/handler/GatewayClientAuthenticationHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. - *

- * This software is the property of WSO2 LLC. and its suppliers, if any. - * Dissemination of any information or reproduction of any material contained - * herein in any form is strictly forbidden, unless permitted by WSO2 expressly. - * You may not alter or remove any copyright or other notice from copies of this content. - */ - -package com.wso2.openbanking.accelerator.gateway.handler; - -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.axis2.context.MessageContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.rest.AbstractHandler; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.Map; - -/** - * Handler to send transport certificate as a header to identity server. - * Responds with an error if the transport certificate is not found or malformed. - */ -public class GatewayClientAuthenticationHandler extends AbstractHandler { - - private static final Log log = LogFactory.getLog(GatewayClientAuthenticationHandler.class); - - @Override - public boolean handleRequest(org.apache.synapse.MessageContext messageContext) { - - log.debug("Gateway Client Authentication Handler engaged"); - MessageContext ctx = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - X509Certificate x509Certificate = GatewayUtils.extractAuthCertificateFromMessageContext(ctx); - Map headers = (Map) ctx.getProperty(MessageContext.TRANSPORT_HEADERS); - - if (x509Certificate != null) { - log.debug("Valid certificate found in request"); - try { - String certificateHeader = GatewayDataHolder.getInstance().getClientTransportCertHeaderName(); - String encodedCert = GatewayUtils.getPEMEncodedCertificateString(x509Certificate); - if (GatewayDataHolder.getInstance().isUrlEncodeClientTransportCertHeaderEnabled()) { - log.debug("URL encoding pem encoded transport certificate"); - encodedCert = URLEncoder.encode(encodedCert, "UTF-8"); - } - headers.put(certificateHeader, encodedCert); - ctx.setProperty(MessageContext.TRANSPORT_HEADERS, headers); - if (log.isDebugEnabled()) { - log.debug(String.format("Added encoded transport certificate in header %s", certificateHeader)); - } - } catch (CertificateEncodingException | UnsupportedEncodingException e) { - log.error("Unable to encode client transport certificate", e); - GatewayUtils.returnSynapseHandlerJSONError(messageContext, OpenBankingErrorCodes.BAD_REQUEST_CODE, - GatewayUtils.getOAuth2JsonErrorBody(GatewayConstants.INVALID_REQUEST, - GatewayConstants.TRANSPORT_CERT_MALFORMED)); - } - } else { - log.debug(GatewayConstants.TRANSPORT_CERT_NOT_FOUND); - GatewayUtils.returnSynapseHandlerJSONError(messageContext, OpenBankingErrorCodes.BAD_REQUEST_CODE, - GatewayUtils.getOAuth2JsonErrorBody(GatewayConstants.INVALID_REQUEST, - GatewayConstants.TRANSPORT_CERT_NOT_FOUND)); - } - return true; - } - - @Override - public boolean handleResponse(org.apache.synapse.MessageContext messageContext) { - - return true; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/handler/JwsResponseSignatureHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/handler/JwsResponseSignatureHandler.java deleted file mode 100644 index 2cbcb347..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/handler/JwsResponseSignatureHandler.java +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.handler; - -import com.nimbusds.jose.JOSEException; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.synapse.AbstractSynapseHandler; -import org.apache.synapse.MessageContext; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.rest.RESTConstants; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Handler class for Signing Responses. - */ -public class JwsResponseSignatureHandler extends AbstractSynapseHandler { - - private static final Log log = LogFactory.getLog(JwsResponseSignatureHandler.class); - - private String xWso2ApiVersion = null; - private String xWso2ApiType = null; - private final String signatureHeaderName = getSignatureHeaderName(); - public static final String ERRORS_TAG = "errors"; - public static final String INTERNAL_SERVER_ERROR = "Internal server error"; - - /** - * Constructor for JwsResponseSignatureHandler. - */ - @Generated(message = "Ignoring since method contains no logics") - public JwsResponseSignatureHandler() { - - log.debug("Initializing JwsResponseSignatureHandler to append jws response signature."); - } - - /** - * Handle request message coming into the engine. - * - * @param messageContext incoming request message context - * @return whether mediation flow should continue - */ - @Override - @Generated(message = "Ignoring since method contains no logics") - public boolean handleRequestInFlow(MessageContext messageContext) { - - return true; - - } - - /** - * Handle request message going out from the engine. - * - * @param messageContext outgoing request message context - * @return whether mediation flow should continue - */ - @Override - @Generated(message = "Ignoring since method contains no logics") - public boolean handleRequestOutFlow(MessageContext messageContext) { - - return true; - } - - /** - * Handle response message coming into the engine. - * - * @param messageContext incoming response message context - * @return whether mediation flow should continue - */ - @Override - @Generated(message = "Ignoring since all cases are covered from other unit tests") - public boolean handleResponseInFlow(MessageContext messageContext) { - - return appendJwsSignatureToResponse(messageContext); - } - - /** - * Handle response message going out from the engine. - * - * @param messageContext outgoing response message context - * @return whether mediation flow should continue - */ - @Override - public boolean handleResponseOutFlow(MessageContext messageContext) { - - org.apache.axis2.context.MessageContext axis2MC = - ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); - if (messageContext.getEnvelope() != null && messageContext.getEnvelope().getBody() != null && - StringUtils.contains(messageContext.getEnvelope().getBody().toString(), - "Schema validation failed")) { - // Add jws header for schema errors, This is due to schema validation happens after responseInFlow. - // So we need to regenerate the jws for schema validation error responses. - return appendJwsSignatureToResponse(messageContext); - } else if (headers.containsKey(signatureHeaderName) && headers.get(signatureHeaderName) != null) { - return true; - } else { - // Add jws header, if it's not added yet. - return appendJwsSignatureToResponse(messageContext); - } - } - - /** - * Method to append Jws Signature to the response. - * - * @param messageContext response/request message context. - * @return jws signature response is successfully appended. - */ - private boolean appendJwsSignatureToResponse(MessageContext messageContext) { - - setXWso2ApiVersion((String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)); - setXWso2ApiType((String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT)); - - try { - boolean applicable = isApplicable(messageContext); - if (!applicable) { - log.debug("Signature generation is not applicable for this response"); - return true; - } else { - log.debug("Generating signature for the response"); - } - } catch (RuntimeException e) { - log.debug("Internal Server Error, Unable to append jws signature", e); - GatewayUtils.returnSynapseHandlerJSONError(messageContext, OpenBankingErrorCodes.SERVER_ERROR_CODE, - getFormattedSignatureHandlingErrorResponse(messageContext, OpenBankingErrorCodes.SERVER_ERROR_CODE, - INTERNAL_SERVER_ERROR, "Internal Server Error, Unable to append jws signature")); - } - - // Build the payload from messageContext. - org.apache.axis2.context.MessageContext axis2MC = - ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); - Optional payloadString; - try { - payloadString = GatewayUtils.buildMessagePayloadFromMessageContext(axis2MC, headers); - } catch (OpenBankingException e) { - log.error("Unable to build response payload", e); - GatewayUtils.returnSynapseHandlerJSONError(messageContext, OpenBankingErrorCodes.SERVER_ERROR_CODE, - getFormattedSignatureHandlingErrorResponse(messageContext, OpenBankingErrorCodes.SERVER_ERROR_CODE, - INTERNAL_SERVER_ERROR, "Internal Server Error, Unable to build response payload")); - return true; - } - - if (payloadString.isPresent()) { - try { - headers.put(signatureHeaderName, generateJWSSignature(payloadString)); - } catch (JOSEException | OpenBankingException e) { - log.error("Unable to sign response", e); - GatewayUtils.returnSynapseHandlerJSONError(messageContext, OpenBankingErrorCodes.SERVER_ERROR_CODE, - getFormattedSignatureHandlingErrorResponse(messageContext, - OpenBankingErrorCodes.SERVER_ERROR_CODE, INTERNAL_SERVER_ERROR, - "Internal Server Error, Unable to sign the response")); - return true; - } - } else { - log.debug("Signature cannot be generated as the payload is invalid or not present."); - } - axis2MC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers); - return true; - } - - /** - * Method to change the expected request header name containing the JWS. - * - * @return String signature header name. - */ - @Generated(message = "Excluding from unit tests since there is no logics to test") - public String getSignatureHeaderName() { - - return "x-jws-signature"; - } - - /** - * Provide the child classes to decide whether the signature generation is required for requestPath. - * - * @param messageContext OB response Object - * @return boolean returns if request needs to be signed - */ - @Generated(message = "Excluding from unit tests since there is a call to a method in Common Module") - public boolean isApplicable(MessageContext messageContext) { - - return OpenBankingConfigParser.getInstance().isJwsResponseSigningEnabled(); - } - - /** - * Method to Generate JWS signature. - * - * @param payloadString payload. - * @return String jws signature. - */ - public String generateJWSSignature(Optional payloadString) - throws OpenBankingException, JOSEException { - - String jwsSignatureHeader = null; - if (payloadString.isPresent() && StringUtils.isNotBlank(payloadString.get())) { - HashMap criticalParameters = getCriticalHeaderParameters(); - try { - jwsSignatureHeader = GatewayUtils.constructJWSSignature(payloadString.get(), criticalParameters); - } catch (OpenBankingExecutorException e) { - throw new OpenBankingException(e.getMessage()); - } - } else { - log.debug("Signature cannot be generated as the payload is invalid."); - } - return jwsSignatureHeader; - } - - /** - * HashMap to be returned with crit header keys and values. - * can be extended at toolkit level. - * - * @return HashMap crit header parameters - */ - @Generated(message = "Excluding from unit test coverage") - public HashMap getCriticalHeaderParameters() { - - return new HashMap<>(); - } - - /** - * Method to get the formatted error response for jws signature response. - * - * @param messageContext messageContext - * @param code error code - * @param title error title - * @param errorMessage error message - * @return String error response - */ - @Generated(message = "Excluding from unit test coverage") - public String getFormattedSignatureHandlingErrorResponse(MessageContext messageContext, String code, String title, - String errorMessage) { - - JSONObject payload = new JSONObject(); - JSONArray errorList = new JSONArray(); - JSONObject errorObj = new JSONObject(); - errorObj.put("Code", code); - errorObj.put("Title", title); - errorObj.put("Message", errorMessage); - errorList.put(errorObj); - return payload.put(ERRORS_TAG, errorList).toString(); - } - - @Generated(message = "Excluding from unit test coverage") - public void setXWso2ApiVersion(String xWso2ApiVersion) { - - this.xWso2ApiVersion = xWso2ApiVersion; - } - - @Generated(message = "Excluding from unit test coverage") - public String getXWso2ApiVersion() { - - return this.xWso2ApiVersion; - } - - @Generated(message = "Excluding from unit test coverage") - public String getXWso2ApiType() { - - return xWso2ApiType; - } - - @Generated(message = "Excluding from unit test coverage") - public void setXWso2ApiType(String xWso2ApiType) { - - this.xWso2ApiType = xWso2ApiType; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/GatewayDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/GatewayDataHolder.java deleted file mode 100644 index d67230ee..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/GatewayDataHolder.java +++ /dev/null @@ -1,372 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.data.publisher.common.constants.DataPublishingConstants; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCache; -import com.wso2.openbanking.accelerator.gateway.executor.core.AbstractRequestRouter; -import com.wso2.openbanking.accelerator.gateway.throttling.ThrottleDataPublisher; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import org.apache.http.impl.client.CloseableHttpClient; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.identity.core.util.IdentityUtil; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Data holder for executor core. - */ -public class GatewayDataHolder { - - private static volatile GatewayDataHolder instance; - private static volatile CloseableHttpClient httpClient; - private static volatile GatewayCache gatewayCache; - private OpenBankingConfigurationService openBankingConfigurationService; - private Map configurations; - private APIManagerConfigurationService apiManagerConfigurationService; - private AbstractRequestRouter requestRouter; - private Map urlMap; - private ThrottleDataPublisher throttleDataPublisher; - private int gatewayCacheAccessExpiry; - private int gatewayCacheModifiedExpiry; - private String keyStoreLocation; - private char[] keyStorePassword; - private String keyAlias; - private String keyPassword; - private boolean isAPIMAnalyticsEnabled; - private boolean isOBDataPublishingEnabled; - private String workerThreadCount; - private String clientTransportCertHeaderName; - private boolean isUrlEncodeClientTransportCertHeaderEnabled; - - private GatewayDataHolder() { - - } - - public static GatewayDataHolder getInstance() { - - if (instance == null) { - synchronized (GatewayDataHolder.class) { - if (instance == null) { - instance = new GatewayDataHolder(); - } - } - } - return instance; - } - - public static CloseableHttpClient getHttpClient() throws OpenBankingException { - - if (httpClient == null) { - synchronized (GatewayDataHolder.class) { - if (httpClient == null) { - httpClient = HTTPClientUtils.getHttpsClient(); - } - } - } - return httpClient; - } - - public static GatewayCache getGatewayCache() { - - if (gatewayCache == null) { - synchronized (GatewayDataHolder.class) { - if (gatewayCache == null) { - gatewayCache = new GatewayCache(); - } - } - } - return gatewayCache; - } - - private static void setGatewayCache(GatewayCache cache) { - gatewayCache = cache; - } - - public OpenBankingConfigurationService getOpenBankingConfigurationService() { - - return openBankingConfigurationService; - } - - public void setOpenBankingConfigurationService( - OpenBankingConfigurationService openBankingConfigurationService) { - - this.openBankingConfigurationService = openBankingConfigurationService; - if (openBankingConfigurationService != null) { - this.configurations = openBankingConfigurationService.getConfigurations(); - AbstractRequestRouter configuredRequestRouter = (AbstractRequestRouter) - OpenBankingUtils.getClassInstanceFromFQN(configurations.get(GatewayConstants.REQUEST_ROUTER) - .toString()); - setGatewayCacheAccessExpiry((String) configurations.get(GatewayConstants.GATEWAY_CACHE_EXPIRY)); - setGatewayCacheModifiedExpiry((String) configurations - .get(GatewayConstants.GATEWAY_CACHE_MODIFIEDEXPIRY)); - this.urlMap = constructURLMap(); - configuredRequestRouter.build(); - this.setRequestRouter(configuredRequestRouter); - if (configurations.get(GatewayConstants.GATEWAY_THROTTLE_DATAPUBLISHER) != null) { - this.setThrottleDataPublisher((ThrottleDataPublisher) OpenBankingUtils - .getClassInstanceFromFQN(configurations.get(GatewayConstants.GATEWAY_THROTTLE_DATAPUBLISHER) - .toString())); - } - - setAPIMAnalyticsEnabled((String) configurations.get(DataPublishingConstants.APIM_ANALYTICS_ENABLED)); - setOBDataPublishingEnabled((String) configurations.get(DataPublishingConstants.DATA_PUBLISHING_ENABLED)); - setWorkerThreadCount((String) configurations.get(DataPublishingConstants.WORKER_THREAD_COUNT)); - setClientTransportCertHeaderName((String) configurations.get(OpenBankingConstants. - CLIENT_TRANSPORT_CERT_HEADER_NAME)); - setUrlEncodeClientTransportCertHeaderEnabled((String) configurations.get(OpenBankingConstants. - URL_ENCODE_CLIENT_TRANSPORT_CERT_HEADER_ENABLED)); - } - } - - public AbstractRequestRouter getRequestRouter() { - - return requestRouter; - } - - public void setRequestRouter( - AbstractRequestRouter requestRouter) { - - this.requestRouter = requestRouter; - } - - public int getGatewayCacheAccessExpiry() { - - return gatewayCacheAccessExpiry; - } - - public void setGatewayCacheAccessExpiry(String expTime) { - - this.gatewayCacheAccessExpiry = expTime == null ? 60 : Integer.parseInt(expTime); - } - - public int getGatewayCacheModifiedExpiry() { - - return gatewayCacheModifiedExpiry; - } - - public void setGatewayCacheModifiedExpiry(String expTime) { - - this.gatewayCacheModifiedExpiry = expTime == null ? 60 : Integer.parseInt(expTime); - } - - public String getKeyStoreLocation() { - - return keyStoreLocation == null ? ServerConfiguration.getInstance() - .getFirstProperty(GatewayConstants.KEYSTORE_LOCATION_TAG) : keyStoreLocation; - - } - - public void setKeyStoreLocation(String keyStoreLocation) { - - this.keyStoreLocation = keyStoreLocation; - } - - public char[] getKeyStorePassword() { - - if (this.keyStorePassword == null) { - char[] password = ServerConfiguration.getInstance() - .getFirstProperty(GatewayConstants.KEYSTORE_PASSWORD_TAG).toCharArray(); - this.keyStorePassword = password; - return Arrays.copyOf(this.keyStorePassword, this.keyStorePassword.length); - } else { - return Arrays.copyOf(this.keyStorePassword, this.keyStorePassword.length); - } - } - - public void setKeyStorePassword(char[] keyStorePassword) { - - if (keyStorePassword != null) { - this.keyStorePassword = Arrays.copyOf(keyStorePassword, keyStorePassword.length); - } - } - - public String getKeyAlias() { - - return keyAlias == null ? ServerConfiguration.getInstance() - .getFirstProperty(GatewayConstants.SIGNING_ALIAS_TAG) : keyAlias; - } - - public void setKeyAlias(String keyAlias) { - - this.keyAlias = keyAlias; - } - - public String getKeyPassword() { - - return keyPassword == null ? ServerConfiguration.getInstance() - .getFirstProperty(GatewayConstants.SIGNING_KEY_PASSWORD) : keyPassword; - } - - public void setKeyPassword(String keyPassword) { - - this.keyPassword = keyPassword; - } - - public void setApiManagerConfiguration(APIManagerConfigurationService apiManagerConfigurationService) { - - this.apiManagerConfigurationService = apiManagerConfigurationService; - } - - public APIManagerConfigurationService getApiManagerConfigurationService() { - - return apiManagerConfigurationService; - } - - public Map getUrlMap() { - - return urlMap; - } - - public void setUrlMap(Map configurations) { - - this.urlMap = configurations; - } - - private Map constructURLMap() { - - Map urlMap = new HashMap<>(); - //get admin credentials - APIManagerConfiguration config = apiManagerConfigurationService.getAPIManagerConfiguration(); - - String adminUsername = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); - urlMap.put(GatewayConstants.USERNAME, adminUsername); - - char[] adminPassword = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray(); - urlMap.put(GatewayConstants.PASSWORD, adminPassword); - - //read APIM store hostname - String apimStoreHostName = configurations.get(OpenBankingConstants.STORE_HOSTNAME).toString(); - if (!apimStoreHostName.endsWith("/")) { - apimStoreHostName = apimStoreHostName.concat("/"); - } - - //set the url for obtaining a token - String tokenURL = configurations.get(OpenBankingConstants.TOKEN_ENDPOINT).toString(); - urlMap.put(GatewayConstants.TOKEN_URL, tokenURL); - - //set the url for apim application creation - String applicationCreationURL = - apimStoreHostName.concat(configurations.get(OpenBankingConstants.APIM_APPCREATION).toString()); - urlMap.put(GatewayConstants.APP_CREATE_URL, applicationCreationURL); - - // set the url for mapping apim app keys to IAM service provider keys - String mapApplicationKeysURL = - apimStoreHostName.concat(configurations.get(OpenBankingConstants.APIM_KEYGENERATION).toString()); - urlMap.put(GatewayConstants.KEY_MAP_URL, mapApplicationKeysURL); - - //set the url to retrieve all published APIs - String retrieveAPIsURL = - apimStoreHostName.concat(configurations.get(OpenBankingConstants.APIM_GETAPIS).toString()); - urlMap.put(GatewayConstants.API_RETRIEVE_URL, retrieveAPIsURL); - - //set the url to subscribe to APIS - String subscribeAPIsURL = - apimStoreHostName.concat(configurations.get(OpenBankingConstants.APIM_SUBSCRIBEAPIS).toString()); - urlMap.put(GatewayConstants.API_SUBSCRIBE_URL, subscribeAPIsURL); - - //set the url to retrieve the subscriptions for an application - //set the url to get subscribed APIS - String retrieveSubscriptionURL = - apimStoreHostName.concat(configurations.get(OpenBankingConstants.APIM_GETSUBSCRIPTIONS).toString()); - urlMap.put(GatewayConstants.API_GET_SUBSCRIBED, retrieveSubscriptionURL); - - String iamHostName = GatewayDataHolder.getInstance() - .getApiManagerConfigurationService().getAPIManagerConfiguration() - .getFirstProperty("APIKeyValidator.ServerURL").split("/services")[0]; - - urlMap.put(GatewayConstants.IAM_HOSTNAME, iamHostName); - - String iamDCREndpoint = IdentityUtil.getProperty("OAuth.OAuth2DCREPUrl").split("/api/")[1]; - iamDCREndpoint = iamHostName.concat("/api/").concat(iamDCREndpoint); - urlMap.put(GatewayConstants.IAM_DCR_URL, iamDCREndpoint); - return urlMap; - } - - public ThrottleDataPublisher getThrottleDataPublisher() { - - return throttleDataPublisher; - } - - public void setThrottleDataPublisher( - ThrottleDataPublisher throttleDataPublisher) { - - this.throttleDataPublisher = throttleDataPublisher; - } - - public boolean isAPIMAnalyticsEnabled() { - - return isAPIMAnalyticsEnabled; - } - - public void setAPIMAnalyticsEnabled(String apimAnalyticsEnabled) { - - isAPIMAnalyticsEnabled = Boolean.parseBoolean(apimAnalyticsEnabled); - } - - public boolean isOBDataPublishingEnabled() { - - return isOBDataPublishingEnabled; - } - - public void setOBDataPublishingEnabled(String obDataPublishingEnabled) { - - isOBDataPublishingEnabled = Boolean.parseBoolean(obDataPublishingEnabled); - } - - public void setWorkerThreadCount(String workerThreadCount) { - this.workerThreadCount = workerThreadCount; - } - - public String getWorkerThreadCount() { - - return workerThreadCount; - } - - public String getClientTransportCertHeaderName() { - - return clientTransportCertHeaderName; - } - - public void setClientTransportCertHeaderName(String clientTransportCertHeaderName) { - - this.clientTransportCertHeaderName = clientTransportCertHeaderName; - } - - public boolean isUrlEncodeClientTransportCertHeaderEnabled() { - - return isUrlEncodeClientTransportCertHeaderEnabled; - } - - public void setUrlEncodeClientTransportCertHeaderEnabled(String isUrlEncodeClientTransportCertHeaderEnabled) { - - this.isUrlEncodeClientTransportCertHeaderEnabled = - Boolean.parseBoolean(isUrlEncodeClientTransportCertHeaderEnabled); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/GatewayServiceComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/GatewayServiceComponent.java deleted file mode 100644 index e5e9677f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/GatewayServiceComponent.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; - -/** - * Service class for executor core. - */ -@Component( - name = "com.wso2.open.banking.common", - immediate = true -) -public class GatewayServiceComponent { - - private static final Log log = LogFactory.getLog(GatewayServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - log.debug("Open banking gateway component is activated "); - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - log.debug("Open banking gateway component is deactivated "); - } - - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - GatewayDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - GatewayDataHolder.getInstance().setOpenBankingConfigurationService(null); - } - - @Reference( - service = APIManagerConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unSetAPIMConfigs" - ) - public void setAPIMConfig(APIManagerConfigurationService apManagerConfigurationService) { - - GatewayDataHolder.getInstance().setApiManagerConfiguration(apManagerConfigurationService); - } - - public void unSetAPIMConfigs(APIManagerConfigurationService apManagerConfigurationService) { - - GatewayDataHolder.getInstance().setApiManagerConfiguration(apManagerConfigurationService); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorComponent.java deleted file mode 100644 index f22e9966..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorComponent.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.base.ServerConfiguration; - -import java.io.IOException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * Service Component For Gateway Component. - **/ -@Component(name = "com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorComponent", - immediate = true) -public class TPPCertValidatorComponent { - - private static final Log log = LogFactory.getLog(TPPCertValidatorComponent.class); - private static final Integer SCHEDULED_INITIAL_DELAY_IN_SECONDS = 1; - - @Activate - protected void activate(ComponentContext context) { - - Object certificateRevocationEnabled = OpenBankingConfigParser.getInstance(). - getConfiguration().get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_ENABLED); - final boolean isCertificateRevocationEnabled = - certificateRevocationEnabled != null && Boolean.parseBoolean((String) certificateRevocationEnabled); - - Object transportCertIssuerValidationEnabled = OpenBankingConfigParser.getInstance(). - getConfiguration().get(OpenBankingConstants.TRANSPORT_CERT_ISSUER_VALIDATION_ENABLED); - final boolean isTransportCertIssuerValidationEnabled = transportCertIssuerValidationEnabled != null - && Boolean.parseBoolean((String) transportCertIssuerValidationEnabled); - - // Loading truststore - if (isCertificateRevocationEnabled || isTransportCertIssuerValidationEnabled) { - ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1); - Runnable readTruststore = () -> { - try { - CertificateValidationUtils.loadTrustStore( - ServerConfiguration.getInstance().getFirstProperty(CertificateValidationUtils - .TRUSTSTORE_PASS_CONF_KEY).toCharArray()); - log.info("client truststore successfully loaded into certificate validator"); - } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) { - log.error("Unable to load the client truststore", e); - } - }; - - // Initiate the scheduled truststore loading with an interval value configured as the truststore - // dynamic loading interval in open-banking.xml. - ScheduledFuture scheduledFuture = scheduledExecutor.scheduleAtFixedRate(readTruststore, - SCHEDULED_INITIAL_DELAY_IN_SECONDS, OpenBankingConfigParser.getInstance() - .getTruststoreDynamicLoadingInterval(), TimeUnit.SECONDS); - if (scheduledFuture.isCancelled()) { - log.error("Error occurred while loading the client truststore into certificate validator"); - } - } - TPPCertValidatorDataHolder.getInstance().initializeTPPValidationDataHolder(); - log.debug("OB Gateway component is activated "); - } - - @Deactivate - protected void deactivate(ComponentContext ctxt) { - log.debug("Client registration validation handler is deactivated"); - } - - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - TPPCertValidatorDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - TPPCertValidatorDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - @Reference(name = "api.manager.config.service", - service = APIManagerConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetAPIManagerConfigurationService" - ) - protected void setAPIConfigurationService(APIManagerConfigurationService confService) { - log.debug("API manager configuration service bound to the OB Gateway component"); - TPPCertValidatorDataHolder.getInstance().setApiManagerConfiguration(confService); - } - - protected void unsetAPIManagerConfigurationService(APIManagerConfigurationService amcService) { - log.debug("API manager configuration service unbound from the OB Gateway component"); - TPPCertValidatorDataHolder.getInstance().setApiManagerConfiguration(null); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorDataHolder.java deleted file mode 100644 index 1ac87fa2..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorDataHolder.java +++ /dev/null @@ -1,476 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.gateway.executor.service.TPPValidationService; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; - -import java.util.ArrayList; -import java.util.List; - -/** - * Data Holder For Gateway Component. - **/ -public class TPPCertValidatorDataHolder { - - private static final Log log = LogFactory.getLog(TPPCertValidatorDataHolder.class); - - private static TPPCertValidatorDataHolder instance = null; - - private int tppValidationCacheExpiry; - private int tppCertRevocationCacheExpiry; - private int certificateRevocationProxyPort; - private int certificateRevocationValidationRetryCount; - private int connectTimeout; - private int connectionRequestTimeout; - private int socketTimeout; - - private boolean psd2RoleValidationEnabled; - private boolean certificateRevocationProxyEnabled; - private boolean transportCertIssuerValidationEnabled; - private boolean certificateRevocationValidationEnabled; - - private String tppValidationServiceImpl; - private String certificateRevocationProxyHost; - - private List revocationValidationExcludedIssuersList; - - private TPPValidationService tppValidationService; - private OpenBankingConfigurationService openBankingConfigurationService; - private APIManagerConfigurationService apiManagerConfigurationService; - - private TPPCertValidatorDataHolder() { - // Disable direct object creation - } - - public static synchronized TPPCertValidatorDataHolder getInstance() { - if (instance == null) { - instance = new TPPCertValidatorDataHolder(); - } - return instance; - } - - public TPPValidationService getTppValidationService() { - return tppValidationService; - } - - public void setTppValidationService() { - if (isTppValidationEnabled()) { - - String tppValidationServiceImplClass = getTPPValidationServiceImpl(); - if (StringUtils.isNotBlank(tppValidationServiceImplClass)) { - try { - this.tppValidationService = (TPPValidationService) Class.forName(tppValidationServiceImplClass) - .newInstance(); - } catch (ClassNotFoundException e) { - log.error("Unable to find the TPP validation service class " + - "implementation", e); - } catch (InstantiationException | IllegalAccessException e) { - log.error("Error occurred while loading the TPP validation " + - "service class implementation", e); - } - } else { - log.error("TPP validation service class implementation cannot be empty"); - } - } - } - - /** - * Certificate revocation cache expiry time has been configured in the open-banking.xml. - * Default value is 3600 seconds. - */ - public int getTppCertRevocationCacheExpiry() { - return this.tppCertRevocationCacheExpiry; - } - - public void setTppCertRevocationCacheExpiry() { - try { - Object clientCertificateCacheExpiry = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CLIENT_CERTIFICATE_CACHE_EXPIRY); - if (clientCertificateCacheExpiry != null) { - this.tppCertRevocationCacheExpiry = Integer.parseInt((String) clientCertificateCacheExpiry); - } else { - this.tppCertRevocationCacheExpiry = 3600; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the client certificate cache expiry value " + - "in open-banking.xml. caused by, " + e.getMessage()); - } - } - - /** - * Tpp validation cache expiry time has been configured in the open-banking.xml. - * Default value is 3600 seconds. - */ - public int getTppValidationCacheExpiry() { - return this.tppValidationCacheExpiry; - } - - public void setTppValidationCacheExpiry() { - try { - Object clientCertificateCacheExpiry = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.TPP_VALIDATION_CACHE_EXPIRY); - if (clientCertificateCacheExpiry != null) { - this.tppValidationCacheExpiry = Integer.parseInt((String) clientCertificateCacheExpiry); - } else { - this.tppValidationCacheExpiry = 3600; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the tpp validation cache expiry value " + - "in open-banking.xml. caused by, " + e.getMessage()); - } - } - - /** - * Check if the certificate revocation validation is enabled. - * - * @return true if the certificate validation is enabled. Default value has been sent to true. - */ - public boolean isCertificateRevocationValidationEnabled() { - return this.certificateRevocationValidationEnabled; - } - - public void setCertificateRevocationValidationEnabled() { - - Object isCertificateRevocationEnabled = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_ENABLED); - if (isCertificateRevocationEnabled != null) { - this.certificateRevocationValidationEnabled = Boolean.parseBoolean((String) isCertificateRevocationEnabled); - } else { - this.certificateRevocationValidationEnabled = true; - } - } - - public void setCertificateRevocationValidationExcludedIssuers() { - Object revocationValidationExcludedIssuers = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_EXCLUDED_ISSUERS); - - this.revocationValidationExcludedIssuersList = new ArrayList<>(); - if (revocationValidationExcludedIssuers instanceof ArrayList) { - revocationValidationExcludedIssuersList.addAll((ArrayList) revocationValidationExcludedIssuers); - } else if (revocationValidationExcludedIssuers instanceof String) { - revocationValidationExcludedIssuersList.add((String) revocationValidationExcludedIssuers); - } - } - - /** - * Get the certificate issuers whose issued certificates are excluded from revocation validation. - * - * @return Returns a list of certificate issuers whose issued certificates are excluded from revocation validation - */ - public List getCertificateRevocationValidationExcludedIssuers() { - return this.revocationValidationExcludedIssuersList; - - } - - /** - * Validate the TPP using external service implementation. - * - * @return Default value has been set to false - */ - public boolean isTppValidationEnabled() { - Object isTppValidationEnabled = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.TPP_VALIDATION_ENABLED); - if (isTppValidationEnabled != null) { - return Boolean.parseBoolean((String) isTppValidationEnabled); - } else { - return false; - } - } - - public void setCertificateRevocationValidationRetryCount() { - try { - Object certificateRevocationValidationRetryCountObj = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_RETRY_COUNT); - if (certificateRevocationValidationRetryCountObj != null) { - this.certificateRevocationValidationRetryCount = - Integer.parseInt((String) certificateRevocationValidationRetryCountObj); - } else { - this.certificateRevocationValidationRetryCount = 3; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the certificate revocation validation" + - " retry count in open-banking.xml. " + e.getMessage()); - } - } - - /** - * Get the certificate revocation validation retry count for CRL and OCSP validations. - * - * @return returns the certificate revocation validation retry count for CRL and OCSP validations. - * Default value has been set to 3. - */ - public int getCertificateRevocationValidationRetryCount() { - return this.certificateRevocationValidationRetryCount; - } - - /** - * Get the certificate revocation validation connectTimeout for CRL and OCSP validations. - * - * @return returns the certificate revocation validation connectTimeout for CRL and OCSP validations. - */ - public int getConnectTimeout() { - - return connectTimeout; - } - - /** - * Set the certificate revocation validation connectTimeout for CRL and OCSP validations. - * - */ - public void setConnectTimeout() { - try { - Object certValidationConnectTimeout = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_CONNECT_TIMEOUT); - if (certValidationConnectTimeout != null) { - this.connectTimeout = Integer.parseInt((String) certValidationConnectTimeout); - } else { - // Default value has been set to 10000 milliseconds. - this.connectTimeout = 10000; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the connectTimeout value " + - "in open-banking.xml. caused by, " + e.getMessage()); - } - } - - /** - * Get the certificate revocation validation connectionRequestTimeout for CRL and OCSP validations. - * - * @return returns the certificate revocation validation connectionRequestTimeout for CRL and OCSP validations. - */ - public int getConnectionRequestTimeout() { - - return connectionRequestTimeout; - } - - /** - * Set the certificate revocation validation connectionRequestTimeout for CRL and OCSP validations. - * - */ - public void setConnectionRequestTimeout() { - - try { - Object certValidationConnectionRequestTimeout = this.openBankingConfigurationService.getConfigurations() - .get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_CONNECTION_REQUEST_TIMEOUT); - if (certValidationConnectionRequestTimeout != null) { - this.connectionRequestTimeout = Integer.parseInt((String) certValidationConnectionRequestTimeout); - } else { - // Default value has been set to 10000 milliseconds. - this.connectionRequestTimeout = 10000; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the connection request timeout value " + - "in open-banking.xml. caused by, " + e.getMessage()); - } - } - - /** - * Get the certificate revocation validation socketTimeout for CRL and OCSP validations. - * - * @return returns the certificate revocation validation socketTimeout for CRL and OCSP validations. - */ - public int getSocketTimeout() { - - return socketTimeout; - } - - /** - * Set the certificate revocation validation socketTimeout for CRL and OCSP validations. - * - */ - public void setSocketTimeout() { - - try { - Object certValidationSocketTimeout = this.openBankingConfigurationService.getConfigurations() - .get(OpenBankingConstants.CERTIFICATE_REVOCATION_VALIDATION_SOCKET_TIMEOUT); - if (certValidationSocketTimeout != null) { - this.socketTimeout = Integer.parseInt((String) certValidationSocketTimeout); - } else { - // Default value has been set to 10000 milliseconds. - this.socketTimeout = 10000; - } - } catch (NumberFormatException e) { - throw new NumberFormatException("Error occurred while reading the socket timeout value " + - "in open-banking.xml. caused by, " + e.getMessage()); - } - } - - /** - * Get the certificate revocation validation manager implementation class to validate the revocation status - * of a certificate. - * - * @return class name of the certificate revocation validator implementation class - */ - public String getTPPValidationServiceImpl() { - return this.tppValidationServiceImpl; - } - - public void setTPPValidationServiceImpl() { - Object revocationValidationManagerImpl = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.TPP_VALIDATION_SERVICE_IMPL_CLASS); - if (revocationValidationManagerImpl != null) { - this.tppValidationServiceImpl = String.valueOf(revocationValidationManagerImpl) - .replaceAll("[\\n\\t ]", ""); - } - } - - /** - * Returns whether the certification revocation proxy is enabled. - *

- * If enabled, the certificate revocation checks will be done via the configured proxy - * - * @return {@code true} if certificate revocation proxy is enabled, {@code false} otherwise. The default value is - * {@code false} - */ - public boolean isCertificateRevocationProxyEnabled() { - return certificateRevocationProxyEnabled; - } - - public void setCertificateRevocationProxyEnabled() { - Object isCertificateRevocationProxyEnabled = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_PROXY_ENABLED); - if (isCertificateRevocationProxyEnabled != null) { - this.certificateRevocationProxyEnabled = Boolean.parseBoolean((String) isCertificateRevocationProxyEnabled); - } else { - this.certificateRevocationProxyEnabled = false; - } - } - - /** - * Returns the certificate revocation proxy port. - *

- * The certificate revocation checks will be done via this proxy port, if the - * {@code CertificateRevocationProxyEnabled} value is set to {@code true} - * - * @return certificate revocation proxy port - */ - public int getCertificateRevocationProxyPort() { - return this.certificateRevocationProxyPort; - } - - public void setCertificateRevocationProxyPort() { - Object certificateRevocationProxyPortObj = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_PROXY_PORT); - this.certificateRevocationProxyPort = certificateRevocationProxyPortObj != null ? - Integer.parseInt((String) certificateRevocationProxyPortObj) : 8080; - } - - /** - * Returns the certificate revocation proxy host. - *

- * The certificate revocation checks will be done via this proxy host, if the - * {@code CertificateRevocationProxyEnabled} value is set to {@code true} - * - * @return certificate revocation proxy host - */ - public String getCertificateRevocationProxyHost() { - return this.certificateRevocationProxyHost; - } - - public void setCertificateRevocationProxyHost() { - Object certificateRevocationProxyHostObj = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.CERTIFICATE_REVOCATION_PROXY_HOST); - this.certificateRevocationProxyHost = - certificateRevocationProxyHostObj != null ? ((String) certificateRevocationProxyHostObj).trim() : ""; - } - - /** - * Validate the issuer of the client certificate when the client certificate is sent as a header when the TLS - * session is terminated before gateway. - * - * @return Default value has been set to true - */ - public boolean isTransportCertIssuerValidationEnabled() { - return this.transportCertIssuerValidationEnabled; - } - - public void setTransportCertIssuerValidationEnabled() { - Object transportCertIssuerValidationEnabledObj = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.TRANSPORT_CERT_ISSUER_VALIDATION_ENABLED); - if (transportCertIssuerValidationEnabledObj != null) { - this.transportCertIssuerValidationEnabled = - Boolean.parseBoolean((String) transportCertIssuerValidationEnabledObj); - } else { - this.transportCertIssuerValidationEnabled = true; - } - } - - /** - * Validate the TPP PSD2 roles. - * - * @return Default value has been set to true - */ - public boolean isPsd2RoleValidationEnabled() { - return this.psd2RoleValidationEnabled; - } - - public void setPsd2RoleValidationEnabled() { - Object psd2RoleValidationEnabledObj = this.openBankingConfigurationService. - getConfigurations().get(OpenBankingConstants.PSD2_ROLE_VALIDATION_ENABLED); - if (psd2RoleValidationEnabledObj != null) { - this.psd2RoleValidationEnabled = Boolean.parseBoolean((String) psd2RoleValidationEnabledObj); - } else { - this.psd2RoleValidationEnabled = true; - } - } - - public OpenBankingConfigurationService getOpenBankingConfigurationService() { - return openBankingConfigurationService; - } - - public void setOpenBankingConfigurationService(OpenBankingConfigurationService openBankingConfigurationService) { - this.openBankingConfigurationService = openBankingConfigurationService; - } - - public void setApiManagerConfiguration(APIManagerConfigurationService apiManagerConfigurationService) { - - this.apiManagerConfigurationService = apiManagerConfigurationService; - } - - public APIManagerConfigurationService getApiManagerConfigurationService() { - - return apiManagerConfigurationService; - } - - public void initializeTPPValidationDataHolder() { - setTPPValidationServiceImpl(); - setTppValidationService(); - - setTppValidationCacheExpiry(); - setPsd2RoleValidationEnabled(); - setTppCertRevocationCacheExpiry(); - setCertificateRevocationProxyHost(); - setCertificateRevocationProxyPort(); - setCertificateRevocationProxyEnabled(); - setTransportCertIssuerValidationEnabled(); - setCertificateRevocationValidationEnabled(); - setCertificateRevocationValidationRetryCount(); - setCertificateRevocationValidationExcludedIssuers(); - setConnectTimeout(); - setConnectionRequestTimeout(); - setSocketTimeout(); - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/mediator/BasicAuthMediator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/mediator/BasicAuthMediator.java deleted file mode 100644 index cbac8b26..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/mediator/BasicAuthMediator.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.mediator; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.synapse.MessageContext; -import org.apache.synapse.mediators.AbstractMediator; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -/** - * Append Basic Authorisation header to the API calls from gateway to be passed on to the - * key management server. Invoked by the synapse in-sequence.xml files. - */ -public class BasicAuthMediator extends AbstractMediator { - - private static final Log log = LogFactory.getLog(BasicAuthMediator.class); - - public BasicAuthMediator() { - - log.info("Initializing Basic Authentication Mediator to append basic auth credentials in gateway " + - "in-sequence."); - } - - @Override - public boolean mediate(MessageContext messageContext) { - - messageContext.setProperty("basicAuthentication", ("Basic " + Base64.getEncoder().encodeToString( - (getAPIMConfigFromKey(GatewayConstants.API_KEY_VALIDATOR_USERNAME) + ":" - + getAPIMConfigFromKey(GatewayConstants.API_KEY_VALIDATOR_PASSWORD)) - .getBytes(StandardCharsets.UTF_8)))); - return true; - } - - @Generated(message = "Excluded since this method is used for testing purposes") - String getAPIMConfigFromKey(String key) { - - return GatewayUtils.getAPIMgtConfig(key); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBAnalyticsMetricReporter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBAnalyticsMetricReporter.java deleted file mode 100644 index c0c90f60..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBAnalyticsMetricReporter.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.reporter; - -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import org.wso2.am.analytics.publisher.exception.MetricCreationException; -import org.wso2.am.analytics.publisher.reporter.AbstractMetricReporter; -import org.wso2.am.analytics.publisher.reporter.CounterMetric; -import org.wso2.am.analytics.publisher.reporter.MetricSchema; -import org.wso2.am.analytics.publisher.reporter.TimerMetric; -import org.wso2.am.analytics.publisher.reporter.cloud.DefaultAnalyticsMetricReporter; - -import java.util.Map; - -/** - * OB Analytics Metric Reporter class. - */ -public class OBAnalyticsMetricReporter extends AbstractMetricReporter { - - private DefaultAnalyticsMetricReporter defaultAnalyticsMetricReporter; - - public OBAnalyticsMetricReporter(Map properties) throws MetricCreationException { - - super(properties); - if (GatewayDataHolder.getInstance().isAPIMAnalyticsEnabled()) { - defaultAnalyticsMetricReporter = new DefaultAnalyticsMetricReporter(properties); - } - } - - @Override - protected void validateConfigProperties(Map map) throws MetricCreationException { - - } - - @Override - protected CounterMetric createCounter(String name, MetricSchema schema) throws MetricCreationException { - - CounterMetric counterMetric = null; - if (GatewayDataHolder.getInstance().isAPIMAnalyticsEnabled()) { - counterMetric = defaultAnalyticsMetricReporter.createCounterMetric(name, schema); - } - return new OBCounterMetric(name, counterMetric, schema); - } - - @Override - protected TimerMetric createTimer(String s) { - - return null; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBCounterMetric.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBCounterMetric.java deleted file mode 100644 index b507c31a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBCounterMetric.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.reporter; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.am.analytics.publisher.exception.MetricReportingException; -import org.wso2.am.analytics.publisher.reporter.CounterMetric; -import org.wso2.am.analytics.publisher.reporter.MetricEventBuilder; -import org.wso2.am.analytics.publisher.reporter.MetricSchema; -import org.wso2.am.analytics.publisher.reporter.cloud.DefaultChoreoFaultMetricEventBuilder; -import org.wso2.am.analytics.publisher.reporter.cloud.DefaultChoreoResponseMetricEventBuilder; -import org.wso2.am.analytics.publisher.reporter.cloud.DefaultFaultMetricEventBuilder; -import org.wso2.am.analytics.publisher.reporter.cloud.DefaultResponseMetricEventBuilder; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * OB Counter metric class to publish am analytics and ob analytics data. - */ -public class OBCounterMetric implements CounterMetric { - - private static final Log log = LogFactory.getLog(OBCounterMetric.class); - private final ExecutorService obExecutorService; - private final CounterMetric counterMetric; - private String name; - private MetricSchema schema; - - public OBCounterMetric(String name, CounterMetric counterMetric, MetricSchema schema) { - - this.counterMetric = counterMetric; - this.name = name; - this.schema = schema; - int workerThreadCount = Integer.parseInt(GatewayDataHolder.getInstance().getWorkerThreadCount()); - this.obExecutorService = Executors.newFixedThreadPool(workerThreadCount); - } - - @Override - public int incrementCount(MetricEventBuilder builder) { - - int status; - - if (GatewayDataHolder.getInstance().isAPIMAnalyticsEnabled()) { - try { - status = counterMetric.incrementCount(builder); - } catch (MetricReportingException e) { - log.error("Error while publishing APIM analytics", e); - status = 0; - } - } else { - log.debug("APIM analytics disabled."); - status = 0; - } - - // OB data publishing - if (GatewayDataHolder.getInstance().isOBDataPublishingEnabled()) { - obExecutorService.submit(new OBTimestampPublisher(builder)); - } - return status; - } - - @Override - public String getName() { - - return this.name; - } - - @Override - public MetricSchema getSchema() { - - return this.schema; - } - - @Override - @Generated(message = "This is skipped because schema cannot be mocked") - public MetricEventBuilder getEventBuilder() { - - switch (schema) { - case RESPONSE: - return new DefaultResponseMetricEventBuilder(); - case ERROR: - return new DefaultFaultMetricEventBuilder(); - case CHOREO_RESPONSE: - return new DefaultChoreoResponseMetricEventBuilder(); - case CHOREO_ERROR: - return new DefaultChoreoFaultMetricEventBuilder(); - default: - // will not happen - return null; - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBTimestampPublisher.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBTimestampPublisher.java deleted file mode 100644 index 4ac020ab..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/reporter/OBTimestampPublisher.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.reporter; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.am.analytics.publisher.exception.MetricReportingException; -import org.wso2.am.analytics.publisher.reporter.MetricEventBuilder; - -import java.time.Duration; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; - -/** - * OB timestamp publisher worker class. - */ -public class OBTimestampPublisher implements Runnable { - - private MetricEventBuilder builder; - private static final String CORRELATION_ID = "correlationId"; - private static final String REQUEST_TIMESTAMP = "requestTimestamp"; - private static final String BACKEND_LATENCY = "backendLatency"; - private static final String REQUEST_MEDIATION_LATENCY = "requestMediationLatency"; - private static final String RESPONSE_LATENCY = "responseLatency"; - private static final String RESPONSE_MEDIATION_LATENCY = "responseMediationLatency"; - private static final String API_LATENCY_INPUT_STREAM = "APILatencyInputStream"; - private static final String API_LATENCY_STREAM_VERSION = "1.0.0"; - private static final Log log = LogFactory.getLog(OBTimestampPublisher.class); - - public OBTimestampPublisher(MetricEventBuilder builder) { - - this.builder = builder; - } - - public void run() { - - try { - Map eventMap = builder.build(); - Map analyticsData = new HashMap<>(); - Object requestTimestamp = eventMap.get(REQUEST_TIMESTAMP); - analyticsData.put(CORRELATION_ID, eventMap.get(CORRELATION_ID)); - analyticsData.put(REQUEST_TIMESTAMP, requestTimestamp); - analyticsData.put(BACKEND_LATENCY, - eventMap.get(BACKEND_LATENCY) != null ? eventMap.get(BACKEND_LATENCY) : 0L); - analyticsData.put(REQUEST_MEDIATION_LATENCY, - eventMap.get(REQUEST_MEDIATION_LATENCY) != null ? eventMap.get(REQUEST_MEDIATION_LATENCY) : 0L); - analyticsData.put(RESPONSE_LATENCY, - eventMap.get(RESPONSE_LATENCY) != null ? eventMap.get(RESPONSE_LATENCY) - : Duration.between(Instant.parse(requestTimestamp.toString()), Instant.now()).toMillis()); - analyticsData.put(RESPONSE_MEDIATION_LATENCY, eventMap.get(RESPONSE_MEDIATION_LATENCY) != null ? - eventMap.get(RESPONSE_MEDIATION_LATENCY) : 0L); - publishLatencyData(analyticsData); - } catch (MetricReportingException e) { - log.error("Error while collecting latency stats", e); - } - } - - @Generated(message = "This method is already covered") - protected void publishLatencyData(Map analyticsData) { - OBDataPublisherUtil.publishData(API_LATENCY_INPUT_STREAM, API_LATENCY_STREAM_VERSION, analyticsData); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/synapse/handler/DisputeResolutionSynapseHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/synapse/handler/DisputeResolutionSynapseHandler.java deleted file mode 100644 index 5bd95d8a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/synapse/handler/DisputeResolutionSynapseHandler.java +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.synapse.handler; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.synapse.AbstractSynapseHandler; -import org.apache.synapse.MessageContext; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.wso2.carbon.apimgt.impl.APIConstants; - -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Dispute Resolution Synapse Handler. - */ -public class DisputeResolutionSynapseHandler extends AbstractSynapseHandler { - private static final Log log = LogFactory.getLog(DisputeResolutionSynapseHandler.class); - - /** - * Handle request message coming into the engine. - * - * @param messageContext incoming request message context - * @return whether mediation flow should continue - */ - @Override - public boolean handleRequestInFlow(MessageContext messageContext) { - - //Checking Dispute Resolution Feature is Enabled - if (!OpenBankingConfigParser.getInstance().isDisputeResolutionEnabled()) { - return true; - } - - org.apache.axis2.context.MessageContext axis2MC = - ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); - - Map contextEntries = messageContext.getContextEntries(); - - //Extracting Request Body - Optional requestBody = Optional.empty(); - try { - requestBody = GatewayUtils.buildMessagePayloadFromMessageContext(axis2MC, headers); - } catch (OpenBankingException e) { - log.error("Unable to build request payload", e); - } - - contextEntries.put(OpenBankingConstants.REQUEST_BODY, - requestBody.isPresent() ? requestBody.get() : null); - return true; - } - - /** - * Handle request message going out from the engine. - * - * @param messageContext outgoing request message context - * @return whether mediation flow should continue - */ - @Override - @Generated(message = "Ignoring since method contains no logics") - public boolean handleRequestOutFlow(MessageContext messageContext) { - return true; - } - - /** - * Handle response message coming into the engine. - * - * @param messageContext incoming response message context - * @return whether mediation flow should continue - */ - @Override - @Generated(message = "Ignoring since method contains no logics") - public boolean handleResponseInFlow(MessageContext messageContext) { - return true; - } - - /** - * Handle response message going out from the engine. - * - * @param messageContext outgoing response message context - * @return whether mediation flow should continue - */ - @Override - public boolean handleResponseOutFlow(MessageContext messageContext) { - - //Checking Dispute Resolution Feature is Enabled - if (!OpenBankingConfigParser.getInstance().isDisputeResolutionEnabled()) { - return true; - } - - org.apache.axis2.context.MessageContext axis2MessageContext - = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - - Map disputeResolutionData = new HashMap<>(); - int statusCode = 0; - String httpMethod = null; - String headers = null; - long unixTimestamp = Instant.now().getEpochSecond(); - String electedResource = (String) messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE); - String responseBody = null; - String requestBody = null; - - //Extracting Status Code - String stringStatusCode = axis2MessageContext.getProperty(GatewayConstants.HTTP_SC).toString(); - statusCode = Integer.parseInt(stringStatusCode); - - //Extracting Headers - Map headerMap = (Map) axis2MessageContext - .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); - headers = headerMap.toString(); - - //Extracting HTTP Method - if (messageContext.getProperty(GatewayConstants.HTTP_METHOD) != null) { - httpMethod = (String) messageContext.getProperty(GatewayConstants.HTTP_METHOD); - } else { - httpMethod = GatewayConstants.UNKNOWN; - } - - //Extracting Response Body - Optional response = Optional.empty(); - try { - response = GatewayUtils.buildMessagePayloadFromMessageContext(axis2MessageContext, headerMap); - } catch (OpenBankingException e) { - log.error("Unable to build response payload", e); - - } - responseBody = response.get(); - - //Extracting Request Body - Map contextEntries = messageContext.getContextEntries(); - requestBody = (String) contextEntries.get(OpenBankingConstants.REQUEST_BODY); - - //reduced Headers, Request and Response Body Lengths - requestBody = OpenBankingUtils.reduceStringLength(requestBody, - OpenBankingConfigParser.getInstance().getMaxRequestBodyLength()); - responseBody = OpenBankingUtils.reduceStringLength(responseBody, - OpenBankingConfigParser.getInstance().getMaxResponseBodyLength()); - headers = OpenBankingUtils.reduceStringLength(headers, - OpenBankingConfigParser.getInstance().getMaxHeaderLength()); - - // Add the captured data put into the disputeResolutionData Map - disputeResolutionData.put(OpenBankingConstants.STATUS_CODE, statusCode); - disputeResolutionData.put(OpenBankingConstants.HTTP_METHOD, httpMethod); - disputeResolutionData.put(OpenBankingConstants.ELECTED_RESOURCE, electedResource); - disputeResolutionData.put(OpenBankingConstants.TIMESTAMP, unixTimestamp); - disputeResolutionData.put(OpenBankingConstants.HEADERS, headers); - disputeResolutionData.put(OpenBankingConstants.RESPONSE_BODY, responseBody); - disputeResolutionData.put(OpenBankingConstants.REQUEST_BODY, requestBody); - - //Checking configurations to publish Dispute Data - if (OpenBankingUtils.isPublishableDisputeData(statusCode)) { - OBDataPublisherUtil.publishData(OpenBankingConstants.DISPUTE_RESOLUTION_STREAM_NAME, - OpenBankingConstants.DISPUTE_RESOLUTION_STREAM_VERSION, disputeResolutionData); - } - - return true; - } - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/throttling/OBThrottlingExtensionImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/throttling/OBThrottlingExtensionImpl.java deleted file mode 100644 index 3ad97057..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/throttling/OBThrottlingExtensionImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.throttling; - -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseStatus; -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.ResponseContextDTO; -import org.wso2.carbon.apimgt.common.gateway.extensionlistener.ExtensionListener; - -/** - * Throttling Extension listener implementation for OB. - */ -public class OBThrottlingExtensionImpl implements ExtensionListener { - - @Override - public ExtensionResponseDTO preProcessRequest(RequestContextDTO requestContextDTO) { - - ExtensionResponseDTO responseDTO = null; - ThrottleDataPublisher throttleDataPublisher = GatewayDataHolder.getInstance().getThrottleDataPublisher(); - if (throttleDataPublisher != null) { - responseDTO = new ExtensionResponseDTO(); - responseDTO.setCustomProperty(throttleDataPublisher.getCustomProperties(requestContextDTO)); - responseDTO.setResponseStatus(ExtensionResponseStatus.CONTINUE.toString()); - } - return responseDTO; - - } - - @Override - public ExtensionResponseDTO postProcessRequest(RequestContextDTO requestContextDTO) { - - return null; - } - - @Override - public ExtensionResponseDTO preProcessResponse(ResponseContextDTO responseContextDTO) { - - return null; - } - - @Override - public ExtensionResponseDTO postProcessResponse(ResponseContextDTO responseContextDTO) { - - return null; - } - - @Override - public String getType() { - - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/throttling/ThrottleDataPublisher.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/throttling/ThrottleDataPublisher.java deleted file mode 100644 index 4da2df7f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/throttling/ThrottleDataPublisher.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.throttling; - -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; - -import java.util.Map; - -/** - * Throttling data publisher interface. - */ -public interface ThrottleDataPublisher { - - public Map getCustomProperties(RequestContextDTO requestContextDTO); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewayConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewayConstants.java deleted file mode 100644 index 9691cfed..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewayConstants.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.util; - -/** - * Gateway common constants class. - */ -public class GatewayConstants { - - public static final String CONTENT_TYPE_TAG = "Content-Type"; - public static final String CONTENT_LENGTH = "Content-Length"; - public static final String JWT_CONTENT_TYPE = "application/jwt"; - public static final String JSON_CONTENT_TYPE = "application/json"; - public static final String JOSE_CONTENT_TYPE = "application/jose"; - public static final String APPLICATION_XML_CONTENT_TYPE = "application/xml"; - public static final String TEXT_XML_CONTENT_TYPE = "text/xml"; - public static final String GET_HTTP_METHOD = "GET"; - public static final String POST_HTTP_METHOD = "POST"; - public static final String PUT_HTTP_METHOD = "PUT"; - public static final String PATCH_HTTP_METHOD = "PATCH"; - public static final String DELETE_HTTP_METHOD = "DELETE"; - public static final String ACCEPT = "Accept"; - public static final String AUTH_HEADER = "Authorization"; - public static final String BASIC_TAG = "Basic "; - public static final String BEARER_TAG = "Bearer "; - public static final String PUBLISHER_API_PATH = "api/am/publisher/apis/"; - public static final String SWAGGER_ENDPOINT = "/swagger"; - public static final String REGULATORY_CUSTOM_PROP = "x-wso2-regulatory-api"; - public static final String API_TYPE_CUSTOM_PROP = "x-wso2-api-type"; - public static final String IS_RETURN_RESPONSE = "isReturnResponse"; - public static final String MODIFIED_STATUS = "ModifiedStatus"; - public static final String APPLICATION = "application"; - public static final String APPLICATION_USER = "application_user"; - public static final String AXIS2_MTLS_CERT_PROPERTY = "ssl.client.auth.cert.X509"; - public static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; - public static final String END_CERT = "-----END CERTIFICATE-----"; - - //dcr related configs - public static final String AM_APP_NAME_CACHEKEY = "APP_NAME"; - public static final String APP_CREATE_URL = "APP_CREATION_URL"; - public static final String KEY_MAP_URL = "KEY_MAPPING_URL"; - public static final String API_RETRIEVE_URL = "API_RETRIEVAL_URL"; - public static final String API_SUBSCRIBE_URL = "API_SUBSCRIBE_URL"; - public static final String API_GET_SUBSCRIBED = "API_GET_SUBSCRIPTIONS"; - public static final String TOKEN_URL = "TOKEN_URL"; - public static final String USERNAME = "userName"; - public static final String IAM_DCR_URL = "DCR_Endpoint"; - public static final String PASSWORD = "password"; - public static final String IAM_HOSTNAME = "IAM_Hostname"; - public static final String VALIDATE_JWT = "DCR.RequestJWTValidation"; - - - //Config elements - public static final String CONSENT_VALIDATION_ENDPOINT_TAG = "Gateway.ConsentValidationEndpoint"; - public static final String KEYSTORE_LOCATION_TAG = "Security.InternalKeyStore.Location"; - public static final String KEYSTORE_PASSWORD_TAG = "Security.InternalKeyStore.Password"; - public static final String SIGNING_ALIAS_TAG = "Security.InternalKeyStore.KeyAlias"; - public static final String SIGNING_KEY_PASSWORD = "Security.InternalKeyStore.KeyPassword"; - public static final String API_KEY_VALIDATOR_USERNAME = "APIKeyValidator.Username"; - public static final String API_KEY_VALIDATOR_PASSWORD = "APIKeyValidator.Password"; - public static final String PUBLISHER_HOSTNAME = "PublisherURL"; - public static final String CONTEXT_PROP_CACHE_KEY = "_contextProp"; - public static final String ANALYTICS_PROP_CACHE_KEY = "_analyticsData"; - public static final String API_DATA_STREAM = "APIInputStream"; - public static final String API_DATA_VERSION = "1.0.0"; - public static final String ERROR_STATUS_PROP = "errorStatusCode"; - public static final String CONSENT_ID_CLAIM_NAME = "Identity.ConsentIDClaimName"; - public static final String REQUEST_ROUTER = "Gateway.RequestRouter"; - public static final String GATEWAY_CACHE_EXPIRY = "Gateway.Cache.GatewayCache.CacheAccessExpiry"; - public static final String GATEWAY_CACHE_MODIFIEDEXPIRY = "Gateway.Cache.GatewayCache.CacheModifiedExpiry"; - public static final String GATEWAY_THROTTLE_DATAPUBLISHER = "Gateway.CustomThrottleDataPublisher"; - - public static final String CUSTOMER_CARE_OFFICER_SCOPE = "consents:read_all"; - - public static final String API_TYPE_CONSENT = "consent"; - public static final String API_TYPE_NON_REGULATORY = "non-regulatory"; - - // Idempotency - public static final String REQUEST_CACHE_KEY = "Request"; - public static final String CREATED_TIME_CACHE_KEY = "Created_Time"; - public static final String RESPONSE_CACHE_KEY = "Response"; - public static final String TRUE = "true"; - public static final String IDEMPOTENCY_KEY_CACHE_KEY = "Idempotency_Key"; - - // Error constants - public static final String INVALID_CLIENT = "invalid_client"; - public static final String INVALID_REQUEST = "invalid_request"; - public static final String CLIENT_CERTIFICATE_MISSING = "Invalid mutual TLS request. Client certificate is missing"; - public static final String CLIENT_CERTIFICATE_INVALID = "Invalid mutual TLS request. Client certificate is invalid"; - public static final String INVALID_GRANT_TYPE = "Access failure for API: grant type validation failed."; - public static final String INVALID_CREDENTIALS = "Invalid Credentials. Make sure you have provided the " + - "correct security credentials "; - public static final String MISSING_CREDENTIALS = "Invalid Credentials. Make sure your API invocation call " + - "has a header - 'Authorization'"; - public static final String TRANSPORT_CERT_NOT_FOUND = "Valid transport certificate not found in the request"; - public static final String TRANSPORT_CERT_MALFORMED = "Provided transport certificate is malformed"; - - // Error codes - public static final int API_AUTH_INVALID_CREDENTIALS = 900901; - public static final int API_AUTH_MISSING_CREDENTIALS = 900902; - - // Oauth2 constants - public static final String AUTHORIZED_USER_TYPE_CLAIM_NAME = "aut"; - public static final String DEFAULT = "default"; - public static final String OPENID = "openid"; - - // HTTP methods - public static final String GET = "GET"; - public static final String POST = "POST"; - public static final String PUT = "PUT"; - public static final String PATCH = "PATCH"; - public static final String DELETE = "DELETE"; - - // Grant types - public static final String CLIENT_CREDENTIALS = "client_credentials"; - public static final String AUTHORIZATION_CODE = "authorization_code"; - public static final String IMPLICIT = "Implicit"; - public static final String PASSWORD_GRANT = "Password"; - - //Dispute resolution constants - public static final String UNKNOWN = "Unknown"; - public static final String ERROR_CODE = "ERROR_CODE"; - public static final String HTTP_RESPONSE_STATUS_CODE = "HTTP_RESPONSE_STATUS_CODE"; - public static final String CUSTOM_HTTP_SC = "CUSTOM_HTTP_SC"; - public static final String HTTP_SC = "HTTP_SC"; - public static final String HTTP_METHOD = "api.ut.HTTP_METHOD"; - public static final String API_BODY = "API"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewaySignatureHandlingUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewaySignatureHandlingUtils.java deleted file mode 100644 index 25571307..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewaySignatureHandlingUtils.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.util; - -import com.nimbusds.jose.JOSEObjectType; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.util.Base64URL; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.identity.IdentityConstants; -import com.wso2.openbanking.accelerator.common.identity.retriever.ServerIdentityRetriever; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import org.apache.commons.lang.StringUtils; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.util.HashMap; -import java.util.Optional; - -/** - * Utility class for Signature Handling. - */ -public class GatewaySignatureHandlingUtils { - - private static final String B64_CLAIM_KEY = "b64"; - - /** - * Returns the JWS Header. - * @param kid Key id of the signing certificate. - * @param criticalParameters Hashmap of critical paramters - * @param algorithm Signing algorithm - * @return JWSHeader returns Jws Header - */ - public static JWSHeader constructJWSHeader(String kid, HashMap criticalParameters, - JWSAlgorithm algorithm) { - return new JWSHeader.Builder(algorithm) - .keyID(kid) - .type(JOSEObjectType.JOSE) - .criticalParams(criticalParameters.keySet()) - .customParams(criticalParameters) - .build(); - } - - /** - * Creates a JWS Object. - * @param header JWS header - * @param responsePayload response payload as a string - * @return JWSObject jws object created - */ - public static JWSObject constructJWSObject(JWSHeader header, String responsePayload) { - return new JWSObject(header, new Payload(responsePayload)); - } - - /** - * Returns the signing input with encoded jws header and un-encoded payload. - * @param jwsHeader JWS Header - * @param payloadString Response payload - * @return signing input - * @throws UnsupportedEncodingException throws UnsupportedEncodingException Exception - */ - public static byte[] getSigningInput(JWSHeader jwsHeader, String payloadString) - throws UnsupportedEncodingException { - - String combinedInput = jwsHeader.toBase64URL().toString() + "." + payloadString; - return combinedInput.getBytes(StandardCharsets.UTF_8); - } - - /** - * Method to create a detached jws. - * @param jwsHeader header part of the JWS - * @param signature signature part of the JWS - * @return String Detached JWS - */ - public static String createDetachedJws(JWSHeader jwsHeader, Base64URL signature) { - - return jwsHeader.toBase64URL().toString() + ".." + signature.toString(); - } - - /** - * Loads the KID of the signing certificate. - * @return String Key ID of the public key - */ - @Generated(message = "Excluding from unit tests since there is a call to a method " + - "in Common Module") - public static String getSigningKeyId() { - - return OpenBankingConfigParser.getInstance().getOBIdnRetrieverSigningCertificateKid(); - } - - /** - * Returns the signing key. - * - * @return Key Signing key - * @throws OpenBankingExecutorException throws OpenBanking Exception - */ - @Generated(message = "Excluding from unit tests since there is a call to a method " + - "in Common Module") - public static Optional getSigningKey() throws OpenBankingExecutorException { - - try { - return ServerIdentityRetriever.getPrimaryCertificate(IdentityConstants.CertificateType.SIGNING); - } catch (OpenBankingException e) { - throw new OpenBankingExecutorException("Unable to load primary signing certificate", e); - } - } - - @Generated(message = "Excluding from unit tests since a signer is required to create a valid JWSObject") - public static String createDetachedJws(String serializedJws) { - - String[] jwsParts = StringUtils.split(serializedJws, "."); - return jwsParts[0] + ".." + jwsParts[2]; - } - - /** - * JWSAlgorithm to be returned in JWS header when signing. - * can be extended at toolkit level. - * - * @return JWSAlgorithm the signing algorithm defined to use in configs - */ - @Generated(message = "Excluding from unit tests since there is a call to a method " + - "in Common Module") - public static JWSAlgorithm getSigningAlgorithm() { - - String alg = OpenBankingConfigParser.getInstance().getJwsResponseSigningAlgorithm(); - return JWSAlgorithm.parse(alg); - } - - /** - * If the b64 header is not available or is true, it is verifiable. - * - * @param jwsObject The reconstructed jws object parsed from x-jws-signature - * @return Boolean - */ - public static boolean isB64HeaderVerifiable(JWSObject jwsObject) { - - JWSHeader jwsHeader = jwsObject.getHeader(); - Object b64Value = jwsHeader.getCustomParam(B64_CLAIM_KEY); - return b64Value != null ? ((Boolean) b64Value) : true; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewayUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewayUtils.java deleted file mode 100644 index 15a10fdc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/GatewayUtils.java +++ /dev/null @@ -1,829 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.util; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.crypto.ECDSASigner; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.util.Base64URL; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.security.OAuthFlows; -import io.swagger.v3.oas.models.security.SecurityRequirement; -import io.swagger.v3.oas.models.security.SecurityScheme; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.synapse.MessageContext; -import org.apache.synapse.commons.json.JsonUtil; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.core.axis2.Axis2Sender; -import org.apache.synapse.transport.nhttp.NhttpConstants; -import org.apache.synapse.transport.passthru.PassThroughConstants; -import org.apache.synapse.transport.passthru.util.RelayUtils; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.XML; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.security.PrivateKey; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.security.interfaces.ECPrivateKey; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import javax.ws.rs.core.MediaType; -import javax.xml.stream.XMLStreamException; - -/** - * Utility methods used in gateway. - */ -public class GatewayUtils { - private static final Log log = LogFactory.getLog(GatewayUtils.class); - - private static final String SOAP_ENV_START_TAG = ""; - private static final String SOAP_ENV_END_TAG = ""; - - /** - * Method to decode the base64 encoded JSON payload. - * - * @param payload base64 encoded payload - * @return Decoded JSON Object - * @throws UnsupportedEncodingException When encoding is not UTF-8 - */ - public static JSONObject decodeBase64(String payload) throws UnsupportedEncodingException { - - return new JSONObject(new String(Base64.getDecoder().decode(payload), - String.valueOf(StandardCharsets.UTF_8))); - } - - /** - * Method to extract JWT payload section as a string. - * - * @param jwtString full JWT - * @return Payload section of JWT - */ - public static String getPayloadFromJWT(String jwtString) { - - return jwtString.split("\\.")[1]; - } - - /** - * Method to retrieve payload as a String from XML. - * This method expects 'xml-multiple' instruction in xmlPayload to transform single element json arrays. - * synapse.commons.json.output.xmloutMultiplePI=true should be set in synapse.properties file. - * - * This method is deprecated. Use getXMLPayloadToSign method instead. - * - * @param xmlPayload Payload in XML format - * @return String version of JSON object - */ - @Deprecated - public static String getPayloadFromXML(String xmlPayload) throws OpenBankingException { - - String jsonString = null; - try { - OMElement omElement = AXIOMUtil.stringToOM(xmlPayload); - jsonString = JsonUtil.toJsonString(omElement).toString(); - } catch (AxisFault e) { - log.error("Error occurred while reading the xml payload"); - throw new OpenBankingException("Error occurred while reading the xml payload", e); - } catch (XMLStreamException e) { - log.error("Error occurred while transforming the xml payload to json"); - throw new OpenBankingException("Error occurred while transforming the xml payload to json", e); - } - JSONObject jsonObject = new JSONObject(jsonString); - return jsonObject.has("Body") ? jsonObject.get("Body").toString() : null; - } - - /** - * Method to retrieve payload from response with xml Payload. - * - * @param xmlPayload Payload in XML format - * @return String payload - */ - public static String getXMLPayloadToSign(String xmlPayload) throws OpenBankingException { - - try { - OMElement omElement = AXIOMUtil.stringToOM(xmlPayload); - OMElement firstElement = (OMElement) omElement.getFirstOMChild(); - if (firstElement != null) { - return firstElement.toString(); - } else { - return ""; - } - } catch (XMLStreamException e) { - log.error("Error occurred while transforming the xml payload."); - throw new OpenBankingException("Error occurred while transforming the xml payload", e); - } - } - - public static String getTextPayload(String payload) { - - return XML.toJSONObject(payload).getJSONObject("soapenv:Body").getJSONObject("text").getString("content"); - - } - - /** - * Method to obatain basic auth header. - * - * @param username Username of Auth header - * @param password Password of Auth header - * @return basic auth header - */ - public static String getBasicAuthHeader(String username, String password) { - - byte[] authHeader = Base64.getEncoder().encode((username + ":" + password).getBytes(StandardCharsets.UTF_8)); - return GatewayConstants.BASIC_TAG + new String(authHeader, StandardCharsets.UTF_8); - } - - /** - * Method to obtain swagger definition from publisher API. - * - * @param apiId ID of the API - * @return String of swagger definition - */ - @Generated(message = "Cannot test without running APIM. Integration test will be written for this") - public static String getSwaggerDefinition(String apiId) { - - String publisherHostName = - GatewayDataHolder.getInstance().getOpenBankingConfigurationService() - .getConfigurations() - .get(GatewayConstants.PUBLISHER_HOSTNAME).toString(); - - String publisherAPIURL = publisherHostName.endsWith("/") ? - publisherHostName + GatewayConstants.PUBLISHER_API_PATH + apiId + GatewayConstants.SWAGGER_ENDPOINT : - publisherHostName + "/" + GatewayConstants.PUBLISHER_API_PATH + apiId + - GatewayConstants.SWAGGER_ENDPOINT; - - HttpGet httpGet = new HttpGet(publisherAPIURL); - String userName = getAPIMgtConfig(GatewayConstants.API_KEY_VALIDATOR_USERNAME); - String password = getAPIMgtConfig(GatewayConstants.API_KEY_VALIDATOR_PASSWORD); - - httpGet.setHeader(GatewayConstants.AUTH_HEADER, GatewayUtils.getBasicAuthHeader(userName, password)); - HttpResponse response = null; - try { - response = GatewayDataHolder.getHttpClient().execute(httpGet); - InputStream in = response.getEntity().getContent(); - return IOUtils.toString(in, String.valueOf(StandardCharsets.UTF_8)); - } catch (IOException | OpenBankingException e) { - throw new OpenBankingRuntimeException("Failed to retrieve swagger definition from API", e); - } - } - - /** - * Method to read API mgt configs when key is given. - * - * @param key config key - * @return config value - */ - public static String getAPIMgtConfig(String key) { - - return GatewayDataHolder.getInstance() - .getApiManagerConfigurationService().getAPIManagerConfiguration().getFirstProperty(key); - } - - public static boolean isValidJWTToken(String jwtString) { - - String[] jwtPart = jwtString.split("\\."); - if (jwtPart.length != 3) { - return false; - } - try { - decodeBase64(jwtPart[0]); - decodeBase64(jwtPart[1]); - } catch (UnsupportedEncodingException | JSONException | IllegalArgumentException e) { - return false; - } - return true; - } - - /** - * Check the content type and http method of the request. - * - * @param contentType - contentType - * @param httpMethod - httpMethod - * @return - */ - public static boolean isEligibleRequest(String contentType, String httpMethod) { - - return (contentType.startsWith(GatewayConstants.JSON_CONTENT_TYPE) || - contentType.startsWith(GatewayConstants.APPLICATION_XML_CONTENT_TYPE) || - contentType.startsWith(GatewayConstants.TEXT_XML_CONTENT_TYPE)) && - (GatewayConstants.POST_HTTP_METHOD.equals(httpMethod) || GatewayConstants.PUT_HTTP_METHOD - .equals(httpMethod)); - } - - /** - * Check the content type and http method of the response. - * - * @param contentType - contentType - * @param httpMethod - httpMethod - * @return - */ - public static boolean isEligibleResponse(String contentType, String httpMethod) { - - return (contentType.startsWith(GatewayConstants.JSON_CONTENT_TYPE) || - contentType.startsWith(GatewayConstants.APPLICATION_XML_CONTENT_TYPE) || - contentType.startsWith(GatewayConstants.TEXT_XML_CONTENT_TYPE)) && - (GatewayConstants.GET_HTTP_METHOD.equals(httpMethod) || GatewayConstants. - POST_HTTP_METHOD.equals(httpMethod) || GatewayConstants.PUT_HTTP_METHOD.equals(httpMethod) - || GatewayConstants.PATCH_HTTP_METHOD.equals(httpMethod) || GatewayConstants. - DELETE_HTTP_METHOD.equals(httpMethod)); - } - - /** - * Method to extract request payload from OBAPIRequestContext. - * - * @param obapiRequestContext - * @param requestHeaders - * @return - */ - public static Optional extractRequestPayload(OBAPIRequestContext obapiRequestContext, - Map requestHeaders) - throws OpenBankingException { - - Optional payloadString = Optional.empty(); - - if (requestHeaders.containsKey(GatewayConstants.CONTENT_TYPE_TAG)) { - if (requestHeaders.get(GatewayConstants.CONTENT_TYPE_TAG).contains( - GatewayConstants.TEXT_XML_CONTENT_TYPE) - || requestHeaders.get(GatewayConstants.CONTENT_TYPE_TAG).contains( - GatewayConstants.APPLICATION_XML_CONTENT_TYPE)) { - try { - payloadString = Optional.of(GatewayUtils.getXMLPayloadToSign( - obapiRequestContext.getMsgInfo().getPayloadHandler().consumeAsString())); - } catch (Exception e) { - throw new OpenBankingException("Internal Server Error, Unable to process Payload"); - } - } else { - payloadString = Optional.ofNullable(obapiRequestContext.getRequestPayload()); - } - } else { - payloadString = Optional.ofNullable(obapiRequestContext.getRequestPayload()); - } - - return payloadString; - } - - /** - * Method to extract response payload from OBAPIResponseContext. - * - * @param obapiResponseContext - * @param responseHeaders - * @return - */ - public static Optional extractResponsePayload(OBAPIResponseContext obapiResponseContext, - Map responseHeaders) - throws OpenBankingException { - - Optional payloadString = Optional.empty(); - - if (responseHeaders.containsKey(GatewayConstants.CONTENT_TYPE_TAG)) { - if (responseHeaders.get(GatewayConstants.CONTENT_TYPE_TAG).contains( - GatewayConstants.TEXT_XML_CONTENT_TYPE) - || responseHeaders.get(GatewayConstants.CONTENT_TYPE_TAG).contains( - GatewayConstants.APPLICATION_XML_CONTENT_TYPE)) { - try { - payloadString = Optional.of(GatewayUtils.getXMLPayloadToSign( - obapiResponseContext.getMsgInfo().getPayloadHandler().consumeAsString())); - } catch (Exception e) { - throw new OpenBankingException("Internal Server Error, Unable to process Payload"); - } - } else { - payloadString = Optional.ofNullable(obapiResponseContext.getResponsePayload()); - } - } else { - payloadString = Optional.ofNullable(obapiResponseContext.getResponsePayload()); - } - - return payloadString; - } - - /** - * Returns the JWS with a detached payload. - * @param payloadString response payload - * @param criticalParameters Critical parameters - * @return String Detached Jws Signature - * @throws JOSEException throws JOSEException Exception - * @throws OpenBankingExecutorException throws OpenBanking Executor Exception - */ - @Generated(message = "Excluding from unit tests since it is covered by other methods") - public static String constructJWSSignature(String payloadString, HashMap criticalParameters) - throws OpenBankingExecutorException, JOSEException { - - String detachedJWS; - - Optional signingKey; - - // Get from config parser - JWSAlgorithm algorithm = GatewaySignatureHandlingUtils.getSigningAlgorithm(); - - // Get signing certificate of ASPSP from keystore - signingKey = GatewaySignatureHandlingUtils.getSigningKey(); - - if (signingKey.isPresent()) { - // Create a new JWSSigner - JWSSigner signer; - Key privateKey = signingKey.get(); - - // Retrieve kid or empty string for signingKeyId - String signingKeyId = GatewaySignatureHandlingUtils.getSigningKeyId(); - - if (StringUtils.isBlank(signingKeyId)) { - throw new OpenBankingExecutorException("The kid is not present to sign."); - } - - JWSHeader jwsHeader = GatewaySignatureHandlingUtils.constructJWSHeader(signingKeyId, - criticalParameters, algorithm); - JWSObject jwsObject = GatewaySignatureHandlingUtils.constructJWSObject(jwsHeader, - payloadString); - - if (privateKey.getAlgorithm().equals("RSA")) { - // If the signing key is an RSA Key - signer = new RSASSASigner((PrivateKey) privateKey); - } else if (privateKey.getAlgorithm().equals("EC")) { - // If the signing key is an EC Key - signer = new ECDSASigner((ECPrivateKey) privateKey); - } else { - throw new JOSEException("The \"" + privateKey.getAlgorithm() + - "\" algorithm is not supported by the Solution"); - } - - try { - // Check if payload is b64 encoded or un-encoded - if (GatewaySignatureHandlingUtils.isB64HeaderVerifiable(jwsObject)) { - // b64=true - jwsObject.sign(signer); - String serializedJws = jwsObject.serialize(); - detachedJWS = GatewaySignatureHandlingUtils.createDetachedJws(serializedJws); - } else { - // b64=false - // Produces the signature with un-encoded payload. - // which is the encoded header + ".." + the encoded signature - Base64URL signature = signer.sign(jwsHeader, - GatewaySignatureHandlingUtils.getSigningInput(jwsHeader, payloadString)); - detachedJWS = GatewaySignatureHandlingUtils.createDetachedJws(jwsHeader, signature); - } - } catch (JOSEException | UnsupportedEncodingException e) { - throw new OpenBankingExecutorException("Unable to compute JWS signature", e); - } - return detachedJWS; - } else { - throw new OpenBankingExecutorException("Signing key is not present"); - } - } - - /** - * Method to handle internal server errors in JWS Signature validation. - * - * @param obapiRequestContext OB response context object - * @param message error message - */ - @Generated(message = "Excluding from unit tests since the method is for exception" + - "handling") - public static void handleRequestInternalServerError( - OBAPIRequestContext obapiRequestContext, String message, String errorCode) { - - OpenBankingExecutorError error = new OpenBankingExecutorError(errorCode, - "Internal server error", message, OpenBankingErrorCodes.SERVER_ERROR_CODE); - ArrayList executorErrors = obapiRequestContext.getErrors(); - executorErrors.add(error); - obapiRequestContext.setError(true); - obapiRequestContext.setErrors(executorErrors); - } - - /** - * Method to handle internal server errors in JWS Signature validation. - * - * @param obapiResponseContext OB response context object - * @param message error message - */ - @Generated(message = "Excluding from unit tests since the method is for exception" + - "handling") - public static void handleResponseInternalServerError( - OBAPIResponseContext obapiResponseContext, String message, String errorCode) { - - OpenBankingExecutorError error = new OpenBankingExecutorError(errorCode, - "Internal server error", message, OpenBankingErrorCodes.SERVER_ERROR_CODE); - ArrayList executorErrors = obapiResponseContext.getErrors(); - executorErrors.add(error); - obapiResponseContext.setError(true); - obapiResponseContext.setErrors(executorErrors); - } - - /** - * Method to get the userName with tenant domain. - * - * @param userName username - * @return username with tenant domain - */ - public static String getUserNameWithTenantDomain(String userName) { - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (userName.endsWith(tenantDomain)) { - return userName; - } else { - return userName + "@" + tenantDomain; - } - } - - /** - * Retrieve security definitions defined in the swagger. - * This method will return cached values if present, else will read swagger and cache the result. - * - * @param obApiRequestContext ob api request context - * @return list of allowed auth flows for the elected resource - */ - @Generated(message = "Ignoring since the method has covered in other tests") - public static List getAllowedOAuthFlows(OBAPIRequestContext obApiRequestContext) { - - List oauthFlows = new ArrayList<>(); - String httpMethod = obApiRequestContext.getMsgInfo().getHttpMethod(); - String cacheKey = obApiRequestContext.getMsgInfo().getElectedResource() + ":" + httpMethod; - GatewayCacheKey apiSecurityCacheKey = GatewayCacheKey.of(cacheKey); - - try { - oauthFlows = - (List) GatewayDataHolder.getGatewayCache().getFromCacheOrRetrieve(apiSecurityCacheKey, - () -> { - OpenAPI openAPI = obApiRequestContext.getOpenAPI(); - String electedResource = obApiRequestContext.getMsgInfo().getElectedResource(); - return getAllowedOAuthFlowsFromSwagger(openAPI, electedResource, httpMethod); - }); - } catch (OpenBankingException e) { - log.error("Unable to cache or retrieve from API Security Cache", e); - } - return oauthFlows; - } - - /** - * Read allowed security schemes defined in the swagger for the given resource. - * - * @param openAPI open API object - * @param electedResource elected resource - * @param httpMethod http method - * @return allowed security scheme - */ - public static List getAllowedOAuthFlowsFromSwagger(OpenAPI openAPI, String electedResource, - String httpMethod) { - - Map securitySchemes = openAPI.getComponents().getSecuritySchemes(); - HashMap> oAuthFlows = new HashMap<>(); - - for (Object scheme : securitySchemes.keySet()) { - OAuthFlows flows = securitySchemes.get(scheme.toString()).getFlows(); - - if (flows != null) { - ArrayList allowedFlowsPerScheme = new ArrayList<>(); - - if (flows.getAuthorizationCode() != null) { - allowedFlowsPerScheme.add(GatewayConstants.AUTHORIZATION_CODE); - } - if (flows.getImplicit() != null) { - allowedFlowsPerScheme.add(GatewayConstants.IMPLICIT); - } - if (flows.getClientCredentials() != null) { - allowedFlowsPerScheme.add(GatewayConstants.CLIENT_CREDENTIALS); - } - if (flows.getPassword() != null) { - allowedFlowsPerScheme.add(GatewayConstants.PASSWORD_GRANT); - } - oAuthFlows.put(scheme.toString(), allowedFlowsPerScheme); - } - } - - // get security flows defined for the resource - PathItem electedPath = openAPI.getPaths().get(electedResource); - List resourceSecurity = null; - if (GatewayConstants.GET.equalsIgnoreCase(httpMethod)) { - resourceSecurity = electedPath.getGet().getSecurity(); - } else if (GatewayConstants.POST.equalsIgnoreCase(httpMethod)) { - resourceSecurity = electedPath.getPost().getSecurity(); - } else if (GatewayConstants.PUT.equalsIgnoreCase(httpMethod)) { - resourceSecurity = electedPath.getPut().getSecurity(); - } else if (GatewayConstants.PATCH.equalsIgnoreCase(httpMethod)) { - resourceSecurity = electedPath.getPatch().getSecurity(); - } else if (GatewayConstants.DELETE.equalsIgnoreCase(httpMethod)) { - resourceSecurity = electedPath.getDelete().getSecurity(); - } - - ArrayList allowedFlows = new ArrayList<>(); - List securityRequirementList = new ArrayList<>(); - if (resourceSecurity != null) { - for (Object security : resourceSecurity) { - // Adding the keys of each security requirement to a list - securityRequirementList.addAll(new ArrayList<>(((SecurityRequirement) security).keySet())); - } - } - - for (String requirement : securityRequirementList) { - if (GatewayConstants.DEFAULT.equalsIgnoreCase(requirement) || - GatewayConstants.OPENID.equalsIgnoreCase(requirement)) { - continue; - } - if (oAuthFlows.containsKey(requirement)) { - allowedFlows.addAll(oAuthFlows.get(requirement)); - } - } - - return allowedFlows; - } - - - /** - * Get bearer token payload. - * - * @param transportHeaders transport headers - * @return jwt token payload - * @throws OpenBankingExecutorException when authorization header not found in transport headers. - */ - public static String getBearerTokenPayload(Map transportHeaders) - throws OpenBankingExecutorException { - - String authorizationHeader = "Authorization"; - if (transportHeaders.containsKey(authorizationHeader)) { - try { - return transportHeaders.get(authorizationHeader).split(" ")[1].split("\\.")[1]; - } catch (ArrayIndexOutOfBoundsException e) { - log.debug("Invalid authorization header format", e); - throw new OpenBankingExecutorException("Invalid Credentials.", - String.valueOf(GatewayConstants.API_AUTH_INVALID_CREDENTIALS), - GatewayConstants.INVALID_CREDENTIALS); - } - } else { - log.debug("Missing Authorization header"); - throw new OpenBankingExecutorException("Missing Credentials.", - String.valueOf(GatewayConstants.API_AUTH_MISSING_CREDENTIALS), - GatewayConstants.MISSING_CREDENTIALS); - } - } - - /** - * Get type of the token (application/ application user). - * - * @param tokenPayload jwt token payload - * @return token type - */ - public static String getTokenType(String tokenPayload) throws OpenBankingExecutorException { - - try { - JSONObject decodedPayload = new JSONObject(new String(Base64.getUrlDecoder().decode(tokenPayload), - StandardCharsets.UTF_8)); - return decodedPayload.getString(GatewayConstants.AUTHORIZED_USER_TYPE_CLAIM_NAME); - } catch (RuntimeException e) { - log.error("Invalid tokenPayload", e); - throw new OpenBankingExecutorException("Invalid Credentials.", - String.valueOf(GatewayConstants.API_AUTH_INVALID_CREDENTIALS), - GatewayConstants.INVALID_CREDENTIALS); - } - } - - /** - * Validate the grant type against the swagger allowed auth flows. - * - * @param tokenType grant type in the token - * @param allowedOAuthFlows oauth flows allowed by swagger - * @throws OpenBankingExecutorException when incorrect grant type is provided - */ - public static void validateGrantType(String tokenType, List allowedOAuthFlows) - throws OpenBankingExecutorException { - - if ((GatewayConstants.APPLICATION.equalsIgnoreCase(tokenType) && - allowedOAuthFlows.contains(GatewayConstants.CLIENT_CREDENTIALS)) || - (GatewayConstants.APPLICATION_USER.equalsIgnoreCase(tokenType) && - allowedOAuthFlows.contains(GatewayConstants.AUTHORIZATION_CODE))) { - log.debug("Valid Access Token type found"); - } else { - log.error("Incorrect Access Token Type is provided"); - throw new OpenBankingExecutorException(GatewayConstants.INVALID_GRANT_TYPE, - OpenBankingErrorCodes.INVALID_GRANT_TYPE_CODE, "Incorrect Access Token Type provided"); - } - } - - /** - * Build Message and extract payload. - * - * @param axis2MC message context - * @return optional json message - * @throws OpenBankingException thrown if unable to build - */ - public static Optional buildMessagePayloadFromMessageContext( - org.apache.axis2.context.MessageContext axis2MC, Map headers) throws OpenBankingException { - - String requestPayload = null; - boolean isMessageContextBuilt = isMessageContextBuilt(axis2MC); - if (!isMessageContextBuilt) { - // Build Axis2 Message. - try { - RelayUtils.buildMessage(axis2MC); - } catch (IOException | XMLStreamException e) { - throw new OpenBankingException("Unable to build axis2 message", e); - } - } - - if (headers.containsKey(GatewayConstants.CONTENT_TYPE_TAG)) { - if (headers.get(GatewayConstants.CONTENT_TYPE_TAG).toString().contains( - GatewayConstants.TEXT_XML_CONTENT_TYPE) - || headers.get(GatewayConstants.CONTENT_TYPE_TAG).toString().contains( - GatewayConstants.APPLICATION_XML_CONTENT_TYPE) - || headers.get(GatewayConstants.CONTENT_TYPE_TAG).toString().contains( - GatewayConstants.JWT_CONTENT_TYPE)) { - - OMElement payload = axis2MC.getEnvelope().getBody().getFirstElement(); - if (payload != null) { - requestPayload = payload.toString(); - } else { - requestPayload = ""; - } - } else { - // Get JSON Stream and cast to string - try { - InputStream jsonPayload = JsonUtil.getJsonPayload(axis2MC); - if (jsonPayload != null) { - requestPayload = IOUtils.toString(JsonUtil.getJsonPayload(axis2MC), - StandardCharsets.UTF_8.name()); - } - - } catch (IOException e) { - throw new OpenBankingException("Unable to read payload stream", e); - } - } - } - return Optional.ofNullable(requestPayload); - } - - /** - * Util method to check whether the message context is already built. - * - * @param axis2MC axis2 message context - * @return true if message context is already built - */ - public static boolean isMessageContextBuilt(org.apache.axis2.context.MessageContext axis2MC) { - - boolean isMessageContextBuilt = false; - Object messageContextBuilt = axis2MC.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED); - if (messageContextBuilt != null) { - isMessageContextBuilt = (Boolean) messageContextBuilt; - } - return isMessageContextBuilt; - } - - /** - * Return JSON ResponseError for SynapseHandler. - * - * @param messageContext messages context. - * @param code response code. - * @param jsonPayload json payload. - */ - public static void returnSynapseHandlerJSONError(MessageContext messageContext, String code, String jsonPayload) { - - org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext). - getAxis2MessageContext(); - axis2MC.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE); - try { - RelayUtils.discardRequestMessage(axis2MC); - } catch (AxisFault axisFault) { - log.error("ResponseError occurred while discarding the message", axisFault); - } - setJsonFaultPayloadToMessageContext(messageContext, jsonPayload); - sendSynapseHandlerFaultResponse(messageContext, code); - } - - /** - * Setting JSON payload as fault message to messageContext. - * @param messageContext messages context. - * @param payload json payload. - */ - private static void setJsonFaultPayloadToMessageContext(MessageContext messageContext, String payload) { - - org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) - .getAxis2MessageContext(); - - axis2MessageContext.setProperty(Constants.Configuration.MESSAGE_TYPE, MediaType.APPLICATION_JSON); - - try { - JsonUtil.getNewJsonPayload(axis2MessageContext, payload, true, true); - } catch (AxisFault axisFault) { - log.error("Unable to set JSON payload to fault message", axisFault); - } - } - - /** - * Send synapseHandler fault response. - * @param messageContext messages context. - * @param status error code. - */ - private static void sendSynapseHandlerFaultResponse(MessageContext messageContext, String status) { - - org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext). - getAxis2MessageContext(); - - axis2MC.setProperty(NhttpConstants.HTTP_SC, status); - messageContext.setResponse(true); - messageContext.setProperty("RESPONSE", "true"); - messageContext.setTo(null); - axis2MC.removeProperty(Constants.Configuration.CONTENT_TYPE); - Axis2Sender.sendBack(messageContext); - } - - /** - * Method to get json error body in OAuth2 format. - * @return json error body - */ - public static String getOAuth2JsonErrorBody(String error, String errorDescription) { - - JSONObject errorJSON = new JSONObject(); - errorJSON.put("error", error); - errorJSON.put("error_description", errorDescription); - return errorJSON.toString(); - } - - /** - * Convert X509Certificate to PEM encoded string. - * - * @param certificate X509Certificate - * @return PEM encoded string - */ - public static String getPEMEncodedCertificateString(X509Certificate certificate) - throws CertificateEncodingException { - - StringBuilder certificateBuilder = new StringBuilder(); - Base64.Encoder encoder = Base64.getEncoder(); - byte[] encoded = certificate.getEncoded(); - String base64Encoded = encoder.encodeToString(encoded); - - certificateBuilder.append(GatewayConstants.BEGIN_CERT); - certificateBuilder.append(base64Encoded); - certificateBuilder.append(GatewayConstants.END_CERT); - - return certificateBuilder.toString().replaceAll("\n", "+"); - } - - /** - * Extract Certificate from Message Context. - * - * @param ctx Message Context - * @return X509Certificate - */ - public static X509Certificate extractAuthCertificateFromMessageContext( - org.apache.axis2.context.MessageContext ctx) { - - Object sslCertObject = ctx.getProperty(GatewayConstants.AXIS2_MTLS_CERT_PROPERTY); - if (sslCertObject != null) { - X509Certificate[] certs = (X509Certificate[]) sslCertObject; - return certs[0]; - } else { - return null; - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/IdempotencyConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/IdempotencyConstants.java deleted file mode 100644 index b8991259..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/java/com/wso2/openbanking/accelerator/gateway/util/IdempotencyConstants.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; - -/** - * IdempotencyConstants. - */ -public class IdempotencyConstants { - - // config parser keys - public static final String IDEMPOTENCY_ALLOWED_TIME = "Gateway.Idempotency.AllowedTimeDuration"; - public static final String IDEMPOTENCY_CACHE_TIME_TO_LIVE = - "Gateway.Cache.IdempotencyValidationCache.CacheTimeToLive"; - public static final String IDEMPOTENCY_KEY_HEADER = "Gateway.Idempotency.IdempotencyKeyHeader"; - public static final String IDEMPOTENCY_IS_ENABLED = "Gateway.Idempotency.IsEnabled"; - - public static final String HTTP_STATUS = "httpStatus"; - public static final String PAYLOAD = "payload"; - - - /** - * Error. - */ - public static class Error { - - public static final String DATE_MISSING = "Date header is missing in the request"; - public static final String EXECUTOR_IDEMPOTENCY_KEY_ERROR = - "Error while handling Idempotency check.:Header." + getPathIdemKey();; - public static final String EXECUTOR_IDEMPOTENCY_KEY_FRAUDULENT = - "Idempotency check failed.:Header." + getPathIdemKey(); - public static final String HEADER_INVALID = "Header Invalid"; - public static final String IDEMPOTENCY_HANDLE_ERROR = - "Error occurred while handling the idempotency available request"; - - private static String getPathIdemKey() { - - return (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(IdempotencyConstants.IDEMPOTENCY_KEY_HEADER); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index fd470b2c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/resources/findbugs-include.xml deleted file mode 100644 index 649d044e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/DefaultRequestRouterTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/DefaultRequestRouterTest.java deleted file mode 100644 index 10892914..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/DefaultRequestRouterTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.test.util.TestUtil; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import io.swagger.v3.oas.models.OpenAPI; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * Test for default request router. - */ -public class DefaultRequestRouterTest { - - DefaultRequestRouter defaultRequestRouter; - OpenAPI openAPI; - - @BeforeClass - public void beforeClass() { - - defaultRequestRouter = new DefaultRequestRouter(); - defaultRequestRouter.setExecutorMap(TestUtil.initExecutors()); - openAPI = new OpenAPI(); - openAPI.setExtensions(new HashMap<>()); - } - - @Test(priority = 1) - public void testDCRRequestsForRouter() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO1 = new MsgInfoDTO(); - msgInfoDTO1.setResource("/anyAPIcall/register"); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO1); - Mockito.when(obapiRequestContext.getOpenAPI()).thenReturn(openAPI); - Mockito.when(obapiResponseContext.getMsgInfo()).thenReturn(msgInfoDTO1); - Assert.assertNotNull(defaultRequestRouter.getExecutorsForRequest(obapiRequestContext)); - Assert.assertNotNull(defaultRequestRouter.getExecutorsForResponse(obapiResponseContext)); - - } - - @Test(priority = 1) - public void testAccountRequestsForRouter() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO2 = new MsgInfoDTO(); - msgInfoDTO2.setResource("/anyAPIcall"); - Mockito.when(obapiRequestContext.getOpenAPI()).thenReturn(openAPI); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO2); - Mockito.when(obapiResponseContext.getMsgInfo()).thenReturn(msgInfoDTO2); - Assert.assertNotNull(defaultRequestRouter.getExecutorsForRequest(obapiRequestContext)); - Assert.assertNotNull(defaultRequestRouter.getExecutorsForResponse(obapiResponseContext)); - } - - @Test(priority = 2) - public void testNonRegulatoryAPIcall() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO2 = new MsgInfoDTO(); - msgInfoDTO2.setResource("/anyAPIcall"); - Map extensions = new HashMap<>(); - Map contextProps = new HashMap<>(); - extensions.put(GatewayConstants.API_TYPE_CUSTOM_PROP, GatewayConstants.API_TYPE_NON_REGULATORY); - contextProps.put(GatewayConstants.API_TYPE_CUSTOM_PROP, GatewayConstants.API_TYPE_NON_REGULATORY); - openAPI.setExtensions(extensions); - Mockito.when(obapiRequestContext.getOpenAPI()).thenReturn(openAPI); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO2); - Mockito.when(obapiResponseContext.getMsgInfo()).thenReturn(msgInfoDTO2); - Mockito.when(obapiResponseContext.getContextProps()).thenReturn(contextProps); - Assert.assertEquals(defaultRequestRouter.getExecutorsForRequest(obapiRequestContext).size(), 0); - Assert.assertEquals(defaultRequestRouter.getExecutorsForResponse(obapiResponseContext).size(), 0); - } - - @Test(priority = 2) - public void testRegulatoryAPIcall() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO2 = new MsgInfoDTO(); - msgInfoDTO2.setResource("/anyAPIcall"); - Map extensions = new HashMap<>(); - Map contextProps = new HashMap<>(); - extensions.put(GatewayConstants.API_TYPE_CUSTOM_PROP, GatewayConstants.API_TYPE_NON_REGULATORY); - contextProps.put(GatewayConstants.API_TYPE_CUSTOM_PROP, "regulatory"); - openAPI.setExtensions(extensions); - Mockito.when(obapiRequestContext.getOpenAPI()).thenReturn(openAPI); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO2); - Mockito.when(obapiResponseContext.getMsgInfo()).thenReturn(msgInfoDTO2); - Mockito.when(obapiResponseContext.getContextProps()).thenReturn(contextProps); - Assert.assertNotNull(defaultRequestRouter.getExecutorsForRequest(obapiRequestContext)); - Assert.assertNotNull(defaultRequestRouter.getExecutorsForResponse(obapiResponseContext)); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/TestOBExtensionImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/TestOBExtensionImpl.java deleted file mode 100644 index a59b5579..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/TestOBExtensionImpl.java +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.test.TestConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import org.apache.http.HttpStatus; -import org.json.JSONObject; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseStatus; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * Test for open Banking extension implementation. - */ -public class TestOBExtensionImpl { - - private static OBAPIRequestContext obapiRequestContext; - private static OBAPIResponseContext obapiResponseContext; - private static OBExtensionListenerImpl obExtensionListener = new OBExtensionListenerImpl(); - - @BeforeClass - public static void beforeClass() { - - } - - @Test(priority = 1) - public void testMinimumFlow() { - - obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(false); - Mockito.when(obapiRequestContext.getModifiedPayload()).thenReturn(null); - Mockito.when(obapiRequestContext.getAddedHeaders()).thenReturn(new HashMap<>()); - - obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiResponseContext.isError()).thenReturn(false); - Mockito.when(obapiResponseContext.getModifiedPayload()).thenReturn(null); - Mockito.when(obapiResponseContext.getAddedHeaders()).thenReturn(new HashMap<>()); - - ExtensionResponseDTO responseDTOForRequest = obExtensionListener.getResponseDTOForRequest(obapiRequestContext); - Assert.assertEquals(responseDTOForRequest.getResponseStatus(), ExtensionResponseStatus.CONTINUE.toString()); - Assert.assertNull(responseDTOForRequest.getHeaders()); - Assert.assertNull(responseDTOForRequest.getPayload()); - Assert.assertNull(responseDTOForRequest.getCustomProperty()); - Assert.assertEquals(responseDTOForRequest.getStatusCode(), 0); - - ExtensionResponseDTO responseDTOForResponse = - obExtensionListener.getResponseDTOForResponse(obapiResponseContext); - - Assert.assertEquals(responseDTOForResponse.getResponseStatus(), ExtensionResponseStatus.CONTINUE.toString()); - Assert.assertNull(responseDTOForResponse.getHeaders()); - Assert.assertNull(responseDTOForResponse.getPayload()); - Assert.assertNull(responseDTOForResponse.getCustomProperty()); - Assert.assertEquals(responseDTOForResponse.getStatusCode(), 0); - - } - - @Test(priority = 1) - public void testAddedHeaders() { - - obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(false); - Mockito.when(obapiRequestContext.getModifiedPayload()).thenReturn(null); - MsgInfoDTO msgInfoDTO = new MsgInfoDTO(); - msgInfoDTO.setHeaders(new HashMap<>()); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO); - Map addedHeaders = new HashMap<>(); - addedHeaders.put("custom", "header"); - Mockito.when(obapiRequestContext.getAddedHeaders()).thenReturn(addedHeaders); - - ExtensionResponseDTO responseDTOForRequest = obExtensionListener.getResponseDTOForRequest(obapiRequestContext); - Assert.assertEquals(responseDTOForRequest.getResponseStatus(), ExtensionResponseStatus.CONTINUE.toString()); - Assert.assertEquals(responseDTOForRequest.getHeaders().get("custom"), "header"); - Assert.assertNull(responseDTOForRequest.getPayload()); - Assert.assertNull(responseDTOForRequest.getCustomProperty()); - Assert.assertEquals(responseDTOForRequest.getStatusCode(), 0); - - Mockito.when(obapiResponseContext.isError()).thenReturn(false); - Mockito.when(obapiResponseContext.getModifiedPayload()).thenReturn(null); - Mockito.when(obapiResponseContext.getMsgInfo()).thenReturn(msgInfoDTO); - Mockito.when(obapiResponseContext.getAddedHeaders()).thenReturn(addedHeaders); - - ExtensionResponseDTO responseDTOForResponse = - obExtensionListener.getResponseDTOForResponse(obapiResponseContext); - Assert.assertEquals(responseDTOForResponse.getResponseStatus(), ExtensionResponseStatus.CONTINUE.toString()); - Assert.assertEquals(responseDTOForResponse.getHeaders().get("custom"), "header"); - Assert.assertNull(responseDTOForResponse.getPayload()); - Assert.assertNull(responseDTOForResponse.getCustomProperty()); - Assert.assertEquals(responseDTOForResponse.getStatusCode(), 0); - - } - - @Test(priority = 1) - public void testModifiedPayload() { - - obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(false); - Mockito.when(obapiRequestContext.getModifiedPayload()).thenReturn(TestConstants.CUSTOM_PAYLOAD); - Mockito.when(obapiRequestContext.getAddedHeaders()).thenReturn(new HashMap<>()); - - ExtensionResponseDTO responseDTOForRequest = obExtensionListener.getResponseDTOForRequest(obapiRequestContext); - Assert.assertEquals(responseDTOForRequest.getResponseStatus(), ExtensionResponseStatus.CONTINUE.toString()); - Assert.assertNull(responseDTOForRequest.getHeaders()); - Assert.assertNotNull(responseDTOForRequest.getPayload()); - Assert.assertNull(responseDTOForRequest.getCustomProperty()); - Assert.assertEquals(responseDTOForRequest.getStatusCode(), 0); - - Mockito.when(obapiResponseContext.isError()).thenReturn(false); - Mockito.when(obapiResponseContext.getModifiedPayload()).thenReturn(TestConstants.CUSTOM_PAYLOAD); - Mockito.when(obapiResponseContext.getAddedHeaders()).thenReturn(new HashMap<>()); - - ExtensionResponseDTO responseDTOForResponse = - obExtensionListener.getResponseDTOForResponse(obapiResponseContext); - Assert.assertEquals(responseDTOForResponse.getResponseStatus(), ExtensionResponseStatus.CONTINUE.toString()); - Assert.assertNull(responseDTOForResponse.getHeaders()); - Assert.assertNotNull(responseDTOForResponse.getPayload()); - Assert.assertNull(responseDTOForResponse.getCustomProperty()); - Assert.assertEquals(responseDTOForResponse.getStatusCode(), 0); - - } - - @Test(priority = 1) - public void testErrorFlow() { - - obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(true); - JSONObject errorJSON = new JSONObject(); - errorJSON.put("error", true); - Mockito.when(obapiRequestContext.getModifiedPayload()).thenReturn(errorJSON.toString()); - Mockito.when(obapiRequestContext.getAddedHeaders()).thenReturn(new HashMap<>()); - - obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiResponseContext.isError()).thenReturn(true); - Mockito.when(obapiResponseContext.getModifiedPayload()).thenReturn(errorJSON.toString()); - Mockito.when(obapiResponseContext.getAddedHeaders()).thenReturn(new HashMap<>()); - - ExtensionResponseDTO responseDTOForRequest = obExtensionListener.getResponseDTOForRequest(obapiRequestContext); - Assert.assertEquals(responseDTOForRequest.getResponseStatus(), ExtensionResponseStatus.RETURN_ERROR.toString()); - Assert.assertNull(responseDTOForRequest.getHeaders()); - Assert.assertNotNull(responseDTOForRequest.getPayload()); - Assert.assertNull(responseDTOForRequest.getCustomProperty()); - Assert.assertEquals(responseDTOForRequest.getStatusCode(), 500); - - ExtensionResponseDTO responseDTOForResponse = - obExtensionListener.getResponseDTOForResponse(obapiResponseContext); - - Assert.assertEquals(responseDTOForResponse.getResponseStatus(), - ExtensionResponseStatus.RETURN_ERROR.toString()); - Assert.assertNull(responseDTOForResponse.getHeaders()); - Assert.assertNotNull(responseDTOForResponse.getPayload()); - Assert.assertNull(responseDTOForResponse.getCustomProperty()); - Assert.assertEquals(responseDTOForResponse.getStatusCode(), 500); - - } - - @Test(priority = 1) - public void testFlowWithReturnResponseTrue() { - - Map contextProps = new HashMap<>(); - contextProps.put(GatewayConstants.IS_RETURN_RESPONSE, "true"); - contextProps.put(GatewayConstants.MODIFIED_STATUS, String.valueOf(HttpStatus.SC_CREATED)); - MsgInfoDTO msgInfoDTO = new MsgInfoDTO(); - msgInfoDTO.setHeaders(new HashMap<>()); - - obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(false); - Mockito.when(obapiRequestContext.getModifiedPayload()).thenReturn(null); - Mockito.when(obapiRequestContext.getAddedHeaders()).thenReturn(new HashMap<>()); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO); - Mockito.when(obapiRequestContext.getContextProps()).thenReturn(contextProps); - - obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiResponseContext.isError()).thenReturn(false); - Mockito.when(obapiResponseContext.getModifiedPayload()).thenReturn(null); - Mockito.when(obapiResponseContext.getAddedHeaders()).thenReturn(new HashMap<>()); - Mockito.when(obapiResponseContext.getMsgInfo()).thenReturn(msgInfoDTO); - Mockito.when(obapiResponseContext.getContextProps()).thenReturn(contextProps); - - ExtensionResponseDTO responseDTOForRequest = obExtensionListener.getResponseDTOForRequest(obapiRequestContext); - Assert.assertEquals(responseDTOForRequest.getResponseStatus(), ExtensionResponseStatus.RETURN_ERROR.toString()); - Assert.assertEquals(responseDTOForRequest.getStatusCode(), HttpStatus.SC_CREATED); - - ExtensionResponseDTO responseDTOForResponse = - obExtensionListener.getResponseDTOForResponse(obapiResponseContext); - - Assert.assertEquals(responseDTOForResponse.getResponseStatus(), - ExtensionResponseStatus.RETURN_ERROR.toString()); - Assert.assertEquals(responseDTOForResponse.getStatusCode(), HttpStatus.SC_CREATED); - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/UtilityTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/UtilityTest.java deleted file mode 100644 index 58c87c1f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/core/UtilityTest.java +++ /dev/null @@ -1,422 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.core; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import io.swagger.parser.OpenAPIParser; -import io.swagger.v3.oas.models.OpenAPI; -import org.json.JSONObject; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Test for utility methods used in gateway. - */ -public class UtilityTest { - - private static final String TEST_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwI" + - "iwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; - private static final String B64_PAYLOAD = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpva" + - "G4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"; - private static final String XML_PAYLOAD = "" + - "\n" + - " \n" + - " \n" + - " ABC/086\n" + - " TRF\n" + - " false\n" + - " \n" + - "

2012-09-29
\n" + - " \n" + - " \n" + - " \n" + - ""; - private String signingPayload = "\n" + - " \n" + - " \n" + - " ABC/086\n" + - " TRF\n" + - " false\n" + - " \n" + - "
2012-09-29
\n" + - "
\n" + - "
\n" + - "
\n" + - "
"; - private static final String APPLICATION = "APPLICATION"; - private static final String APPLICATION_USER = "APPLICATION_USER"; - - @Test(priority = 1) - public void testB64Encode() throws UnsupportedEncodingException { - - JSONObject payload = GatewayUtils.decodeBase64(B64_PAYLOAD); - Assert.assertEquals(payload.getString("sub"), "1234567890"); - Assert.assertEquals(payload.getString("name"), "John Doe"); - Assert.assertEquals(payload.getInt("iat"), 1516239022); - } - - @Test(priority = 1) - public void testJWTPayloadLoad() { - - Assert.assertEquals(GatewayUtils.getPayloadFromJWT(TEST_JWT), B64_PAYLOAD); - } - - @Test(priority = 1) - public void testBasicAuthHeader() { - - Assert.assertEquals(GatewayUtils.getBasicAuthHeader("admin", "admin"), - "Basic YWRtaW46YWRtaW4="); - } - - @Test(priority = 2) - public void testGetXMLPayloadToSign() throws OpenBankingException { - - Assert.assertEquals(GatewayUtils.getXMLPayloadToSign(XML_PAYLOAD), signingPayload); - } - - @Test (priority = 2) - public void testIsEligibleRequest() { - - Assert.assertTrue(GatewayUtils.isEligibleRequest(GatewayConstants.JSON_CONTENT_TYPE, - GatewayConstants.POST_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleRequest(GatewayConstants.APPLICATION_XML_CONTENT_TYPE, - GatewayConstants.POST_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleRequest(GatewayConstants.TEXT_XML_CONTENT_TYPE, - GatewayConstants.POST_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleRequest(GatewayConstants.JSON_CONTENT_TYPE, - GatewayConstants.PUT_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleRequest(GatewayConstants.APPLICATION_XML_CONTENT_TYPE, - GatewayConstants.PUT_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleRequest(GatewayConstants.TEXT_XML_CONTENT_TYPE, - GatewayConstants.PUT_HTTP_METHOD)); - } - - @Test (priority = 3) - public void testIsEligibleResponse() { - - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.JSON_CONTENT_TYPE, - GatewayConstants.POST_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.APPLICATION_XML_CONTENT_TYPE, - GatewayConstants.POST_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.TEXT_XML_CONTENT_TYPE, - GatewayConstants.POST_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.JSON_CONTENT_TYPE, - GatewayConstants.PUT_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.APPLICATION_XML_CONTENT_TYPE, - GatewayConstants.PUT_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.TEXT_XML_CONTENT_TYPE, - GatewayConstants.PUT_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.JSON_CONTENT_TYPE, - GatewayConstants.GET_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.APPLICATION_XML_CONTENT_TYPE, - GatewayConstants.GET_HTTP_METHOD)); - Assert.assertTrue(GatewayUtils.isEligibleResponse(GatewayConstants.TEXT_XML_CONTENT_TYPE, - GatewayConstants.GET_HTTP_METHOD)); - } - - @Test(description = "Test the extraction of grant type from jwt token payload") - public void getTokenTypeForUserAccessTokens() throws OpenBankingExecutorException { - - String tokenPayload = "eyJzdWIiOiJhZG1pbkB3c28yLmNvbUBjYXJib24uc3VwZXIiLCJhdXQiOiJBUFBMSUNBVElPTl9VU0VSIiwiY" + - "XVkIjoiZldwTmNEVzFZM3FwVFVwcHp3SGFGMnZaWllBYSIsIm5iZiI6MTYxNzc5NjM3OCwiZ3JhbnRfdHlwZSI6ImNsaWVudF9j" + - "cmVkZW50aWFscyIsImNvbnNlbnRfaWQiOiJPQl8xMjM0IiwiYXpwIjoiZldwTmNEVzFZM3FwVFVwcHp3SGFGMnZaWllBYSIsInN" + - "jb3BlIjoiYWNjb3VudHMgcGF5bWVudHMiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo5NDQ2L29hdXRoMi90b2tlbiIsImNuZi" + - "I6eyJ4NXQjUzI1NiI6ImRtaVk1ZE03cE81VzdpbjhrUmFqZkFycXlUTU9uRlcyOVdCVU5rUUlYZTgifSwiZXhwIjoxNjE3Nzk5O" + - "Tc4LCJpYXQiOjE2MTc3OTYzNzgsImp0aSI6Ijk5NjQwN2RjLTY5MmYtNDk0Ni1hMGRlLTRlOWJkNTU3NWRmNSIsImFsZyI6IkhT" + - "MjU2In0"; - String grantType = GatewayUtils.getTokenType(tokenPayload); - Assert.assertEquals(grantType, APPLICATION_USER); - } - - - @Test - public void getTokenTypeForApplicationAccessTokens() throws OpenBankingExecutorException { - - String tokenPayload = "eyJzdWIiOiJhZG1pbkB3c28yLmNvbUBjYXJib24uc3VwZXIiLCJhdXQiOiJBUFBMSUNBVElPTiIsImF1ZCI6I" + - "mZXcE5jRFcxWTNxcFRVcHB6d0hhRjJ2WlpZQWEiLCJuYmYiOjE2MTc3OTYzNzgsImdyYW50X3R5cGUiOiJjbGllbnRfY3JlZGVu" + - "dGlhbHMiLCJhenAiOiJmV3BOY0RXMVkzcXBUVXBwendIYUYydlpaWUFhIiwic2NvcGUiOiJhY2NvdW50cyBwYXltZW50cyIsIml" + - "zcyI6Imh0dHBzOlwvXC9sb2NhbGhvc3Q6OTQ0Nlwvb2F1dGgyXC90b2tlbiIsImNuZiI6eyJ4NXQjUzI1NiI6ImRtaVk1ZE03cE" + - "81VzdpbjhrUmFqZkFycXlUTU9uRlcyOVdCVU5rUUlYZTgifSwiZXhwIjoxNjE3Nzk5OTc4LCJpYXQiOjE2MTc3OTYzNzgsImp0a" + - "SI6Ijk5NjQwN2RjLTY5MmYtNDk0Ni1hMGRlLTRlOWJkNTU3NWRmNSJ9"; - String grantType = GatewayUtils.getTokenType(tokenPayload); - Assert.assertEquals(grantType, APPLICATION); - } - - @Test(description = "Test the extraction of grant type from jwt token payload for GET requests") - public void getAllowedOAuthFlowsForGetRequest() { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - - OpenAPI openAPI = getOpenAPI(); - String electedResource = "/testResource"; - String httpMethod = "GET"; - - Assert.assertEquals(GatewayUtils.getAllowedOAuthFlowsFromSwagger(openAPI, electedResource, httpMethod), - oauthFlows); - } - - @Test(description = "Test the extraction of grant type from jwt token payload for POST requests") - public void getAllowedOAuthFlowsForPostRequest() { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - - OpenAPI openAPI = getOpenAPI(); - String electedResource = "/testResource"; - String httpMethod = "POST"; - - Assert.assertEquals(GatewayUtils.getAllowedOAuthFlowsFromSwagger(openAPI, electedResource, httpMethod), - oauthFlows); - } - - @Test(description = "Test the extraction of grant type from jwt token payload for PUT requests") - public void getAllowedOAuthFlowsForPutRequest() { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - - OpenAPI openAPI = getOpenAPI(); - String electedResource = "/testResource"; - String httpMethod = "PUT"; - - Assert.assertEquals(GatewayUtils.getAllowedOAuthFlowsFromSwagger(openAPI, electedResource, httpMethod), - oauthFlows); - } - - @Test(description = "Test the extraction of grant type from jwt token payload for DELETE requests") - public void getAllowedOAuthFlowsForDeleteRequest() { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - - OpenAPI openAPI = getOpenAPI(); - String electedResource = "/testResource"; - String httpMethod = "DELETE"; - - Assert.assertEquals(GatewayUtils.getAllowedOAuthFlowsFromSwagger(openAPI, electedResource, httpMethod), - oauthFlows); - } - - @Test(description = "Test the extraction of grant type from jwt token payload for PATCH requests") - public void getAllowedOAuthFlowsForPatchRequest() { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - - OpenAPI openAPI = getOpenAPI(); - String electedResource = "/testResource"; - String httpMethod = "PATCH"; - - Assert.assertEquals(GatewayUtils - .getAllowedOAuthFlowsFromSwagger(openAPI, electedResource, httpMethod), oauthFlows); - } - - @Test - public void checkValidityForCorrectClientCredentialsGrantType() throws OpenBankingExecutorException { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("client_credentials"); - String grantType = APPLICATION; - GatewayUtils.validateGrantType(grantType, oauthFlows); - } - - @Test - public void checkValidityForCorrectAuthCodeGrantType() throws OpenBankingExecutorException { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - String grantType = APPLICATION_USER; - GatewayUtils.validateGrantType(grantType, oauthFlows); - } - - @Test(expectedExceptions = OpenBankingExecutorException.class) - public void checkValidityForInvalidClientCredentialsGrantType() throws OpenBankingExecutorException { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("authorization_code"); - String grantType = APPLICATION; - GatewayUtils.validateGrantType(grantType, oauthFlows); - } - - @Test(expectedExceptions = OpenBankingExecutorException.class) - public void checkValidityForInvalidAuthCodeGrantType() throws OpenBankingExecutorException { - - List oauthFlows = new ArrayList<>(); - oauthFlows.add("client_credentials"); - String grantType = APPLICATION_USER; - GatewayUtils.validateGrantType(grantType, oauthFlows); - } - - @Test(expectedExceptions = OpenBankingExecutorException.class) - public void getTokenPayloadWhenAuhHeaderNotPresent() throws OpenBankingExecutorException { - - Map transportHeaders = new HashMap<>(); - GatewayUtils.getBearerTokenPayload(transportHeaders); - } - - @Test - public void getTokenPayloadWhenAuhHeaderPresent() throws OpenBankingExecutorException { - - String sampleToken = "Bearer abc.xyz.123"; - Map transportHeaders = new HashMap<>(); - transportHeaders.put("Authorization", sampleToken); - Assert.assertEquals(GatewayUtils.getBearerTokenPayload(transportHeaders), "xyz"); - } - - private OpenAPI getOpenAPI() { - - String swagger = "openapi: 3.0.1\n" + - "info:\n" + - " title: TestAPI\n" + - " version: \"1.0.0\"\n" + - "servers:\n" + - "- url: /testapi/{version}\n" + - "paths:\n" + - " /testResource:\n" + - " get:\n" + - " tags:\n" + - " - Client Registration\n" + - " summary: Get a Client Registration for a given Client ID\n" + - " responses:\n" + - " 200:\n" + - " description: Client registration retrieval success\n" + - " content:\n" + - " application/json:\n" + - " schema: {}\n" + - " security:\n" + - " - PSUOAuth2Security: \n" + - " - accounts\n" + - " - default:\n" + - " - accounts\n" + - " x-auth-type: Application\n" + - " x-throttling-tier: Unlimited\n" + - " post:\n" + - " tags:\n" + - " - Client Registration\n" + - " summary: Get a Client Registration for a given Client ID\n" + - " responses:\n" + - " 200:\n" + - " description: Client registration retrieval success\n" + - " content:\n" + - " application/json:\n" + - " schema: {}\n" + - " security:\n" + - " - PSUOAuth2Security: \n" + - " - accounts\n" + - " - default:\n" + - " - accounts\n" + - " x-auth-type: Application\n" + - " x-throttling-tier: Unlimited\n" + - " delete:\n" + - " tags:\n" + - " - Client Registration\n" + - " summary: Get a Client Registration for a given Client ID\n" + - " responses:\n" + - " 200:\n" + - " description: Client registration retrieval success\n" + - " content:\n" + - " application/json:\n" + - " schema: {}\n" + - " security:\n" + - " - PSUOAuth2Security: \n" + - " - accounts\n" + - " - default:\n" + - " - accounts\n" + - " x-auth-type: Application\n" + - " x-throttling-tier: Unlimited\n" + - " put:\n" + - " tags:\n" + - " - Client Registration\n" + - " summary: Get a Client Registration for a given Client ID\n" + - " responses:\n" + - " 200:\n" + - " description: Client registration retrieval success\n" + - " content:\n" + - " application/json:\n" + - " schema: {}\n" + - " security:\n" + - " - PSUOAuth2Security: \n" + - " - accounts\n" + - " - default:\n" + - " - accounts\n" + - " x-auth-type: Application\n" + - " x-throttling-tier: Unlimited\n" + - " patch:\n" + - " tags:\n" + - " - Client Registration\n" + - " summary: Get a Client Registration for a given Client ID\n" + - " responses:\n" + - " 200:\n" + - " description: Client registration retrieval success\n" + - " content:\n" + - " application/json:\n" + - " schema: {}\n" + - " security:\n" + - " - PSUOAuth2Security: \n" + - " - accounts\n" + - " - default:\n" + - " - accounts\n" + - " x-auth-type: Application\n" + - " x-throttling-tier: Unlimited\n" + - "components:\n" + - " securitySchemes:\n" + - " TPPOAuth2Security:\n" + - " type: oauth2\n" + - " description: TPP client credential authorisation flow with the ASPSP\n" + - " flows:\n" + - " clientCredentials:\n" + - " tokenUrl: https://authserver.example/token\n" + - " scopes: \n" + - " accounts: Ability to read Accounts information\n" + - " PSUOAuth2Security:\n" + - " type: oauth2\n" + - " description: >-\n" + - " OAuth flow, it is required when the PSU needs to perform SCA with the\n" + - " ASPSP when a TPP wants to access an ASPSP resource owned by the PSU\n" + - " flows:\n" + - " authorizationCode:\n" + - " authorizationUrl: 'https://authserver.example/authorization'\n" + - " tokenUrl: 'https://authserver.example/token'\n" + - " scopes:\n" + - " accounts: Ability to read Accounts information\n" + - " default:\n" + - " type: oauth2\n" + - " flows:\n" + - " implicit: \n" + - " authorizationUrl: https://test.com\n" + - " scopes:\n" + - " accounts: Ability to read Accounts information"; - OpenAPIParser parser = new OpenAPIParser(); - return parser.readContents(swagger, - null, null).getOpenAPI(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/dcr/DCRExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/dcr/DCRExecutorTest.java deleted file mode 100644 index f790554d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/dcr/DCRExecutorTest.java +++ /dev/null @@ -1,838 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.executor.dcr; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCache; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import org.apache.http.HttpStatus; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.APIRequestInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.identity.core.util.IdentityUtil; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.HttpMethod; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * Test for DCR executor. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityUtil.class, GatewayDataHolder.class, OpenBankingConfigParser.class}) -public class DCRExecutorTest { - - @Mock - Map urlMap = new HashMap<>(); - - @Mock - OpenBankingConfigurationService openBankingConfigurationService; - - @Mock - APIManagerConfigurationService apiManagerConfigurationService; - - @Mock - APIManagerConfiguration apiManagerConfiguration; - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - @InjectMocks - DCRExecutor dcrExecutor = new DCRExecutor(); - - Map configMap = new HashMap<>(); - Map> configuredAPIList = new HashMap<>(); - JsonParser jsonParser = new JsonParser(); - - @BeforeTest - public void init() { - - MockitoAnnotations.initMocks(this); - - urlMap = new HashMap<>(); - urlMap.put("userName", "admin"); - urlMap.put("password", "admin".toCharArray()); - urlMap.put(GatewayConstants.IAM_HOSTNAME, "localhost"); - urlMap.put(GatewayConstants.IAM_DCR_URL, "dcr/register"); - urlMap.put(GatewayConstants.TOKEN_URL, "/token"); - urlMap.put(GatewayConstants.APP_CREATE_URL, "/appCreate"); - urlMap.put(GatewayConstants.KEY_MAP_URL, "/keyMap/application-id"); - urlMap.put(GatewayConstants.API_RETRIEVE_URL, "/apis"); - urlMap.put(GatewayConstants.API_SUBSCRIBE_URL, "/subscriptions/multiple"); - urlMap.put(GatewayConstants.API_GET_SUBSCRIBED, "/subscriptions"); - - configMap.put(GatewayConstants.REQUEST_ROUTER, - "com.wso2.openbanking.accelerator.gateway.executor.core.DefaultRequestRouter"); - configMap.put(GatewayConstants.GATEWAY_CACHE_EXPIRY, "1"); - configMap.put(GatewayConstants.GATEWAY_CACHE_MODIFIEDEXPIRY, "1"); - configMap.put(OpenBankingConstants.STORE_HOSTNAME, "localhost"); - configMap.put(OpenBankingConstants.TOKEN_ENDPOINT, "/token"); - configMap.put(OpenBankingConstants.APIM_APPCREATION, "/appCreation"); - configMap.put(OpenBankingConstants.APIM_KEYGENERATION, "/keygeneration"); - configMap.put(OpenBankingConstants.APIM_GETAPIS, "/getAPIs"); - configMap.put(OpenBankingConstants.APIM_SUBSCRIBEAPIS, "/subscribe"); - configMap.put(OpenBankingConstants.APIM_GETSUBSCRIPTIONS, "/getSubscriptions"); - configMap.put(OpenBankingConstants.OB_KM_NAME, "OBKM"); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configMap); - - List dcrRoles = new ArrayList<>(); - dcrRoles.add("AISP"); - dcrRoles.add("PISP"); - List accountRoles = new ArrayList<>(); - accountRoles.add("AISP"); - configuredAPIList.put("DynamicClientRegistration", dcrRoles); - configuredAPIList.put("AccountandTransactionAPI", accountRoles); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - String isDcrResponse = "{\"client_name\":\"application_test\",\"client_id\":\"provided_client_id0001\"," + - "\"client_secret\":\"provided_client_secret0001\",\"redirect_uris\":[\"\"]}"; - - String tokenResponse = "{\n" + - " \"access_token\": \"sdsdfcdvvfvfvfv\",\n" + - " \"scope\": \"accounts cdr-register\",\n" + - " \"token_type\": \"Bearer\",\n" + - " \"expires_in\": 3600\n" + - "}"; - String publishedAPIResponse = "{\n" + - " \"count\":2,\n" + - " \"list\":[\n" + - " {\n" + - " \"id\":\"01234567-0123-0123-0123-012345678901\",\n" + - " \"name\":\"DynamicClientRegistration\"\n" + - " },\n" + - " {\n" + - " \"id\":\"2962f3bb-8330-438e-baee-0ee1d6434ba4\",\n" + - " \"name\":\"AccountandTransactionAPI\"\n" + - " }\n" + - " ],\n" + - " \"pagination\":{\n" + - " \"offset\":2,\n" + - " \"limit\":2,\n" + - " \"total\":10,\n" + - " \"next\":\"/apis?limit=2&offset=4\",\n" + - " \"previous\":\"/apis?limit=2&offset=0\"\n" + - " }\n" + - "}"; - - String subscriptionResponse = "[\n" + - " {\n" + - " \"subscriptionId\":\"faae5fcc-cbae-40c4-bf43-89931630d313\",\n" + - " \"applicationId\":\"b3ade481-30b0-4b38-9a67-498a40873a6d\",\n" + - " \"apiId\":\"2962f3bb-8330-438e-baee-0ee1d6434ba4\",\n" + - " \"apiInfo\":{\n" + - " \"id\":\"01234567-0123-0123-0123-012345678901\",\n" + - " \"name\":\"DynamicClientRegistration\"\n" + - " },\n" + - " \"applicationInfo\":{\n" + - " \"applicationId\":\"01234567-0123-0123-0123-012345678901\",\n" + - " \"name\":\"DynamicClientRegistration\",\n" + - " \"throttlingPolicy\":\"Unlimited\",\n" + - " \"description\":\"Sample calculator application\",\n" + - " \"status\":\"APPROVED\",\n" + - " \"groups\":\"\",\n" + - " \"subscriptionCount\":0,\n" + - " \"attributes\":\"External Reference ID, Billing Tier\",\n" + - " \"owner\":\"admin\"\n" + - " },\n" + - " \"throttlingPolicy\":\"Unlimited\",\n" + - " \"requestedThrottlingPolicy\":\"Unlimited\",\n" + - " \"status\":\"UNBLOCKED\",\n" + - " \"redirectionParams\":\"\"\n" + - " }\n" + - "]"; - - String applicationSearchResponse = "{ \"count\": 1, \"list\": " + - "[ { \"applicationId\": \"01234567-0123-0123-0123-012345678901\", " + - "\"name\": \"CalculatorApp\", \"throttlingPolicy\": \"Unlimited\", " + - "\"description\": \"Sample calculator application\", \"status\": \"APPROVED\", " + - "\"groups\": \"\", \"subscriptionCount\": 0," + - " \"attributes\": \"External Reference ID, Billing Tier\", " + - "\"owner\": \"admin\" } ], " + - "\"pagination\": { \"offset\": 0, \"limit\": 1, \"total\": 10, \"next\": \"\", \"previous\": \"\" } }"; - - String createdApplicationResponse = "{\n" + - " \"applicationId\": \"01234567-0123-0123-0123-012345678901\",\n" + - " \"name\": \"CalculatorApp\"\n" + - "}"; - String keyMapResponse = "{\n" + - " \"keyMappingId\": \"92ab520c-8847-427a-a921-3ed19b15aad7\",\n" + - " \"keyManager\": \"Resident Key Manager\",\n" + - " \"consumerKey\": \"vYDoc9s7IgAFdkSyNDaswBX7ejoa\",\n" + - " \"consumerSecret\": \"TIDlOFkpzB7WjufO3OJUhy1fsvAa\"\n" + - "}"; - - String softwareStatement = "eyJhbGciOiJQUzI1NiIsImtpZCI6IkR3TUtkV01tajdQV2ludm9xZlF5WFZ6eVo2USIsInR5cCI6IkpXVCJ9." + - "eyJpc3MiOiJjZHItcmVnaXN0ZXIiLCJpYXQiOjE1NzE4MDgxNjcsImV4cCI6MjE0NzQ4MzY0NiwianRpIjoiM2JjMjA1YTFlYmM5NDNm" + - "YmI2MjRiMTRmY2IyNDExOTYiLCJvcmdfaWQiOiIzQjBCMEE3Qi0zRTdCLTRBMkMtOTQ5Ny1FMzU3QTcxRDA3QzgiLCJvcmdfbmFtZSI6" + - "Ik1vY2sgQ29tcGFueSBJbmMuIiwiY2xpZW50X25hbWUiOiJNb2NrIFNvZnR3YXJlIE5ldyIsImNsaWVudF9kZXNjcmlwdGlvbiI6IkEg" + - "bW9jayBzb2Z0d2FyZSBwcm9kdWN0IGZvciB0ZXN0aW5nIFNTQSIsImNsaWVudF91cmkiOiJodHRwczovL3d3dy5tb2NrY29tcGFueS5j" + - "b20uYXUiLCJyZWRpcmVjdF91cmlzIjpbImh0dHBzOi8vd3d3Lmdvb2dsZS5jb20vcmVkaXJlY3RzL3JlZGlyZWN0MSIsImh0dHBzOi8v" + - "d3d3Lmdvb2dsZS5jb20vcmVkaXJlY3RzL3JlZGlyZWN0MiJdLCJsb2dvX3VyaSI6Imh0dHBzOi8vd3d3Lm1vY2tjb21wYW55LmNvbS5h" + - "dS9sb2dvcy9sb2dvMS5wbmciLCJ0b3NfdXJpIjoiaHR0cHM6Ly93d3cubW9ja2NvbXBhbnkuY29tLmF1L3Rvcy5odG1sIiwicG9saWN5" + - "X3VyaSI6Imh0dHBzOi8vd3d3Lm1vY2tjb21wYW55LmNvbS5hdS9wb2xpY3kuaHRtbCIsImp3a3NfdXJpIjoiaHR0cHM6Ly9rZXlzdG9y" + - "ZS5vcGVuYmFua2luZ3Rlc3Qub3JnLnVrLzAwMTU4MDAwMDFIUVFyWkFBWC85YjV1c0RwYk50bXhEY1R6czdHektwLmp3a3MiLCJyZXZv" + - "Y2F0aW9uX3VyaSI6Imh0dHBzOi8vZ2lzdC5naXRodWJ1c2VyY29udGVudC5jb20vaW1lc2g5NC8zMTcyZTJlNDU3NTdjZGEwOGVjMjcy" + - "N2Y5MGI3MmNlZC9yYXcvZmYwZDNlYWJlNGNkZGNlNDdlZWMwMjI4ZjU5MjE3NTIyM2RkOTJiMi93c28yLWF1LWRjci1kZW1vLmp3a3Mi" + - "LCJyZWNpcGllbnRfYmFzZV91cmkiOiJodHRwczovL3d3dy5tb2NrY29tcGFueS5jb20uYXUiLCJzb2Z0d2FyZV9pZCI6InRlc3QxMjM0" + - "Iiwic29mdHdhcmVfcm9sZXMiOiJkYXRhLXJlY2lwaWVudC1zb2Z0d2FyZS1wcm9kdWN0IEFJU1AiLCJzY29wZSI6ImJhbms6YWNjb3Vu" + - "dHMuYmFzaWM6cmVhZCBiYW5rOmFjY291bnRzLmRldGFpbDpyZWFkIGJhbms6dHJhbnNhY3Rpb25zOnJlYWQgYmFuazpwYXllZXM6cmVh" + - "ZCBiYW5rOnJlZ3VsYXJfcGF5bWVudHM6cmVhZCBjb21tb246Y3VzdG9tZXIuYmFzaWM6cmVhZCBjb21tb246Y3VzdG9tZXIuZGV0YWls" + - "OnJlYWQgY2RyOnJlZ2lzdHJhdGlvbiJ9.O5xHyhgOyAcTyXLqaUD9O2Iz-Dv5i3_P-ADw1A7PrMZV9j8JdrvY0n0QfhV0YKhmiSTYtII" + - "RCFB_9EchBpnfPeVW4AJ9wt-JpQ2_TWCDSnGIlKb0fmepQkbcQmSRvecFpuECFWUIab6rDOz8IOMMuRXZrwghn3LaP5gKbbDT2NhCp0C" + - "GjBZ2RwriIEx4NZjLBXP4RIw7ZhicOdXL3_544vFs6rOs6IjEkK1z9pHaBfyU0j7BRNcCwPL0Y9_zo4VpZ81Bd8IB_AxIpRNOLcpsa5c" + - "c9oD5B-bqqTeWAkI_INjTlDXf-Rq5bBs7ldkuHh0fRNbI0gIyrpT_VyRL3IKIlw"; - - String dcrResponsePayload = "{\n" + - " \"software_id\": \"test1234\",\n" + - " \"software_statement\": \"eyJhbGciOiJQUzI1NiIsImtpZCI6IkR3TUtkV01tajdQV2ludm9xZlF5WFZ6eVo2U" + - "SIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjZHItcmVnaXN0ZXIiLCJpYXQiOjE1NzE4MDgxNjcsImV4cCI6MjE0NzQ4MzY0Ni" + - "wianRpIjoiM2JjMjA1YTFlYmM5NDNmYmI2MjRiMTRmY2IyNDExOTYiLCJvcmdfaWQiOiIzQjBCMEE3Qi0zRTdCLTRBMkMtO" + - "TQ5Ny1FMzU3QTcxRDA3QzgiLCJvcmdfbmFtZSI6Ik1vY2sgQ29tcGFueSBJbmMuIiwiY2xpZW50X25hbWUiOiJNb2NrIFNv" + - "ZnR3YXJlIE5ldyIsImNsaWVudF9kZXNjcmlwdGlvbiI6IkEgbW9jayBzb2Z0d2FyZSBwcm9kdWN0IGZvciB0ZXN0aW5nIFNT" + - "QSIsImNsaWVudF91cmkiOiJodHRwczovL3d3dy5tb2NrY29tcGFueS5jb20uYXUiLCJyZWRpcmVjdF91cmlzIjpbImh0dHB" + - "zOi8vd3d3Lmdvb2dsZS5jb20vcmVkaXJlY3RzL3JlZGlyZWN0MSIsImh0dHBzOi8vd3d3Lmdvb2dsZS5jb20vcmVkaXJlY3" + - "RzL3JlZGlyZWN0MiJdLCJsb2dvX3VyaSI6Imh0dHBzOi8vd3d3Lm1vY2tjb21wYW55LmNvbS5hdS9sb2dvcy9sb2dvMS5wb" + - "mciLCJ0b3NfdXJpIjoiaHR0cHM6Ly93d3cubW9ja2NvbXBhbnkuY29tLmF1L3Rvcy5odG1sIiwicG9saWN5X3VyaSI6Imh0" + - "dHBzOi8vd3d3Lm1vY2tjb21wYW55LmNvbS5hdS9wb2xpY3kuaHRtbCIsImp3a3NfdXJpIjoiaHR0cHM6Ly9rZXlzdG9yZS5" + - "vcGVuYmFua2luZ3Rlc3Qub3JnLnVrLzAwMTU4MDAwMDFIUVFyWkFBWC85YjV1c0RwYk50bXhEY1R6czdHektwLmp3a3MiLC" + - "JyZXZvY2F0aW9uX3VyaSI6Imh0dHBzOi8vZ2lzdC5naXRodWJ1c2VyY29udGVudC5jb20vaW1lc2g5NC8zMTcyZTJlNDU3N" + - "TdjZGEwOGVjMjcyN2Y5MGI3MmNlZC9yYXcvZmYwZDNlYWJlNGNkZGNlNDdlZWMwMjI4ZjU5MjE3NTIyM2RkOTJiMi93c28y" + - "LWF1LWRjci1kZW1vLmp3a3MiLCJyZWNpcGllbnRfYmFzZV91cmkiOiJodHRwczovL3d3dy5tb2NrY29tcGFueS5jb20uYXU" + - "iLCJzb2Z0d2FyZV9pZCI6InRlc3QxMjM0Iiwic29mdHdhcmVfcm9sZXMiOiJkYXRhLXJlY2lwaWVudC1zb2Z0d2FyZS1wcm" + - "9kdWN0IEFJU1AiLCJzY29wZSI6ImJhbms6YWNjb3VudHMuYmFzaWM6cmVhZCBiYW5rOmFjY291bnRzLmRldGFpbDpyZWFkI" + - "GJhbms6dHJhbnNhY3Rpb25zOnJlYWQgYmFuazpwYXllZXM6cmVhZCBiYW5rOnJlZ3VsYXJfcGF5bWVudHM6cmVhZCBjb21t" + - "b246Y3VzdG9tZXIuYmFzaWM6cmVhZCBjb21tb246Y3VzdG9tZXIuZGV0YWlsOnJlYWQgY2RyOnJlZ2lzdHJhdGlvbiJ9.O5" + - "xHyhgOyAcTyXLqaUD9O2Iz-Dv5i3_P-ADw1A7PrMZV9j8JdrvY0n0QfhV0YKhmiSTYtIIRCFB_9EchBpnfPeVW4AJ9wt-Jp" + - "Q2_TWCDSnGIlKb0fmepQkbcQmSRvecFpuECFWUIab6rDOz8IOMMuRXZrwghn3LaP5gKbbDT2NhCp0CGjBZ2RwriIEx4NZjL" + - "BXP4RIw7ZhicOdXL3_544vFs6rOs6IjEkK1z9pHaBfyU0j7BRNcCwPL0Y9_zo4VpZ81Bd8IB_AxIpRNOLcpsa5cc9oD5B-b" + - "qqTeWAkI_INjTlDXf-Rq5bBs7ldkuHh0fRNbI0gIyrpT_VyRL3IKIlw\",\n" + - " \"grant_types\": [\n" + - " \"client_credentials\",\n" + - " \"authorization_code\",\n" + - " \"refresh_token\",\n" + - " \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\n" + - " ],\n" + - " \"application_type\": \"web\",\n" + - " \"scope\": \"bank:accounts.basic:read bank:accounts.detail:read bank:transactions:read " + - "bank:payees:read bank:regular_payments:read common:customer.basic:read common:customer.detail:read" + - " cdr:registration\",\n" + - " \"client_id_issued_at\": 1619150285,\n" + - " \"redirect_uris\": [\n" + - " \"https://www.google.com/redirects/redirect1\",\n" + - " \"https://www.google.com/redirects/redirect2\"\n" + - " ],\n" + - " \"request_object_signing_alg\": \"PS256\",\n" + - " \"client_id\": \"uagAipmOU5quayzoznU1ddWg6tca\",\n" + - " \"token_endpoint_auth_method\": \"private_key_jwt\",\n" + - " \"response_types\": \"code id_token\",\n" + - " \"id_token_signed_response_alg\": \"PS256\"\n" + - "}"; - - String dcrResponsePayloadWithoutSSA = "{\n" + - " \"software_id\": \"test12345\",\n" + - "\"client_name\" : \"sample app name\",\n" + - " \"grant_types\": [\n" + - " \"client_credentials\",\n" + - " \"authorization_code\",\n" + - " \"refresh_token\",\n" + - " \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\n" + - " ],\n" + - " \"application_type\": \"web\",\n" + - " \"scope\": \"bank:accounts.basic:read bank:accounts.detail:read bank:transactions:read " + - "bank:payees:read bank:regular_payments:read common:customer.basic:read common:customer.detail:read" + - " cdr:registration\",\n" + - " \"client_id_issued_at\": 1619150285,\n" + - " \"redirect_uris\": [\n" + - " \"https://www.google.com/redirects/redirect1\",\n" + - " \"https://www.google.com/redirects/redirect2\"\n" + - " ],\n" + - " \"request_object_signing_alg\": \"PS256\",\n" + - " \"client_id\": \"uagAipmOU5quayzoznU1ddWg6tca\",\n" + - " \"token_endpoint_auth_method\": \"private_key_jwt\",\n" + - " \"response_types\": \"code id_token\",\n" + - " \"id_token_signed_response_alg\": \"PS256\"\n" + - "}"; - - - @Test - public void testFilterRegulatorAPIs() { - - Map> configuredAPIList = new HashMap<>(); - List dcrRoles = new ArrayList<>(); - dcrRoles.add("AISP"); - dcrRoles.add("PISP"); - List accountRoles = new ArrayList<>(); - accountRoles.add("AISP"); - configuredAPIList.put("DynamicClientRegistration", dcrRoles); - configuredAPIList.put("AccountandTransactionAPI", accountRoles); - - JsonArray publishedAPIs = new JsonArray(); - JsonObject dcrApi = new JsonObject(); - dcrApi.addProperty("id", "1"); - dcrApi.addProperty("name", "DynamicClientRegistration"); - publishedAPIs.add(dcrApi); - - DCRExecutor dcrExecutor = new DCRExecutor(); - List filteredAPIList = dcrExecutor.filterRegulatoryAPIs(configuredAPIList, publishedAPIs, dcrRoles); - Assert.assertEquals(filteredAPIList.get(0), "1"); - } - @Test - public void isSubscriptionDeletionFailed() throws OpenBankingException, IOException { - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - Mockito.doReturn(false).when(dcrExecutor) - .callDelete(Mockito.anyString(), anyString()); - boolean subscriptionDeletionFailed = dcrExecutor.isSubscriptionDeletionFailed(Mockito.anyString(), - Mockito.anyString()); - Assert.assertTrue(subscriptionDeletionFailed); - } - - @Test - public void testExtractApplicationName() throws ParseException { - - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME, "true"); - configMap.put(OpenBankingConstants.DCR_APPLICATION_NAME_KEY, "software_client_name"); - String applicationName = dcrExecutor.getApplicationName(dcrResponsePayload, configMap); - Assert.assertEquals("test1234", applicationName); - } - - @Test - public void testExtractApplicationNameFromAppDetails() throws ParseException { - - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME, "true"); - configMap.put(OpenBankingConstants.DCR_APPLICATION_NAME_KEY, "software_client_name"); - String applicationName = dcrExecutor.getApplicationName(dcrResponsePayloadWithoutSSA, configMap); - Assert.assertEquals("test12345", applicationName); - } - - @Test - public void testExtractApplicationNameWhenSSANotContainsApplicationNameKey() throws ParseException { - - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME, "false"); - configMap.put(OpenBankingConstants.DCR_APPLICATION_NAME_KEY, "client_name"); - String applicationName = dcrExecutor.getApplicationName(dcrResponsePayloadWithoutSSA, configMap); - Assert.assertEquals("sample app name", applicationName); - } - - @Test - public void testExtractApplicationNameWithSoftwareIDEnabledFalse() throws ParseException { - - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME, "false"); - configMap.put(OpenBankingConstants.DCR_APPLICATION_NAME_KEY, "client_name"); - String applicationName = dcrExecutor.getApplicationName(dcrResponsePayload, configMap); - Assert.assertEquals("Mock Software New", applicationName); - } - - @Test - public void testExtractSoftwareRoles() throws ParseException { - - List roles = dcrExecutor.getRolesFromSSA(softwareStatement); - Assert.assertTrue(roles.contains("data-recipient-software-product")); - Assert.assertTrue(roles.contains("AISP")); - - } - - @Test - public void testGetUnauthorizedAPIs() { - - Map> configuredAPIList = new HashMap<>(); - List dcrRoles = new ArrayList<>(); - dcrRoles.add("AISP"); - dcrRoles.add("PISP"); - List accountRoles = new ArrayList<>(); - accountRoles.add("AISP"); - configuredAPIList.put("DynamicClientRegistration", dcrRoles); - configuredAPIList.put("AccountandTransactionAPI", accountRoles); - - JsonArray subscribedAPIs = new JsonArray(); - JsonObject dcrApi = new JsonObject(); - JsonObject apiInfo = new JsonObject(); - apiInfo.addProperty("name", "DynamicClientRegistration"); - dcrApi.add("apiInfo", apiInfo); - dcrApi.addProperty("subscriptionId", "1"); - subscribedAPIs.add(dcrApi); - - List allowedRoles = new ArrayList<>(); - allowedRoles.add("data-recipient-software-product"); - List unAuthorizedAPIs = dcrExecutor - .getUnAuthorizedAPIs(subscribedAPIs, configuredAPIList, allowedRoles); - Assert.assertTrue(unAuthorizedAPIs.contains("1")); - - } - - @Test - public void testNewAPIsToSubscribe() { - - List allowedAPIs = new ArrayList<>(); - allowedAPIs.add("1"); - allowedAPIs.add("2"); - - List subscribedAPIs = new ArrayList<>(); - subscribedAPIs.add("1"); - - List apisToSubscribe = dcrExecutor.getNewAPIsToSubscribe(allowedAPIs, subscribedAPIs); - Assert.assertTrue(apisToSubscribe.contains("2")); - - allowedAPIs.remove("2"); - apisToSubscribe = dcrExecutor.getNewAPIsToSubscribe(allowedAPIs, subscribedAPIs); - Assert.assertTrue(apisToSubscribe.isEmpty()); - - subscribedAPIs.remove("1"); - apisToSubscribe = dcrExecutor.getNewAPIsToSubscribe(allowedAPIs, subscribedAPIs); - Assert.assertTrue(apisToSubscribe.contains("1")); - - allowedAPIs.add("2"); - apisToSubscribe = dcrExecutor.getNewAPIsToSubscribe(allowedAPIs, subscribedAPIs); - Assert.assertTrue(apisToSubscribe.contains("1")); - Assert.assertTrue(apisToSubscribe.contains("2")); - } - - @Test - public void testPostProcessResponseForRegister() throws Exception { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - Mockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParser); - Mockito.when(OpenBankingConfigParser.getInstance() - .getSoftwareEnvIdentificationSSAPropertyValueForSandbox()).thenReturn("sandbox"); - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO = Mockito.mock(MsgInfoDTO.class); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - Mockito.doReturn(msgInfoDTO).when(obapiResponseContext).getMsgInfo(); - Mockito.doReturn(HttpMethod.POST).when(msgInfoDTO).getHttpMethod(); - Mockito.doReturn(HttpStatus.SC_CREATED).when(obapiResponseContext).getStatusCode(); - Mockito.doReturn(dcrResponsePayload).when(obapiResponseContext).getResponsePayload(); - - Mockito.when(openBankingConfigurationService.getAllowedAPIs()).thenReturn(configuredAPIList); - GatewayDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfigurationService); - Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration); - Mockito.doReturn("admin").when(apiManagerConfiguration).getFirstProperty(anyString()); - Mockito.doReturn("localhost/services").when(apiManagerConfiguration) - .getFirstProperty("APIKeyValidator.ServerURL"); - - PowerMockito.mockStatic(IdentityUtil.class); - Mockito.when(IdentityUtil.getProperty("OAuth.OAuth2DCREPUrl")).thenReturn("localhost/api/dcr/register"); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(createdApplicationResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(keyMapResponse)).when(dcrExecutor) - .callPost(eq("/keyMap/01234567-0123-0123-0123-012345678901"), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(publishedAPIResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString()), anyString(), anyString(), - anyString()); - Mockito.doReturn(jsonParser.parse(subscriptionResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.API_SUBSCRIBE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(true).when(dcrExecutor) - .callDelete(eq("dcr/register/provided_client_id0001"), anyString()); - GatewayDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - DCRExecutor.setUrlMap(urlMap); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(0)).setError(true); - } - - @Test - public void testPostProcessResponseForUpdate() throws IOException, OpenBankingException, URISyntaxException { - - String subscribedAPIResponse = "{ \"count\": 1, \"list\": " + - "[ { \"subscriptionId\": \"faae5fcc-cbae-40c4-bf43-89931630d313\", " + - "\"applicationId\": \"b3ade481-30b0-4b38-9a67-498a40873a6d\", " + - "\"apiId\": \"2962f3bb-8330-438e-baee-0ee1d6434ba4\", " + - "\"apiInfo\": { \"id\": \"01234567-0123-0123-0123-012345678901\", " + - "\"name\": \"AccountandTransactionAPI\"," + - " \"description\": \"A calculator API that supports basic operations\", " + - "\"context\": \"CalculatorAPI\", \"version\": \"1.0.0\", \"type\": \"WS\", " + - "\"provider\": \"admin\", \"lifeCycleStatus\": \"PUBLISHED\", " + - "\"thumbnailUri\": \"/apis/01234567-0123-0123-0123-012345678901/thumbnail\", " + - "\"avgRating\": 4.5, \"throttlingPolicies\": [ \"Unlimited\", \"Bronze\" ], " + - "\"advertiseInfo\": { \"advertised\": true, \"originalStoreUrl\": \"https://localhost:9443/store\", " + - "\"apiOwner\": \"admin\" }, " + - "\"businessInformation\": { \"businessOwner\": \"businessowner\", \"businessOwnerEmail\": " + - "\"businessowner@wso2.com\", \"technicalOwner\": \"technicalowner\"," + - " \"technicalOwnerEmail\": \"technicalowner@wso2.com\" }, \"isSubscriptionAvailable\": false, " + - "\"monetizationLabel\": \"Free\" }, " + - "\"applicationInfo\": { \"applicationId\": \"01234567-0123-0123-0123-012345678901\"," + - " \"name\": \"CalculatorApp\", \"throttlingPolicy\": \"Unlimited\", " + - "\"description\": \"Sample calculator application\", \"status\": \"APPROVED\", " + - "\"groups\": \"\", \"subscriptionCount\": 0, \"attributes\": \"External Reference ID, Billing Tier\"," + - " \"owner\": \"admin\" }, \"throttlingPolicy\": \"Unlimited\", \"requestedThrottlingPolicy\":" + - " \"Unlimited\", \"status\": \"UNBLOCKED\", \"redirectionParams\": \"\" } ], " + - "\"pagination\": { \"offset\": 0, \"limit\": 1, \"total\": 10, \"next\": \"\", \"previous\": \"\" } }"; - - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO = Mockito.mock(MsgInfoDTO.class); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - Mockito.doReturn(msgInfoDTO).when(obapiResponseContext).getMsgInfo(); - Mockito.doReturn(HttpMethod.PUT).when(msgInfoDTO).getHttpMethod(); - Mockito.doReturn(HttpStatus.SC_OK).when(obapiResponseContext).getStatusCode(); - Mockito.doReturn(dcrResponsePayload).when(obapiResponseContext).getResponsePayload(); - - PowerMockito.mockStatic(IdentityUtil.class); - Mockito.when(IdentityUtil.getProperty("OAuth.OAuth2DCREPUrl")).thenReturn("localhost/api/dcr/register"); - GatewayDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME, true); - configMap.put(OpenBankingConstants.DCR_APPLICATION_NAME_KEY, "software_name"); - Mockito.when(openBankingConfigurationService.getConfigurations()).thenReturn(configMap); - Mockito.when(openBankingConfigurationService.getAllowedAPIs()).thenReturn(configuredAPIList); - - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(applicationSearchResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(subscribedAPIResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.API_GET_SUBSCRIBED).toString()), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(publishedAPIResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString()), anyString(), anyString(), - anyString()); - Mockito.doReturn(jsonParser.parse(subscriptionResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.API_SUBSCRIBE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(true).when(dcrExecutor) - .callDelete(eq("dcr/register/provided_client_id0001"), anyString()); - DCRExecutor.setUrlMap(urlMap); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(0)).setError(true); - } - - @Test - public void testPostProcessResponseForDelete() throws Exception { - - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO(); - apiRequestInfoDTO.setConsumerKey("clientId"); - MsgInfoDTO msgInfoDTO = Mockito.mock(MsgInfoDTO.class); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - GatewayCache gatewayCache = Mockito.mock(GatewayCache.class); - - PowerMockito.mockStatic(IdentityUtil.class); - - Mockito.when(IdentityUtil.getProperty("OAuth.OAuth2DCREPUrl")).thenReturn("localhost/api/dcr/register"); - Mockito.doReturn(msgInfoDTO).when(obapiResponseContext).getMsgInfo(); - Mockito.doReturn(HttpMethod.DELETE).when(msgInfoDTO).getHttpMethod(); - Mockito.doReturn(HttpStatus.SC_NO_CONTENT).when(obapiResponseContext).getStatusCode(); - Mockito.doReturn(dcrResponsePayload).when(obapiResponseContext).getResponsePayload(); - Mockito.doReturn(apiRequestInfoDTO).when(obapiResponseContext).getApiRequestInfo(); - Mockito.when(openBankingConfigurationService.getAllowedAPIs()).thenReturn(configuredAPIList); - GatewayDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfigurationService); - Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration); - Mockito.doReturn("admin").when(apiManagerConfiguration).getFirstProperty(anyString()); - Mockito.doReturn("localhost/services").when(apiManagerConfiguration) - .getFirstProperty("APIKeyValidator.ServerURL"); - GatewayDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - WhiteboxImpl.invokeMethod(GatewayDataHolder.getInstance(), "setGatewayCache", gatewayCache); - //GatewayDataHolder.setGatewayCache(gatewayCache); - - Mockito.doReturn("application").when(gatewayCache).getFromCache(GatewayCacheKey.of(anyString())); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(applicationSearchResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), - anyString(), anyString(), anyString()); - Mockito.doReturn(true).when(dcrExecutor).callDelete(anyString(), anyString()); - DCRExecutor.setUrlMap(urlMap); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(0)).setError(true); - } - - @Test - public void testPostProcessRequestInvalidAuthenticationDCR() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO(); - apiRequestInfoDTO.setConsumerKey("clientId"); - MsgInfoDTO msgInfoDTO = new MsgInfoDTO(); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - - msgInfoDTO.setHttpMethod(HttpMethod.GET); - msgInfoDTO.setResource("/register/1234"); - apiRequestInfoDTO.setConsumerKey("123"); - Map requestHeaders = new HashMap<>(); - requestHeaders.put(GatewayConstants.CONTENT_TYPE_TAG, "application/jwt"); - requestHeaders.put(GatewayConstants.CONTENT_LENGTH, "1000"); - msgInfoDTO.setHeaders(requestHeaders); - RequestContextDTO requestContextDTO = new RequestContextDTO(); - requestContextDTO.setApiRequestInfo(apiRequestInfoDTO); - requestContextDTO.setMsgInfo(msgInfoDTO); - - Mockito.doReturn(msgInfoDTO).when(obapiRequestContext).getMsgInfo(); - Mockito.doReturn(apiRequestInfoDTO).when(obapiRequestContext).getApiRequestInfo(); - - dcrExecutor.postProcessRequest(obapiRequestContext); - verify(obapiRequestContext).setError(true); - } - - @Test - public void testPostProcessWithInvalidAuthenticationDCRApplicationAccessToken() throws Exception { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - GatewayCache gatewayCache = Mockito.mock(GatewayCache.class); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - MsgInfoDTO msgInfoDTO = new MsgInfoDTO(); - Map headers = new HashMap<>(); - headers.put(GatewayConstants.AUTH_HEADER, ""); - msgInfoDTO.setHeaders(headers); - msgInfoDTO.setResource("/register/123"); - msgInfoDTO.setHttpMethod(HttpMethod.DELETE); - APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO(); - apiRequestInfoDTO.setConsumerKey("123"); - DCRExecutor.setUrlMap(urlMap); - WhiteboxImpl.invokeMethod(GatewayDataHolder.getInstance(), "setGatewayCache", gatewayCache); - - Mockito.doReturn(msgInfoDTO).when(obapiRequestContext).getMsgInfo(); - Mockito.doReturn(apiRequestInfoDTO).when(obapiRequestContext).getApiRequestInfo(); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(anyString(), anyString(), anyString(), anyString()); - Mockito.doNothing().when(gatewayCache).addToCache(anyObject(), anyObject()); - - dcrExecutor.postProcessRequest(obapiRequestContext); - verify(gatewayCache).addToCache(anyObject(), anyObject()); - } - - @Test - public void testAddApplicationNameToCacheInDelete() throws Exception { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - GatewayCache gatewayCache = Mockito.mock(GatewayCache.class); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - MsgInfoDTO msgInfoDTO = new MsgInfoDTO(); - msgInfoDTO.setResource("/register/123"); - msgInfoDTO.setHttpMethod(HttpMethod.DELETE); - APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO(); - apiRequestInfoDTO.setConsumerKey("123"); - DCRExecutor.setUrlMap(urlMap); - WhiteboxImpl.invokeMethod(GatewayDataHolder.getInstance(), "setGatewayCache", gatewayCache); - //GatewayDataHolder.setGatewayCache(gatewayCache); - - Mockito.doReturn(msgInfoDTO).when(obapiRequestContext).getMsgInfo(); - Mockito.doReturn(apiRequestInfoDTO).when(obapiRequestContext).getApiRequestInfo(); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(anyString(), anyString(), anyString(), anyString()); - Mockito.doNothing().when(gatewayCache).addToCache(anyObject(), anyObject()); - - dcrExecutor.postProcessRequest(obapiRequestContext); - verify(gatewayCache).addToCache(anyObject(), anyObject()); - } - - @Test - public void testErrorScenarios() throws IOException, OpenBankingException, URISyntaxException { - - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - MsgInfoDTO msgInfoDTO = Mockito.mock(MsgInfoDTO.class); - DCRExecutor dcrExecutor = Mockito.spy(DCRExecutor.class); - Mockito.doReturn(msgInfoDTO).when(obapiResponseContext).getMsgInfo(); - Mockito.doReturn(HttpMethod.POST).when(msgInfoDTO).getHttpMethod(); - Mockito.doReturn(HttpStatus.SC_CREATED).when(obapiResponseContext).getStatusCode(); - Mockito.doReturn(dcrResponsePayload).when(obapiResponseContext).getResponsePayload(); - - Mockito.when(openBankingConfigurationService.getAllowedAPIs()).thenReturn(configuredAPIList); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - Mockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParser); - Mockito.when(OpenBankingConfigParser.getInstance().getSoftwareEnvIdentificationSSAPropertyValueForSandbox()) - .thenReturn("sandbox"); - GatewayDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfigurationService); - Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration); - Mockito.doReturn("admin").when(apiManagerConfiguration).getFirstProperty(anyString()); - Mockito.doReturn("localhost/services").when(apiManagerConfiguration) - .getFirstProperty("APIKeyValidator.ServerURL"); - PowerMockito.mockStatic(IdentityUtil.class); - Mockito.when(IdentityUtil.getProperty("OAuth.OAuth2DCREPUrl")).thenReturn("localhost/api/dcr/register"); - - //when sp creation fails for token generation - Mockito.doReturn(null).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(true).when(dcrExecutor) - .callDelete(eq("localhost/api/openbanking/dynamic-client-registration/register/" + - "uagAipmOU5quayzoznU1ddWg6tca"), anyString()); - - GatewayDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - DCRExecutor.setUrlMap(urlMap); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext).setError(true); - - //when token call fails - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(null).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(true).when(dcrExecutor) - .callDelete(eq("dcr/register/provided_client_id0001"), anyString()); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(2)).setError(true); - - //when retrieving client id and secret fails - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(null).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(3)).setError(true); - - //when AM application creation fails - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - Mockito.doReturn(null).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), anyString(), anyString()); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(4)).setError(true); - - //when key map response is null - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(createdApplicationResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(null).when(dcrExecutor) - .callPost(eq("/keyMap/01234567-0123-0123-0123-012345678901"), anyString(), anyString()); - ///appCreate/01234567-0123-0123-0123-012345678901 - Mockito.doReturn(true).when(dcrExecutor) - .callDelete(eq("/appCreate/01234567-0123-0123-0123-012345678901"), anyString()); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(5)).setError(true); - - //when retrieving published apis get a null response - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(createdApplicationResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(keyMapResponse)).when(dcrExecutor) - .callPost(eq("/keyMap/01234567-0123-0123-0123-012345678901"), anyString(), anyString()); - Mockito.doReturn(null).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString()), anyString(), anyString(), - anyString()); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(6)).setError(true); - - - //when subscribing to APIs get null response - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(createdApplicationResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(keyMapResponse)).when(dcrExecutor) - .callPost(eq("/keyMap/01234567-0123-0123-0123-012345678901"), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(publishedAPIResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString()), anyString(), anyString(), - anyString()); - Mockito.doReturn(null).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.API_SUBSCRIBE_URL).toString()), anyString(), anyString()); - - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(7)).setError(true); - - //when deleting internal SP get false - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.IAM_DCR_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(tokenResponse)).when(dcrExecutor) - .getToken(anyString(), eq(urlMap.get(GatewayConstants.TOKEN_URL).toString()), anyString()); - Mockito.doReturn(jsonParser.parse(isDcrResponse)).when(dcrExecutor) - .callGet(eq("dcr/register/uagAipmOU5quayzoznU1ddWg6tca"), - anyString(), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(createdApplicationResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.APP_CREATE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(keyMapResponse)).when(dcrExecutor) - .callPost(eq("/keyMap/01234567-0123-0123-0123-012345678901"), anyString(), anyString()); - Mockito.doReturn(jsonParser.parse(publishedAPIResponse)).when(dcrExecutor) - .callGet(eq(urlMap.get(GatewayConstants.API_RETRIEVE_URL).toString()), anyString(), anyString(), - anyString()); - Mockito.doReturn(jsonParser.parse(subscriptionResponse)).when(dcrExecutor) - .callPost(eq(urlMap.get(GatewayConstants.API_SUBSCRIBE_URL).toString()), anyString(), anyString()); - Mockito.doReturn(false).when(dcrExecutor) - .callDelete(eq("dcr/register/provided_client_id0001"), anyString()); - dcrExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(8)).setError(true); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/common/reporting/data/executor/CommonReportingDataExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/common/reporting/data/executor/CommonReportingDataExecutorTest.java deleted file mode 100644 index 43328482..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/common/reporting/data/executor/CommonReportingDataExecutorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.common.reporting.data.executor; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.APIRequestInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * Test for common reporting data executor. - */ -public class CommonReportingDataExecutorTest { - - @Test(priority = 1) - public void testPreRequestFlow() { - - String userAgent = "testUserAgent"; - String electedResource = "/test"; - String messageId = "test_message_id"; - String apiId = "test_apiId"; - String version = "1.0.0"; - String apiName = "testAPI"; - String httpMethod = "GET"; - String sampleToken = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ0cHAiLCJhdXQiOiJBUFBMSUNBVElPTiIsImNvbnNlbnRfaWQiOiJ4eX" + - "pfY29uc25ldF9pZCJ9.wTIt8KUMRjpWD5WML6GYM1BlBOHzTdroVjuDaeFyb7gmVoCPF9zUjzIS1FDbHCh-xf8n5RvlruTwSDgu" + - "g3BUMpvy3fJT5C2dQQiXbkH-aofSrWCBjvHSN1D5GJGnd0TmD9cN2nEfFEbhLao8IeJS8Gj-NvMVP7bloZ_USyiD273gLnmWl53" + - "e2pSYYp7N_b97Ci-nH4WnooHq4HS5f94G85CIJQm6vIUjm0wnzQyVg9Uh_BipUrtV1PMz1h5ugOrv003kBmV10oszj4BSZhscuW" + - "4xSe07jgIN7xPvsx02hzSVHjTXA4hWhP7YeTzSCvpVcDPREtjIT800cf35akhv0w"; - - MsgInfoDTO msgInfoDTO = new MsgInfoDTO(); - msgInfoDTO.setHttpMethod(httpMethod); - - Map headers = new HashMap<>(); - headers.put("Authorization", sampleToken); - headers.put("User-Agent", userAgent); - msgInfoDTO.setHeaders(headers); - msgInfoDTO.setElectedResource(electedResource); - msgInfoDTO.setMessageId(messageId); - - APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO(); - apiRequestInfoDTO.setApiId(apiId); - apiRequestInfoDTO.setVersion(version); - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.getAnalyticsData()).thenReturn(new HashMap<>()); - Mockito.when(obapiRequestContext.getMsgInfo()).thenReturn(msgInfoDTO); - Mockito.when(obapiRequestContext.getApiRequestInfo()).thenReturn(apiRequestInfoDTO); - - CommonReportingDataExecutor commonReportingDataExecutor = Mockito.spy(CommonReportingDataExecutor.class); - Mockito.doReturn(apiName).when(commonReportingDataExecutor).getApiName(Mockito.any()); - commonReportingDataExecutor.preProcessRequest(obapiRequestContext); - - Assert.assertEquals(obapiRequestContext.getAnalyticsData().size(), 7); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("userAgent"), userAgent); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("electedResource"), electedResource); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("httpMethod"), httpMethod); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("apiName"), apiName); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("apiSpecVersion"), version); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("messageId"), messageId); - Assert.assertTrue((long) obapiRequestContext.getAnalyticsData().get("timestamp") > 0); - } - - @Test(priority = 2) - public void testPostRequestFlow() { - - String username = "tpp@wso2.conm"; - String clientId = "test_client_id"; - String consentId = "test_consent_id"; - - APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO(); - apiRequestInfoDTO.setUsername(username); - apiRequestInfoDTO.setConsumerKey(clientId); - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.getApiRequestInfo()).thenReturn(apiRequestInfoDTO); - Mockito.when(obapiRequestContext.getAnalyticsData()).thenReturn(new HashMap<>()); - Mockito.when(obapiRequestContext.getConsentId()).thenReturn(consentId); - - CommonReportingDataExecutor commonReportingDataExecutor = Mockito.spy(CommonReportingDataExecutor.class); - commonReportingDataExecutor.postProcessRequest(obapiRequestContext); - - Assert.assertEquals(obapiRequestContext.getAnalyticsData().size(), 3); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("consumerId"), username); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("consentId"), consentId); - Assert.assertEquals(obapiRequestContext.getAnalyticsData().get("clientId"), clientId); - } - - @Test(priority = 3) - public void testPreResponseFlow() { - CommonReportingDataExecutor commonReportingDataExecutor = new CommonReportingDataExecutor(); - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiResponseContext.getAnalyticsData()).thenReturn(new HashMap<>()); - Mockito.when(obapiResponseContext.getModifiedPayload()).thenReturn("testPayloadOfLength21"); - Mockito.when(obapiResponseContext.getStatusCode()).thenReturn(200); - - commonReportingDataExecutor.preProcessResponse(obapiResponseContext); - Assert.assertTrue(obapiResponseContext.getAnalyticsData().size() == 2); - Assert.assertEquals(obapiResponseContext.getAnalyticsData().get("responsePayloadSize"), (long) 21); - Assert.assertEquals(obapiResponseContext.getAnalyticsData().get("statusCode"), 200); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/consent/TestEnforcementExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/consent/TestEnforcementExecutor.java deleted file mode 100644 index 7ca77016..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/consent/TestEnforcementExecutor.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.consent; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import com.wso2.openbanking.accelerator.gateway.executor.test.TestConstants; -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.json.JSONObject; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** - * Test for enforcement executor. - */ -public class TestEnforcementExecutor { - - private static ConsentEnforcementExecutor consentEnforcementExecutor; - private static OBAPIRequestContext obapiRequestContext; - private String jwtToken = "eyJjdXN0b20iOiJwYXlsb2FkIn0"; - - @BeforeClass - public static void beforeClass() throws OpenBankingException { - - GatewayDataHolder dataHolder = GatewayDataHolder.getInstance(); - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - dataHolder.setKeyStoreLocation(absolutePathForTestResources + "/wso2carbon.jks"); - dataHolder.setKeyAlias("wso2carbon"); - dataHolder.setKeyPassword("wso2carbon"); - dataHolder.setKeyStorePassword("wso2carbon".toCharArray()); - - consentEnforcementExecutor = new ConsentEnforcementExecutor(); - } - - @Test(priority = 1) - public void testSigningKeyRetrieval() { - - Assert.assertNotNull(consentEnforcementExecutor.getJWTSigningKey()); - } - - @Test(priority = 2) - public void testJWTGeneration() { - - String jwtToken = consentEnforcementExecutor.generateJWT(TestConstants.CUSTOM_PAYLOAD); - Assert.assertNotNull(jwtToken); - String[] parts = jwtToken.split("\\."); - Assert.assertEquals(parts.length, 3); - } - - @Test(priority = 2) - public void testValidationPayloadCreation() { - - Map headers = new HashMap<>(); - headers.put("customHeader", "headerValue"); - headers.put("customHeader2", "headerValue2"); - JSONObject jsonObject = - consentEnforcementExecutor.createValidationRequestPayload(headers, - TestConstants.CUSTOM_PAYLOAD, new HashMap<>()); - Assert.assertNotNull(jsonObject); - Assert.assertEquals(((JSONObject) jsonObject.get(ConsentEnforcementExecutor.HEADERS_TAG)).get("customHeader"), - "headerValue"); - Assert.assertEquals(((JSONObject) jsonObject.get(ConsentEnforcementExecutor.BODY_TAG)).get("custom"), - "payload"); - } - - @Test(priority = 3) - public void testB64Decoder() throws UnsupportedEncodingException { - - JSONObject jsonObject = GatewayUtils.decodeBase64(jwtToken); - Assert.assertEquals(jsonObject.get("custom").toString(), "payload"); - } - - @Test - public void testHandlerError() { - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - ArrayList errors = new ArrayList<>(); - Mockito.when(obapiRequestContext.getErrors()).thenReturn(errors); - consentEnforcementExecutor.handleError(obapiRequestContext, "Error", "Error", - "400"); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/error/handler/OBDefaultErrorHandlerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/error/handler/OBDefaultErrorHandlerTest.java deleted file mode 100644 index 810e7b59..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/error/handler/OBDefaultErrorHandlerTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.error.handler; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OpenBankingExecutorError; -import org.mockito.Mockito; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * Test class for OBDefaultErrorHandler. - */ -public class OBDefaultErrorHandlerTest { - - Map contextProps = new HashMap<>(); - - @Test - public void testPreRequestFlow() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(true); - Mockito.when(obapiRequestContext.getErrors()).thenReturn(getErrorList()); - Mockito.when(obapiRequestContext.getContextProps()).thenReturn(contextProps); - Mockito.when(obapiRequestContext.getAnalyticsData()).thenReturn(new HashMap<>()); - - OBDefaultErrorHandler commonReportingDataExecutor = Mockito.spy(OBDefaultErrorHandler.class); - commonReportingDataExecutor.preProcessRequest(obapiRequestContext); - verify(obapiRequestContext, times(0)).setError(false); - } - - @Test - public void testPostRequestFlow() { - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.isError()).thenReturn(true); - Mockito.when(obapiRequestContext.getErrors()).thenReturn(getErrorList()); - Mockito.when(obapiRequestContext.getContextProps()).thenReturn(contextProps); - Mockito.when(obapiRequestContext.getAnalyticsData()).thenReturn(new HashMap<>()); - - OBDefaultErrorHandler commonReportingDataExecutor = Mockito.spy(OBDefaultErrorHandler.class); - commonReportingDataExecutor.postProcessRequest(obapiRequestContext); - verify(obapiRequestContext, times(0)).setError(false); - } - - @Test - public void testPreResponseFlow() { - - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiResponseContext.isError()).thenReturn(true); - Mockito.when(obapiResponseContext.getErrors()).thenReturn(getErrorList()); - Mockito.when(obapiResponseContext.getContextProps()).thenReturn(contextProps); - Mockito.when(obapiResponseContext.getAnalyticsData()).thenReturn(new HashMap<>()); - - OBDefaultErrorHandler commonReportingDataExecutor = Mockito.spy(OBDefaultErrorHandler.class); - commonReportingDataExecutor.preProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(0)).setError(false); - } - - @Test - public void testPostResponseFlow() { - - OBAPIResponseContext obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - Mockito.when(obapiResponseContext.isError()).thenReturn(true); - Mockito.when(obapiResponseContext.getErrors()).thenReturn(getErrorList()); - Mockito.when(obapiResponseContext.getContextProps()).thenReturn(contextProps); - Mockito.when(obapiResponseContext.getAnalyticsData()).thenReturn(new HashMap<>()); - - OBDefaultErrorHandler commonReportingDataExecutor = Mockito.spy(OBDefaultErrorHandler.class); - commonReportingDataExecutor.postProcessResponse(obapiResponseContext); - verify(obapiResponseContext, times(0)).setError(false); - } - - private ArrayList getErrorList() { - - OpenBankingExecutorError error = new OpenBankingExecutorError("400", "Invalid Request", - "Mandatory parameter is missing", "400"); - - ArrayList errors = new ArrayList<>(); - errors.add(error); - return errors; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/CertRevocationValidationExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/CertRevocationValidationExecutorTest.java deleted file mode 100644 index c9f7b963..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/CertRevocationValidationExecutorTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.mtls.cert.validation.executor; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.gateway.cache.CertificateRevocationCache; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.executor.service.CertValidationService; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.executor.util.TestValidationUtil; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Collections; - -/** - * Test cases for MTLSCertValidationExecutor class. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({CertificateValidationUtils.class, TPPCertValidatorDataHolder.class, - CertValidationService.class, CertificateRevocationCache.class}) -public class CertRevocationValidationExecutorTest { - - CertRevocationValidationExecutor certRevocationValidationExecutor; - @Mock - TPPCertValidatorDataHolder tppCertValidatorDataHolder; - @Mock - CertValidationService certValidationService; - - private X509Certificate testPeerCertificate; - private X509Certificate testPeerCertificateIssuer; - private X509Certificate eidasPeerCertificate; - private X509Certificate expiredPeerCertificate; - - @BeforeClass - public void init() throws CertificateValidationException, CertificateException, OpenBankingException { - MockitoAnnotations.initMocks(this); - this.certRevocationValidationExecutor = new CertRevocationValidationExecutor(); - - this.testPeerCertificate = TestValidationUtil.getTestClientCertificate(); - this.testPeerCertificateIssuer = TestValidationUtil.getTestClientCertificateIssuer(); - this.eidasPeerCertificate = TestValidationUtil.getTestEidasCertificate(); - this.expiredPeerCertificate = TestValidationUtil.getExpiredSelfCertificate(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - - @Test(description = "When expired certificate is provided, then should return true") - public void testIsCertValidWithExpiredCert() { - Assert.assertTrue(CertificateUtils.isExpired(expiredPeerCertificate)); - } - - @Test(description = "When certificate validation success, then should return false") - public void testIsCertRevokedWithNonCachedCert() throws Exception { - CertificateRevocationCache mock = Mockito.mock(CertificateRevocationCache.class); - PowerMockito.mockStatic(CertificateRevocationCache.class); - PowerMockito.when(CertificateRevocationCache.getInstance()) - .thenReturn(mock); - - boolean isCertRevoked = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevoked", testPeerCertificate); - Assert.assertFalse(isCertRevoked); - } - - @Test(description = "When cached certificate provided, then return false") - public void testIsCertRevokedWithCachedCert() throws Exception { - CertificateRevocationCache mock = Mockito.mock(CertificateRevocationCache.class); - Mockito.doReturn(true).when(mock).getFromCache(Mockito.any(GatewayCacheKey.class)); - - PowerMockito.mockStatic(CertificateRevocationCache.class); - PowerMockito.when(CertificateRevocationCache.getInstance()) - .thenReturn(mock); - - boolean isCertRevoked = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevoked", testPeerCertificate); - - Assert.assertFalse(isCertRevoked); - } - - @Test(description = "When self signed certificate provided, then should return true") - public void testIsCertRevocationSuccessWithSelfSignedCert() throws Exception { - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()).thenReturn(true); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - boolean isCertRevocationSuccess = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevocationSuccess", expiredPeerCertificate); - - Assert.assertTrue(isCertRevocationSuccess); - } - - @Test(description = "When isCertificateRevocationValidationEnabled is false, then should return true") - public void testIsCertRevocationSuccessWithDisabledRevocationValidation() throws Exception { - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()).thenReturn(false); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - boolean isCertRevocationSuccess = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevocationSuccess", expiredPeerCertificate); - - Assert.assertTrue(isCertRevocationSuccess); - } - - @Test(description = "When certificate issuer is in excluded list, then should return true") - public void testIsCertRevocationSuccessWithExcludedIssuers() throws Exception { - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()).thenReturn(true); - Mockito.when(tppCertValidatorDataHolder.getCertificateRevocationValidationExcludedIssuers()) - .thenReturn(Collections.singletonList(eidasPeerCertificate.getIssuerDN().getName())); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - boolean isCertRevocationSuccess = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevocationSuccess", eidasPeerCertificate); - - Assert.assertTrue(isCertRevocationSuccess); - } - - @Test(description = "When peer certificate is valid, then should return true") - public void testIsCertRevocationSuccessWithValidCerts() throws Exception { - Mockito.when(tppCertValidatorDataHolder.getCertificateRevocationValidationExcludedIssuers()).thenReturn( - Collections.singletonList("")); - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()).thenReturn(true); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito - .when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - PowerMockito.mockStatic(CertificateValidationUtils.class); - PowerMockito.when(CertificateValidationUtils.getIssuerCertificateFromTruststore( - Mockito.any(X509Certificate.class))).thenReturn(testPeerCertificateIssuer); - - Mockito.when(certValidationService.verify(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), - Mockito.anyInt())).thenReturn(true); - - PowerMockito.mockStatic(CertValidationService.class); - PowerMockito - .when(CertValidationService.getInstance()) - .thenReturn(certValidationService); - - boolean isCertRevocationSuccess = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevocationSuccess", testPeerCertificate); - - Assert.assertTrue(isCertRevocationSuccess); - } - - @Test(description = "When peer certificate is invalid, then should throw CertificateValidationException") - public void testIsCertRevocationSuccessWithInValidCert() throws Exception { - Mockito.when(tppCertValidatorDataHolder.getCertificateRevocationValidationExcludedIssuers()) - .thenReturn(Collections.singletonList("")); - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()).thenReturn(true); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito - .when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - Mockito.when(certValidationService.verify(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class), Mockito.anyInt())).thenReturn(true); - - PowerMockito.mockStatic(CertValidationService.class); - PowerMockito - .when(CertValidationService.getInstance()) - .thenReturn(certValidationService); - - boolean isCertRevocationSuccess = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevocationSuccess", testPeerCertificate); - - Assert.assertFalse(isCertRevocationSuccess); - } - - @Test(description = "When certificate revocation validation not configured, then should return true") - public void testIsCertRevocationSuccessWithFalseCertificateRevocationValidation() throws Exception { - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()).thenReturn(false); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito - .when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - boolean isCertRevocationSuccess = WhiteboxImpl.invokeMethod(this.certRevocationValidationExecutor, - "isCertRevocationSuccess", testPeerCertificate); - - Assert.assertTrue(isCertRevocationSuccess); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/MTLSEnforcementExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/MTLSEnforcementExecutorTest.java deleted file mode 100644 index e2f92491..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/mtls/cert/validation/executor/MTLSEnforcementExecutorTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.mtls.cert.validation.executor; - -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import org.mockito.Mockito; -import org.testng.annotations.Test; - -import java.util.ArrayList; -/** - * Test class for MTLSEnforcementExecutor. - */ -public class MTLSEnforcementExecutorTest { - - @Test(description = "When an error occurs, then it should set errors to the obApiRequestContext") - public void testPreProcessRequest() throws Exception { - MTLSEnforcementExecutor mtlsEnforcementExecutor = new MTLSEnforcementExecutor(); - - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - Mockito.when(obapiRequestContext.getErrors()).thenReturn(new ArrayList<>()); - - mtlsEnforcementExecutor.preProcessRequest(obapiRequestContext); - - Mockito.verify(obapiRequestContext, Mockito.times(1)).setError(true); - Mockito.verify(obapiRequestContext, Mockito.times(1)).setErrors(Mockito.any()); - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/selfcare/portal/UserPermissionValidationExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/selfcare/portal/UserPermissionValidationExecutorTest.java deleted file mode 100644 index 425385c7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/selfcare/portal/UserPermissionValidationExecutorTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.selfcare.portal; - -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.Optional; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -/** - * UserPermissionValidationExecutorTest. - *

- * Contains unit tests for UserPermissionValidationExecutor class - */ -@PrepareForTest({GatewayUtils.class}) -@PowerMockIgnore({"jdk.internal.reflect.*"}) -public class UserPermissionValidationExecutorTest { - - private UserPermissionValidationExecutor uut; - - @BeforeClass - public void setup() { - this.uut = new UserPermissionValidationExecutor(); - } - - @Test(description = "when valid url provided, return user IDs") - public void testGetUserIdsFromQueryParamsWithValidUrl() { - PowerMockito.mockStatic(GatewayUtils.class); - when(GatewayUtils.getUserNameWithTenantDomain(anyString())).thenReturn("admin@wso2.com@carbon.super"); - - final String url = "https://localhost:9446/api/consent/admin/search?userIDs=admin@wso2.com&limit=25"; - Optional optUserIds = uut.getUserIdsFromQueryParams(url); - - Assert.assertTrue(optUserIds.isPresent()); - Assert.assertEquals(optUserIds.get(), "admin@wso2.com@carbon.super"); - } - - @Test(description = "when invalid url provided, return empty") - public void testGetUserIdsFromQueryParamsWithInvalidUrl() { - final String url = "https://localhost:9446/api/consent/admin/search?limit=25"; - Optional optUserIds = uut.getUserIdsFromQueryParams(url); - - Assert.assertFalse(optUserIds.isPresent()); - } - - @Test(description = "when valid customer care officer's scopes received from access token, return true") - public void testIsCustomerCareOfficerWithValidScope() { - Assert.assertTrue(uut.isCustomerCareOfficer("consentmgt " + - GatewayConstants.CUSTOMER_CARE_OFFICER_SCOPE + " openid")); - } - - @Test(description = "when invalid scope received from access token, return false") - public void testIsCustomerCareOfficerWithInvalidScope() { - Assert.assertFalse(uut.isCustomerCareOfficer(" ")); - Assert.assertFalse(uut.isCustomerCareOfficer("consentmgt consents:read_self openid")); - } - - @Test(description = "when userId is matching with access token subject, return true") - public void testIsUserIdMatchesTokenSub() { - Assert.assertTrue(uut.isUserIdMatchesTokenSub("amy@gold.com@carbon.super", "amy@gold.com@carbon.super")); - Assert.assertTrue(uut.isUserIdMatchesTokenSub("amy@gold.com", "amy@gold.com")); - - Assert.assertFalse(uut.isUserIdMatchesTokenSub("mark@gold.com", "amy@gold.com")); - Assert.assertFalse(uut.isUserIdMatchesTokenSub("amy@gold.com@carbon.super", "amy@gold.com")); - Assert.assertFalse(uut.isUserIdMatchesTokenSub("amy@gold.com", "amy@gold.com@carbon.super")); - Assert.assertFalse(uut.isUserIdMatchesTokenSub(" ", "amy@gold.com@carbon.super")); - Assert.assertFalse(uut.isUserIdMatchesTokenSub("amy@gold.com", "")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/APITPPValidationExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/APITPPValidationExecutorTest.java deleted file mode 100644 index 4e760c78..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/APITPPValidationExecutorTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.tpp.validation.executor; - -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.security.SecurityRequirement; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Test for API TPP validation executor. - */ -public class APITPPValidationExecutorTest { - - private APITPPValidationExecutor apitppValidationExecutor; - private Map> allowedScopes; - private SecurityRequirement securityRequirement; - - @BeforeClass - public void init() { - this.allowedScopes = new HashMap<>(); - allowedScopes.put("accounts", Arrays.asList("AISP", "PISP")); - allowedScopes.put("payments", Collections.singletonList("PISP")); - - securityRequirement = new SecurityRequirement(); - securityRequirement.put("PSUOAuth2Security", Arrays.asList("accounts", "payments")); - securityRequirement.put("default", Collections.singletonList("accounts")); - - this.apitppValidationExecutor = new APITPPValidationExecutor(); - } - - @Test(description = "when valid scopes provided, then requiredPSD2Roles list should contain roles") - public void testGetRolesFromScopesWithValidScopes() throws Exception { - Set scopes = new HashSet<>(); - scopes.add("accounts"); - scopes.add("payments"); - - List roleList = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "getRolesFromScopes", allowedScopes, scopes); - - Assert.assertTrue(roleList.size() != 0); - Assert.assertTrue(roleList.contains(PSD2RoleEnum.AISP)); - } - - @Test(description = "when invalid scopes provided, then requiredPSD2Roles list should be empty") - public void testGetRolesFromScopesWithInvalidScopes() throws Exception { - Set scopes = new HashSet<>(); - scopes.add("default"); - - List roleList = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "getRolesFromScopes", allowedScopes, scopes); - - Assert.assertEquals(roleList.size(), 0); - } - - @Test(description = "when security requirement provided for GET API, then set of scopes should return") - public void testExtractScopesFromSwaggerAPIWithGet() throws Exception { - Operation get = new Operation(); - get.setSecurity(Collections.singletonList(securityRequirement)); - - PathItem pathItem = new PathItem(); - pathItem.setGet(get); - - Set scopes = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "extractScopesFromSwaggerAPI", pathItem, "GET"); - - Assert.assertTrue(scopes.size() != 0); - Assert.assertTrue(scopes.contains("accounts")); - } - - @Test(description = "when security requirement provided for POST API, then set of scopes should return") - public void testExtractScopesFromSwaggerAPIWithPost() throws Exception { - Operation post = new Operation(); - post.setSecurity(Collections.singletonList(securityRequirement)); - - PathItem pathItem = new PathItem(); - pathItem.setPost(post); - - Set scopes = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "extractScopesFromSwaggerAPI", pathItem, "POST"); - - Assert.assertTrue(scopes.size() != 0); - Assert.assertTrue(scopes.contains("accounts")); - } - - @Test(description = "when security requirement provided for PUT API, then set of scopes should return") - public void testExtractScopesFromSwaggerAPIWithPut() throws Exception { - Operation put = new Operation(); - put.setSecurity(Collections.singletonList(securityRequirement)); - - PathItem pathItem = new PathItem(); - pathItem.setPut(put); - - Set scopes = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "extractScopesFromSwaggerAPI", pathItem, "PUT"); - - Assert.assertTrue(scopes.size() != 0); - Assert.assertTrue(scopes.contains("accounts")); - } - - @Test(description = "when security requirement provided for PATCH API, then set of scopes should return") - public void testExtractScopesFromSwaggerAPIWithPatch() throws Exception { - Operation patch = new Operation(); - patch.setSecurity(Collections.singletonList(securityRequirement)); - - PathItem pathItem = new PathItem(); - pathItem.setPatch(patch); - - Set scopes = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "extractScopesFromSwaggerAPI", pathItem, "PATCH"); - - Assert.assertTrue(scopes.size() != 0); - Assert.assertTrue(scopes.contains("accounts")); - } - - @Test(description = "when security requirement provided for DELETE API, then set of scopes should return") - public void testExtractScopesFromSwaggerAPIWithDelete() throws Exception { - Operation delete = new Operation(); - delete.setSecurity(Collections.singletonList(securityRequirement)); - - PathItem pathItem = new PathItem(); - pathItem.setDelete(delete); - - Set scopes = WhiteboxImpl.invokeMethod(this.apitppValidationExecutor, - "extractScopesFromSwaggerAPI", pathItem, "DELETE"); - - Assert.assertTrue(scopes.size() != 0); - Assert.assertTrue(scopes.contains("accounts")); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/DCRTPPValidationExecutorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/DCRTPPValidationExecutorTest.java deleted file mode 100644 index e6c42d31..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/impl/tpp/validation/executor/DCRTPPValidationExecutorTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.impl.tpp.validation.executor; - -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.gateway.executor.util.TestValidationUtil; -import net.minidev.json.JSONObject; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.util.List; - -/** - * Test for DCR TPP validation executor. - */ -@PowerMockIgnore({"org.mockito.*", "javax.script.*"}) -public class DCRTPPValidationExecutorTest { - - private static final String BODY = "body"; - private static final String SOFTWARE_STATEMENT = "software_statement"; - - private DCRTPPValidationExecutor dcrtppValidationExecutor; - - @BeforeClass - public void init() { - this.dcrtppValidationExecutor = new DCRTPPValidationExecutor(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test(description = "when valid SSA provided, then return extracted software roles as string") - public void testGetRolesFromSsaAsString() throws Exception { - JSONObject requestBody = JWTUtils.decodeRequestJWT(TestValidationUtil.REQUEST_BODY_WITH_SSA, BODY); - String expectedSSA = requestBody.getAsString(SOFTWARE_STATEMENT); - - String actualSSA = WhiteboxImpl.invokeMethod(this.dcrtppValidationExecutor, - "getSSAFromPayload", TestValidationUtil.REQUEST_BODY_WITH_SSA); - - Assert.assertEquals(actualSSA, expectedSSA); - } - - @Test(description = "when valid software statement provided, then requiredPSD2Roles list should return") - public void testGetRolesFromSSAWithValidSSA() throws Exception { - JSONObject requestBody = JWTUtils.decodeRequestJWT(TestValidationUtil.REQUEST_BODY_WITH_SSA, BODY); - // extract software statement - String softwareStatement = requestBody.getAsString(SOFTWARE_STATEMENT); - - List rolesFromSSA = this.dcrtppValidationExecutor.getRolesFromSSA(softwareStatement); - - Assert.assertEquals(rolesFromSSA.size(), 2); - Assert.assertTrue(rolesFromSSA.contains(PSD2RoleEnum.AISP)); - } - - @Test(description = "when invalid software roles provided, then empty requiredPSD2Roles list should return") - public void testGetRolesFromSSAWithInvalidRoles() throws Exception { - - JSONObject requestBody = JWTUtils.decodeRequestJWT(TestValidationUtil.REQUEST_BODY_WITH_SSA_SINGLE_ROLE, BODY); - // extract software statement - String softwareStatement = requestBody.getAsString(SOFTWARE_STATEMENT); - List rolesFromSSA = this.dcrtppValidationExecutor.getRolesFromSSA(softwareStatement); - - Assert.assertTrue(rolesFromSSA.isEmpty()); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsRequestSignatureHandlingExecutorTests.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsRequestSignatureHandlingExecutorTests.java deleted file mode 100644 index 5a13dade..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsRequestSignatureHandlingExecutorTests.java +++ /dev/null @@ -1,299 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.jws; - -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.Payload; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.error.OpenBankingErrorCodes; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.HttpMethod; - -import static org.powermock.api.mockito.PowerMockito.mock; - -/** - * Test class for JwsRequestSignatureHandlingExecutor. - */ - -@PowerMockIgnore({"jdk.internal.reflect.*", "javax.management.*"}) -@PrepareForTest({OpenBankingConfigParser.class}) - -public class JwsRequestSignatureHandlingExecutorTests { - - private static final Log log = LogFactory.getLog(JwsRequestSignatureHandlingExecutorTests.class); - - private OBAPIRequestContext obapiRequestContextMock; - - private MsgInfoDTO msgInfoDTO; - - JwsRequestSignatureHandlingExecutor jwsRequestSignatureHandlingExecutor; - - Map sampleRequestHeaders = new HashMap<>(); - - public JwsRequestSignatureHandlingExecutorTests() throws Exception { - sampleRequestHeaders.put("Authorization", "Bearer 2YotnFZFEjr1zCsicMWpAA"); - sampleRequestHeaders.put("x-idempotency-key", "FRESCO.21302.GFX.20"); - sampleRequestHeaders.put("x-jws-signature", "TGlmZSdzIGEgam91cm5leSBub3QgYSBkZXN0aW5hdGlvbiA=" + - "..T2ggZ29vZCBldmVuaW5nIG1yIHR5bGVyIGdvaW5nIGRvd24gPw=="); - sampleRequestHeaders.put("x-fapi-auth-date", "Sun, 10 Sep 2017 19:43:31 GMT"); - sampleRequestHeaders.put("x-fapi-customer-ip-address", "104.25.212.99"); - sampleRequestHeaders.put("x-fapi-interaction-id", "93bac548-d2de-4546-b106-880a5018460d"); - sampleRequestHeaders.put("Content-Type", "text/xml"); - sampleRequestHeaders.put("Accept", "application/json"); - } - - String samplejwsSignature = "V2hhdCB3ZSBnb3QgaGVyZQ0K..aXMgZmFpbHVyZSB0byBjb21tdW5pY2F0ZQ0K"; - - String sampleJWEsignature = "V2hhdCB3ZSBnb3QgaGVyZQ0K.V2hhdCB3ZSBnb3QgaGVyZQ0K." + - "V2hhdCB3ZSBnb3QgaGVyZQ0K.V2hhdCB3ZSBnb3QgaGVyZQ0K.V2hhdCB3ZSBnb3QgaGVyZQ0K"; - - String sampleRequestPayload = "{\"Data\":{\"Initiation\":{\"InstructionIdentification\":" + - "\"ACME412\",\"EndToEndIdentification\":\"FRESCO.21302.GFX.20\",\"InstructedAmount\":" + - "{\"Amount\":\"165.88\",\"Currency\":\"GBP\"},\"CreditorAccount\":" + - "{\"SchemeName\":\"UK.OBIE.SortCodeAccountNumber\",\"Identification\":\"08080021325698\"" + - "\"Name\":\"ACME Inc\",\"SecondaryIdentification\":\"0002\"}," + - "\"RemittanceInformation\":{\"Reference\":\"FRESCO-101\",\"Unstructured\":\"" + - "Internal ops code 5120101\"}}}," + - "\"Risk\":{" + - "{\"PaymentContextCode\":\"EcommerceGoods\",\"MerchantCategoryCode\":\"5967\"," + - "\"MerchantCustomerIdentification\":\"053598653254\",\"DeliveryAddress\":{" + - "\"AddressLine\":[\"Flat 7\",\"Acacia Lodge\"]," + - "\"StreetName\":\"Acacia Avenue\",\"BuildingNumber\":\"27\",\"PostCode\":\"GU31 2ZZ\"" + - "\"TownName\":\"Sparsholt,\"CountrySubDivision\":\"Wessex\",\"Country\":\"UK\"}}}"; - - String requestHeaderb64False = "{\n" + - "\"alg\": \"PS256\",\n" + - "\"kid\": \"12345\",\n" + - "\"b64\": false, \n" + - "\"http://openbanking.org.uk/iat\": 1739485930,\n" + - "\"http://openbanking.org.uk/iss\": \"http://openbanking.org.uk\", \n" + - "\"crit\": [ \"b64\", \"http://openbanking.org.uk/iat\",\n" + - "\"http://openbanking.org.uk/iss\"] \n" + - "}"; - String requestHeaderb64None = "{\n" + - "\"alg\": \"PS256\",\n" + - "\"kid\": \"12345\",\n" + - "\"http://openbanking.org.uk/iat\": 1739485930,\n" + - "\"http://openbanking.org.uk/iss\": \"http://openbanking.org.uk\", \n" + - "\"crit\": [ \"http://openbanking.org.uk/iat\",\n" + - "\"http://openbanking.org.uk/iss\"] \n" + - "}"; - - @BeforeClass - public void initClass() { - - MockitoAnnotations.initMocks(this); - jwsRequestSignatureHandlingExecutor = new JwsRequestSignatureHandlingExecutor(); - } - - /** - * Test a request with an error. - * @throws Exception - */ - @Test - public void testWithErrorRequest() throws Exception { - - // Mocking request headers - obapiRequestContextMock = mock(OBAPIRequestContext.class); - msgInfoDTO = mock(MsgInfoDTO.class); - PowerMockito.when(obapiRequestContextMock.isError()).thenReturn(true); - PowerMockito.when(msgInfoDTO.getHttpMethod()). - thenReturn(HttpMethod.POST); - - boolean isPreProcessValidationPassed = WhiteboxImpl.invokeMethod( - this.jwsRequestSignatureHandlingExecutor, - "preProcessValidation", obapiRequestContextMock, sampleRequestHeaders); - log.debug("Preprocess Validation passed? " + isPreProcessValidationPassed); - - //should return false - Assert.assertFalse(isPreProcessValidationPassed); - } - - /** - * Test if a JWS consisting of 3 parts are returned at reconstructing JWS. - * @throws Exception - */ - @Test - public void testReconstructJWS() throws Exception { - - String reconstructedJWS = WhiteboxImpl.invokeMethod(this.jwsRequestSignatureHandlingExecutor, - "reconstructJws", samplejwsSignature, sampleRequestPayload); - log.debug("The reconstructed JWS, " + reconstructedJWS); - - Assert.assertTrue(reconstructedJWS.split("\\.").length == 3); - } - - /** - * Test reconstructing a JWS with a Payload with empty string. - * @throws Exception - */ - @Test - public void testReconstructJWSException() throws Exception { - - Method method = JwsRequestSignatureHandlingExecutor.class.getDeclaredMethod( - "reconstructJws", String.class, String.class); - method.setAccessible(true); - - Assert.expectThrows(Exception.class, ()-> - method.invoke(this.jwsRequestSignatureHandlingExecutor, samplejwsSignature, "")); - - } - - /** - * Test reconstructing a JWS if the passed value is a JWE. - * @throws Exception - */ - @Test - public void testReconstructJWE() throws Exception { - - Method method = JwsRequestSignatureHandlingExecutor.class.getDeclaredMethod( - "reconstructJws", String.class, String.class); - method.setAccessible(true); - - Assert.expectThrows(Exception.class, ()-> - method.invoke(this.jwsRequestSignatureHandlingExecutor, - sampleJWEsignature, sampleRequestPayload)); - } - - /** - * Test a request with a JWS having b64 header claim set to false. - * @throws Exception - */ - @Test - public void testb64FalseSigningInput() throws Exception { - - JWSAlgorithm signJWSAlg = JWSAlgorithm.parse("PS256"); - HashSet hs = new HashSet(); - hs.add("crit"); - JWSHeader header = new JWSHeader(signJWSAlg, null, null, hs, null, - null, null, null, null, null, "samplekid", - null, null); - byte[] input = WhiteboxImpl.invokeMethod(this.jwsRequestSignatureHandlingExecutor, - "getSigningInput", header, sampleRequestPayload); - Assert.assertNotNull(input); - } - - /** - * Test with a JOSE header b64 claim set to false. - * @throws Exception - */ - @Test - public void testb64Verifiability() throws Exception { - - JWSHeader header = JWSHeader.parse(requestHeaderb64False); - JWSObject jwsObject = new JWSObject(header, new Payload(sampleRequestPayload)); - Method method = JwsRequestSignatureHandlingExecutor.class.getDeclaredMethod( - "isB64HeaderVerifiable", JWSObject.class); - method.setAccessible(true); - boolean isB64Verifiable = (boolean) method.invoke(this.jwsRequestSignatureHandlingExecutor, jwsObject); - - Assert.assertFalse(isB64Verifiable); - } - - /** - * Test a JOSE header with no b64 claim. - * @throws Exception - */ - @Test - public void testb64VerifiabilityWithNoClaim() throws Exception { - - JWSHeader header = JWSHeader.parse(requestHeaderb64None); - JWSObject jwsObject = new JWSObject(header, new Payload(sampleRequestPayload)); - Method method = JwsRequestSignatureHandlingExecutor.class.getDeclaredMethod( - "isB64HeaderVerifiable", JWSObject.class); - method.setAccessible(true); - boolean isB64Verifiable = (boolean) method.invoke(this.jwsRequestSignatureHandlingExecutor, jwsObject); - - Assert.assertTrue(isB64Verifiable); - } - - @Test - public void testHandleRequestInternalServerError() { - - obapiRequestContextMock = mock(OBAPIRequestContext.class); - - GatewayUtils.handleRequestInternalServerError(obapiRequestContextMock, "Error", - OpenBankingErrorCodes.SERVER_ERROR_CODE); - } - - @Test - public void testHandleJwsSignatureErrors() throws NoSuchMethodException, InvocationTargetException, - IllegalAccessException { - - obapiRequestContextMock = mock(OBAPIRequestContext.class); - Method method = JwsRequestSignatureHandlingExecutor.class.getDeclaredMethod( - "handleJwsSignatureErrors", OBAPIRequestContext.class, String.class, String.class); - - method.invoke(this.jwsRequestSignatureHandlingExecutor, obapiRequestContextMock, "Error", - OpenBankingErrorCodes.BAD_REQUEST_CODE); - } - - @Test - public void testValidateClaims() throws NoSuchMethodException, InvocationTargetException, - IllegalAccessException { - - List alg = new ArrayList<>(); - alg.add("PS256"); - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.doReturn(alg).when(openBankingConfigParserMock).getJwsRequestSigningAlgorithms(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - obapiRequestContextMock = mock(OBAPIRequestContext.class); - JWSAlgorithm signJWSAlg = JWSAlgorithm.parse("PS256"); - HashSet hs = new HashSet(); - hs.add("crit"); - JWSHeader header = new JWSHeader(signJWSAlg, null, null, hs, null, - null, null, null, null, null, "samplekid", - null, null); - Method method = JwsRequestSignatureHandlingExecutor.class.getDeclaredMethod( - "validateClaims", OBAPIRequestContext.class, JWSHeader.class, String.class, - String.class); - - boolean result = (boolean) method.invoke(this.jwsRequestSignatureHandlingExecutor, - obapiRequestContextMock, header, "TestApp", null); - - Assert.assertTrue(result); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsResponseSignatureHandlingExecutorTests.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsResponseSignatureHandlingExecutorTests.java deleted file mode 100644 index 6ed4fc82..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/jws/JwsResponseSignatureHandlingExecutorTests.java +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.jws; - -import com.nimbusds.jose.JOSEObjectType; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.util.Base64URL; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewaySignatureHandlingUtils; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.APIRequestInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.MsgInfoDTO; -import org.wso2.carbon.apimgt.common.gateway.extensionlistener.PayloadHandler; - -import java.io.UnsupportedEncodingException; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Test class for JwsRequestSignatureHandlingExecutor. - */ - -@PowerMockIgnore({"jdk.internal.reflect.*", "javax.management.*"}) -@PrepareForTest({OpenBankingConfigParser.class}) -public class JwsResponseSignatureHandlingExecutorTests { - - JwsResponseSignatureHandlingExecutor jwsResponseSignatureHandlingExecutor; - @Mock - OBAPIRequestContext obapiRequestContext; - @Mock - OBAPIResponseContext obapiResponseContext; - @Mock - APIRequestInfoDTO apiRequestInfoDTO; - @Mock - MsgInfoDTO msgInfoDTO; - @Mock - PayloadHandler payloadHandler; - Map headers = new HashMap<>(); - - private String kid = "1234"; - - private HashMap criticalParameters = new HashMap<>(); - - private String sampleResponsePayload = "{\n" + - " \"Data\": {\n" + - " \"Initiation\": {\n" + - " \"FileType\": \"UK.OBIE.pain.001.001.08\",\n" + - " \"FileHash\": \"sof6XBU7RAkxekFddW38uJ2h2TBknlgLLiRSCP7qVdw=\",\n" + - " \"FileReference\": \"test\"\n" + - " }\n" + - " }\n" + - "}"; - - private String sampleXmlResponsePayload = "\n" + - " \n" + - " \n" + - " ABC/120928/CCT001\n" + - " 2012-09-28T14:07:00\n" + - " 2\n" + - " 70\n" + - " \n" + - " ABC Corporation\n" + - " \n" + - " Times Square\n" + - " 7\n" + - " NY 10036\n" + - " New York\n" + - " US\n" + - " \n" + - " \n" + - " \n" + - ""; - - private String sampleJWS = "eyJodHRwOlwvXC9vcGVuYmFua2luZy5vwvaXNzIjoiMDAxNTgwMDAwMUhRUXFMyNTYifQ." + - "TQolWv8OZM90Wq6mqL2TZ_Sj6cQjefo5mCgWLP33qg5WH38oFh1YBaBQ7daAFALFIN6jMw." + - "hgdyyUcKNoX8bYZzdQvyYBIMkoyxI39rpYUyumxKQEFbNzysihO_f4js5k4L"; - - String requestHeaderb64False = "{\n" + - "\"alg\": \"PS256\",\n" + - "\"kid\": \"12345\",\n" + - "\"b64\": false, \n" + - "\"http://openbanking.org.uk/iat\": 1739485930,\n" + - "\"http://openbanking.org.uk/iss\": \"http://openbanking.org.uk\", \n" + - "\"crit\": [ \"b64\", \"http://openbanking.org.uk/iat\",\n" + - "\"http://openbanking.org.uk/iss\"] \n" + - "}"; - - String requestHedaerb64True = "{\n" + - "\"alg\": \"PS256\",\n" + - "\"kid\": \"12345\",\n" + - "\"b64\": true, \n" + - "\"http://openbanking.org.uk/iat\": 1739485930,\n" + - "\"http://openbanking.org.uk/iss\": \"http://openbanking.org.uk\", \n" + - "\"crit\": [ \"b64\", \"http://openbanking.org.uk/iat\",\n" + - "\"http://openbanking.org.uk/iss\"] \n" + - "}"; - - String requestHedaerb64None = "{\n" + - "\"alg\": \"PS256\",\n" + - "\"kid\": \"12345\",\n" + - "\"http://openbanking.org.uk/iat\": 1739485930,\n" + - "\"http://openbanking.org.uk/iss\": \"http://openbanking.org.uk\", \n" + - "\"crit\": [ \"http://openbanking.org.uk/iat\",\n" + - "\"http://openbanking.org.uk/iss\"] \n" + - "}"; - - @BeforeClass - public void initClass() { - - MockitoAnnotations.initMocks(this); - - jwsResponseSignatureHandlingExecutor = new JwsResponseSignatureHandlingExecutor(); - - obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - obapiResponseContext = Mockito.mock(OBAPIResponseContext.class); - apiRequestInfoDTO = Mockito.mock(APIRequestInfoDTO.class); - msgInfoDTO = Mockito.mock(MsgInfoDTO.class); - payloadHandler = Mockito.mock(PayloadHandler.class); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - /** - * Test the returned JWS Header with the input parameter. - */ - @Test - public void testJWSHeader() { - - criticalParameters.put("iss", "issuer"); - criticalParameters.put("iat", 123456); - criticalParameters.put("tan", "trustAnchor"); - JWSHeader jwsHeader = GatewaySignatureHandlingUtils.constructJWSHeader(kid, criticalParameters, - JWSAlgorithm.parse("ES256")); - Assert.assertTrue("ES256".equals(jwsHeader.getAlgorithm().getName())); - } - - /** - * Test make JWSObject. - */ - @Test - public void testConstructJWSObject() { - - criticalParameters.put("iss", "issuer"); - criticalParameters.put("iat", 123456); - criticalParameters.put("tan", "trustAnchor"); - JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.parse("EC")) - .keyID(kid) - .type(JOSEObjectType.JOSE) - .criticalParams(criticalParameters.keySet()) - .customParams(criticalParameters) - .build(); - - JWSObject jwsObject = GatewaySignatureHandlingUtils.constructJWSObject(jwsHeader, sampleResponsePayload); - - Assert.assertTrue("EC".equals(jwsObject.getHeader().getAlgorithm().getName())); - } - - /** - * Test input to sign when b64 claim set to true. - */ - @Test - public void getSigningInput() throws UnsupportedEncodingException { - - criticalParameters.put("iss", "issuer"); - criticalParameters.put("iat", 123456); - criticalParameters.put("tan", "trustAnchor"); - criticalParameters.put("b64", true); - JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.parse("EC")) - .keyID(kid) - .type(JOSEObjectType.JOSE) - .criticalParams(criticalParameters.keySet()) - .customParams(criticalParameters) - .build(); - Object signingInput = GatewaySignatureHandlingUtils.getSigningInput(jwsHeader, sampleResponsePayload); - Assert.assertNotNull(signingInput); - } - - /** - * Test a header with b64 claim set to true. - */ - @Test - public void testHeaderWithB64True() throws ParseException { - - JWSHeader header = JWSHeader.parse(requestHedaerb64True); - JWSObject jwsObject = new JWSObject(header, new Payload(sampleResponsePayload)); - boolean isB64Verifiable = GatewaySignatureHandlingUtils.isB64HeaderVerifiable(jwsObject); - - Assert.assertTrue(isB64Verifiable); - } - - /** - * Test a header with b64 claim not set. - */ - @Test - public void testHeaderWithB64NotSet() throws ParseException { - - JWSHeader header = JWSHeader.parse(requestHedaerb64None); - JWSObject jwsObject = new JWSObject(header, new Payload(sampleResponsePayload)); - boolean isB64Verifiable = GatewaySignatureHandlingUtils.isB64HeaderVerifiable(jwsObject); - - Assert.assertTrue(isB64Verifiable); - } - - /** - * Test a header with b64 claim set to false. - */ - @Test - public void testHeaderWithB64False() throws ParseException { - - JWSHeader header = JWSHeader.parse(requestHeaderb64False); - JWSObject jwsObject = new JWSObject(header, new Payload(sampleResponsePayload)); - boolean isB64Verifiable = GatewaySignatureHandlingUtils.isB64HeaderVerifiable(jwsObject); - - - Assert.assertFalse(isB64Verifiable); - } - - /** - * Test creating a detached JWS with serialized JWS. - */ - @Test - public void testDetachedJWS() throws ParseException { - - JWSHeader header = JWSHeader.parse(requestHeaderb64False); - Base64URL signature = Base64URL.encode("signature"); - String detachedJWS = GatewaySignatureHandlingUtils.createDetachedJws(header, signature); - String[] jwsParts = detachedJWS.split("\\."); - - Assert.assertEquals("", jwsParts[1]); - } - - @Test - public void testExtractRequestPayloadForJsonPayloads() throws OpenBankingException { - - headers.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - Mockito.doReturn(sampleResponsePayload).when(obapiRequestContext).getRequestPayload(); - - Optional payload = GatewayUtils.extractRequestPayload(obapiRequestContext, headers); - Assert.assertNotNull(payload.get()); - } - - @Test - public void testExtractResponsePayloadForJsonPayloads() throws OpenBankingException { - - headers.put(GatewayConstants.CONTENT_TYPE_TAG, GatewayConstants.JSON_CONTENT_TYPE); - Mockito.doReturn(sampleResponsePayload).when(obapiResponseContext).getResponsePayload(); - - Optional payload = GatewayUtils.extractResponsePayload(obapiResponseContext, headers); - Assert.assertNotNull(payload.get()); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/CRLValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/CRLValidatorTest.java deleted file mode 100644 index e3d62725..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/CRLValidatorTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.revocation; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.executor.util.TestValidationUtil; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.apache.commons.io.FileUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.nio.charset.StandardCharsets; -import java.security.PublicKey; -import java.security.cert.CRLException; -import java.security.cert.CertificateException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; - -/** - * Test for CRL validator. - */ -@PrepareForTest({TPPCertValidatorDataHolder.class, HTTPClientUtils.class, CertificateValidationUtils.class}) -@PowerMockIgnore({"javax.security.auth.x500.*", "jdk.internal.reflect.*"}) -public class CRLValidatorTest extends PowerMockTestCase { - - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - - private CRLValidator crlValidator; - private X509Certificate eidasPeerCertificate; - private X509Certificate eidasPeerCertificateIssuer; - private X509Certificate expiredPeerCertificate; - - @BeforeClass - public void initClass() throws CertificateValidationException, CertificateException, OpenBankingException { - this.eidasPeerCertificate = TestValidationUtil.getTestEidasCertificate(); - this.eidasPeerCertificateIssuer = TestValidationUtil.getTestEidasCertificateIssuer(); - this.expiredPeerCertificate = TestValidationUtil.getExpiredSelfCertificate(); - this.crlValidator = new CRLValidator(3); - } - - @BeforeMethod - public void initMethods() throws IOException, OpenBankingException { - StatusLine statusLineMock = Mockito.mock(StatusLine.class); - Mockito.doReturn(HttpStatus.SC_OK).when(statusLineMock).getStatusCode(); - - File file = new File(absolutePathForTestResources + "/test_crl_entries.pem"); - byte[] crlBytes = FileUtils.readFileToString(file, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8); - InputStream inStream = new ByteArrayInputStream(crlBytes); - - HttpEntity httpEntityMock = Mockito.mock(HttpEntity.class); - Mockito.doReturn(inStream).when(httpEntityMock).getContent(); - - CloseableHttpResponse httpResponseMock = Mockito.mock(CloseableHttpResponse.class); - Mockito.doReturn(statusLineMock).when(httpResponseMock).getStatusLine(); - Mockito.doReturn(httpEntityMock).when(httpResponseMock).getEntity(); - - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doReturn(httpResponseMock).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - } - - @Test - public void testCRLValidatorConstructor() { - Assert.assertSame(new CRLValidator(3).getRetryCount(), 3); - } - - @Test(description = "when valid certificate provided, then X509URL should not be null") - public void testDownloadCRLFromWeb() throws Exception { - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - // Date needs to be an old date than X509 next update date - Date dateMock = new SimpleDateFormat("dd/MM/yyyy").parse("17/03/2021"); - PowerMockito.mockStatic(CertificateValidationUtils.class); - PowerMockito.when(CertificateValidationUtils.getNewDate()).thenReturn(dateMock); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - - } - - @Test(description = "when valid proxy provided, then X509URL should not be null") - public void testDownloadCRLFromWebWithProxy() throws Exception { - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - Mockito.doReturn(true).when(tppCertValidatorDataHolder).isCertificateRevocationProxyEnabled(); - Mockito.doReturn("localhost").when(tppCertValidatorDataHolder).getCertificateRevocationProxyHost(); - Mockito.doReturn(8080).when(tppCertValidatorDataHolder).getCertificateRevocationProxyPort(); - - // Date needs to be an old date than X509 next update date - Date dateMock = new SimpleDateFormat("dd/MM/yyyy").parse("17/03/2021"); - PowerMockito.mockStatic(CertificateValidationUtils.class); - PowerMockito.when(CertificateValidationUtils.getNewDate()).thenReturn(dateMock); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid proxy host provided, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testDownloadCRLFromWebWithInvalidProxy() throws CertificateValidationException { - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - Mockito.doReturn(true).when(tppCertValidatorDataHolder).isCertificateRevocationProxyEnabled(); - Mockito.doReturn(" ").when(tppCertValidatorDataHolder).getCertificateRevocationProxyHost(); - Mockito.doReturn(8080).when(tppCertValidatorDataHolder).getCertificateRevocationProxyPort(); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid http response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testDownloadCRLFromWebWithInvalidHTTPResponse() throws CertificateValidationException, IOException, - OpenBankingException { - StatusLine statusLineMock = Mockito.mock(StatusLine.class); - Mockito.doReturn(HttpStatus.SC_BAD_REQUEST).when(statusLineMock).getStatusCode(); - - CloseableHttpResponse httpResponseMock = Mockito.mock(CloseableHttpResponse.class); - Mockito.doReturn(statusLineMock).when(httpResponseMock).getStatusLine(); - - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doReturn(httpResponseMock).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid http response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testDownloadCRLFromWebWhenThrowingIOException() throws Exception { - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doThrow(IOException.class).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid http response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testDownloadCRLFromWebWhenThrowingCertificateException() throws Exception { - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doThrow(CertificateException.class).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid http response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testDownloadCRLFromWebWhenThrowingCRLException() throws Exception { - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doThrow(CRLException.class).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid http response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testDownloadCRLFromWebWhenThrowingMalformedURLException() throws Exception { - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - Mockito.doThrow(MalformedURLException.class).when(closeableHttpClientMock).execute(Mockito.any(HttpGet.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - TPPCertValidatorDataHolder tppCertValidatorDataHolder = Mockito.mock(TPPCertValidatorDataHolder.class); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - Assert.assertNotNull(this.crlValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer)); - } - - @Test(description = "when invalid X509URL, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testIsValidX509CRLFromIssuer() throws Exception { - X509CRL x509CRLMock = Mockito.mock(X509CRL.class); - WhiteboxImpl.invokeMethod(this.crlValidator, "isValidX509Crl", x509CRLMock, - eidasPeerCertificate, eidasPeerCertificateIssuer); - } - - @Test(description = "when X509URL next update date is invalid, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testIsValidX509CRLFromNextUpdate() throws Exception { - X509CRL x509CRLMock = Mockito.mock(X509CRL.class); - final Date today = new Date(); - final Date yesterday = new Date(today.getTime() - (1000 * 60 * 60 * 24)); - Mockito.doReturn(yesterday).when(x509CRLMock).getNextUpdate(); - - WhiteboxImpl.invokeMethod(this.crlValidator, "isValidX509CRLFromNextUpdate", x509CRLMock, - today, today); - } - - @Test(description = "when X509URL next update date is null, then return false") - public void testIsValidX509CRLFromNextUpdateWithNullDate() throws Exception { - X509CRL x509CRLMock = Mockito.mock(X509CRL.class); - boolean result = WhiteboxImpl.invokeMethod(this.crlValidator, - "isValidX509CRLFromNextUpdate", x509CRLMock, null, null); - - Assert.assertFalse(result); - } - - @Test(description = "when X509URL verification failed, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testIsValidX509CRLFromIssuerWithFailedVerification() throws Exception { - X509CRL x509CRLMock = Mockito.mock(X509CRL.class); - Mockito.doReturn(eidasPeerCertificate.getIssuerDN()).when(x509CRLMock).getIssuerDN(); - Mockito.doThrow(CRLException.class).when(x509CRLMock).verify(Mockito.any(PublicKey.class)); - - WhiteboxImpl.invokeMethod(this.crlValidator, "isValidX509CRLFromIssuer", x509CRLMock, - eidasPeerCertificate, eidasPeerCertificateIssuer); - } - - @Test(description = "when CRL URL list is empty, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testGetCRLRevocationStatusWithEmptyCRLUrls() throws CertificateValidationException { - CRLValidator.getCRLRevocationStatus(null, null, 0, Collections.emptyList(), false, "", 0); - } - - @Test(description = "when invalid cert provided, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testGetCRLUrlsWithInvalidCert() throws CertificateValidationException { - CRLValidator.getCRLUrls(expiredPeerCertificate); - } - - @Test(description = "when certificate is revoked, then return revoked revocation status") - public void testGetRevocationStatusFromCRLWithRevokedCert() throws Exception { - X509CRL x509CRLMock = Mockito.mock(X509CRL.class); - Mockito.doReturn(true).when(x509CRLMock).isRevoked(eidasPeerCertificate); - - RevocationStatus actual = WhiteboxImpl.invokeMethod(this.crlValidator, "getRevocationStatusFromCRL", - x509CRLMock, eidasPeerCertificate); - - Assert.assertSame(actual, RevocationStatus.REVOKED); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/OCSPValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/OCSPValidatorTest.java deleted file mode 100644 index 21d5a7f7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/revocation/OCSPValidatorTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.revocation; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; -import com.wso2.openbanking.accelerator.gateway.executor.util.CertificateValidationUtils; -import com.wso2.openbanking.accelerator.gateway.executor.util.TestValidationUtil; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.bouncycastle.cert.ocsp.CertificateStatus; -import org.bouncycastle.cert.ocsp.OCSPReq; -import org.bouncycastle.cert.ocsp.RevokedStatus; -import org.bouncycastle.cert.ocsp.SingleResp; -import org.bouncycastle.cert.ocsp.UnknownStatus; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.List; - -/** - * Test for OCSP validator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({TPPCertValidatorDataHolder.class, HTTPClientUtils.class}) -public class OCSPValidatorTest extends PowerMockTestCase { - - @Mock - TPPCertValidatorDataHolder tppCertValidatorDataHolder; - OCSPValidator ocspValidator; - - private X509Certificate testPeerCertificateIssuer; - private X509Certificate eidasPeerCertificate; - private X509Certificate eidasPeerCertificateIssuer; - private X509Certificate expiredPeerCertificate; - - @BeforeClass - public void init() throws CertificateValidationException, CertificateException, OpenBankingException { - MockitoAnnotations.initMocks(this); - this.ocspValidator = new OCSPValidator(1); - this.testPeerCertificateIssuer = TestValidationUtil.getTestClientCertificateIssuer(); - this.eidasPeerCertificate = TestValidationUtil.getTestEidasCertificate(); - this.eidasPeerCertificateIssuer = TestValidationUtil.getTestEidasCertificateIssuer(); - this.expiredPeerCertificate = TestValidationUtil.getExpiredSelfCertificate(); - } - - @Test(description = "when valid certificate provided, then list of crl urls should return") - public void testGetAIALocationsWithValidCert() throws CertificateValidationException { - List crlUrls = OCSPValidator.getAIALocations(eidasPeerCertificate); - Assert.assertFalse(crlUrls.isEmpty()); - } - - @Test(description = "when invalid certificate provided, then CertificateValidationException should throw", - expectedExceptions = CertificateValidationException.class) - public void testGetAIALocationsWithInvalidCert() throws CertificateValidationException { - OCSPValidator.getAIALocations(expiredPeerCertificate); - } - - @Test(description = "when valid certificate provided, then OCSP object should return") - public void testGenerateOCSPRequestWithValidCert() throws Exception { - OCSPReq ocspRequest = WhiteboxImpl.invokeMethod(this.ocspValidator, - "generateOCSPRequest", testPeerCertificateIssuer, expiredPeerCertificate.getSerialNumber()); - Assert.assertNotNull(ocspRequest); - } - - @Test - public void testSetRequestProperties() throws Exception { - byte[] bytes = "test msg".getBytes(StandardCharsets.UTF_8); - HttpPost httpPost = new HttpPost(); - - WhiteboxImpl.invokeMethod(this.ocspValidator, - "setRequestProperties", bytes, httpPost); - - Assert.assertTrue(httpPost.containsHeader(CertificateValidationUtils.HTTP_CONTENT_TYPE)); - Assert.assertTrue(httpPost.containsHeader(CertificateValidationUtils.HTTP_ACCEPT)); - Assert.assertEquals(httpPost.getEntity().getContentType().getValue(), CertificateValidationUtils.CONTENT_TYPE); - } - - @Test(description = "when invalid proxy provided, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testCheckRevocationStatusWithInvalidProxy() throws Exception { - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - Mockito.when(tppCertValidatorDataHolder.isCertificateRevocationProxyEnabled()).thenReturn(true); - Mockito.when(tppCertValidatorDataHolder.getCertificateRevocationProxyHost()).thenReturn(" "); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - this.ocspValidator - .checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer); - } - - @Test(description = "when issuer cert is null, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testCheckRevocationStatusWithNullCerts() throws CertificateValidationException { - this.ocspValidator.checkRevocationStatus(null, null); - } - - @Test(description = "when invalid response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testCheckRevocationStatusWithInvalidResponse() throws CertificateValidationException, IOException, - OpenBankingException { - StatusLine statusLineMock = Mockito.mock(StatusLine.class); - Mockito.doReturn(HttpStatus.SC_BAD_REQUEST).when(statusLineMock).getStatusCode(); - - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - CloseableHttpResponse httpResponseMock = Mockito.mock(CloseableHttpResponse.class); - Mockito.doReturn(statusLineMock).when(httpResponseMock).getStatusLine(); - - Mockito.doReturn(httpResponseMock).when(closeableHttpClientMock).execute(Mockito.any(HttpPost.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - Mockito.doReturn(true).when(tppCertValidatorDataHolder).isCertificateRevocationProxyEnabled(); - Mockito.doReturn("localhost").when(tppCertValidatorDataHolder).getCertificateRevocationProxyHost(); - Mockito.doReturn(8080).when(tppCertValidatorDataHolder).getCertificateRevocationProxyPort(); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolder); - - this.ocspValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer); - } - - @Test(description = "when invalid response received, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testCheckRevocationStatusWhenThrowingIOException() throws CertificateValidationException, IOException, - OpenBankingException { - CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); - - Mockito.doThrow(IOException.class).when(closeableHttpClientMock).execute(Mockito.any(HttpPost.class)); - - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClientMock); - - TPPCertValidatorDataHolder tppCertValidatorDataHolderMock = Mockito.mock(TPPCertValidatorDataHolder.class); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()).thenReturn(tppCertValidatorDataHolderMock); - - this.ocspValidator.checkRevocationStatus(eidasPeerCertificate, eidasPeerCertificateIssuer); - } - - @Test - public void testOCSPValidatorConstructor() { - Assert.assertSame(new OCSPValidator(3).getRetryCount(), 3); - } - - - @Test(description = "when certificate is good, then return good revocation status") - public void testGetRevocationStatusFromOCSGood() throws Exception { - SingleResp singleRespMock = Mockito.mock(SingleResp.class); - Mockito.doReturn(CertificateStatus.GOOD).when(singleRespMock).getCertStatus(); - - RevocationStatus revocationStatus = WhiteboxImpl.invokeMethod(this.ocspValidator, - "getRevocationStatusFromOCSP", singleRespMock); - - Assert.assertSame(revocationStatus, RevocationStatus.GOOD); - } - - @Test(description = "when certificate is revoked, then return revoked revocation status") - public void testGetRevocationStatusFromOCSRevoked() throws Exception { - SingleResp singleRespMock = Mockito.mock(SingleResp.class); - RevokedStatus revokedStatusMock = Mockito.mock(RevokedStatus.class); - Mockito.doReturn(revokedStatusMock).when(singleRespMock).getCertStatus(); - - RevocationStatus revocationStatus = WhiteboxImpl.invokeMethod(this.ocspValidator, - "getRevocationStatusFromOCSP", singleRespMock); - - Assert.assertSame(revocationStatus, RevocationStatus.REVOKED); - } - - @Test(description = "when certificate status is unknown, then return unknown revocation status") - public void testGetRevocationStatusFromOCSUnknown() throws Exception { - SingleResp singleRespMock = Mockito.mock(SingleResp.class); - UnknownStatus unknownStatusMock = Mockito.mock(UnknownStatus.class); - Mockito.doReturn(unknownStatusMock).when(singleRespMock).getCertStatus(); - - RevocationStatus revocationStatus = WhiteboxImpl.invokeMethod(this.ocspValidator, - "getRevocationStatusFromOCSP", singleRespMock); - - Assert.assertSame(revocationStatus, RevocationStatus.UNKNOWN); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/service/CertValidationServiceTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/service/CertValidationServiceTest.java deleted file mode 100644 index dfe30851..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/service/CertValidationServiceTest.java +++ /dev/null @@ -1,351 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.service; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCache; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.exception.TPPValidationException; -import com.wso2.openbanking.accelerator.common.model.PSD2RoleEnum; -import com.wso2.openbanking.accelerator.gateway.cache.GatewayCacheKey; -import com.wso2.openbanking.accelerator.gateway.cache.TppValidationCache; -import com.wso2.openbanking.accelerator.gateway.executor.model.RevocationStatus; -import com.wso2.openbanking.accelerator.gateway.executor.revocation.OCSPValidator; -import com.wso2.openbanking.accelerator.gateway.executor.util.TestValidationUtil; -import com.wso2.openbanking.accelerator.gateway.internal.TPPCertValidatorDataHolder; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.reflect.internal.WhiteboxImpl; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Test for certificate validation service. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class, OCSPValidator.class, TPPCertValidatorDataHolder.class, - TppValidationCache.class}) -public class CertValidationServiceTest { - - @Mock - OpenBankingConfigParser openBankingConfigParser; - @Mock - TPPCertValidatorDataHolder tppCertValidatorDataHolder; - @Mock - TppValidationCache tppValidationCache; - CertValidationService certValidationService; - private X509Certificate testPeerCertificate; - private X509Certificate testPeerCertificateIssuer; - private X509Certificate eidasPeerCertificate; - - @BeforeClass - public void init() throws CertificateValidationException, CertificateException, OpenBankingException { - MockitoAnnotations.initMocks(this); - certValidationService = CertValidationService.getInstance(); - this.testPeerCertificate = TestValidationUtil.getTestClientCertificate(); - this.testPeerCertificateIssuer = TestValidationUtil.getTestClientCertificateIssuer(); - this.eidasPeerCertificate = TestValidationUtil.getTestEidasCertificate(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test(description = "when valid certificate provided, then should return true") - public void testVerifyWithValidCertificate() throws Exception { - Map validators = new HashMap<>(); - validators.put(1, "OCSP"); - - Mockito.when(openBankingConfigParser.getCertificateRevocationValidators()).thenReturn(validators); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - PowerMockito.mockStatic(OCSPValidator.class); - PowerMockito.when(OCSPValidator.getOCSPRevocationStatus(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class), Mockito.anyInt(), Mockito.anyListOf(String.class), - Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyInt())) - .thenReturn(RevocationStatus.GOOD); - - boolean isVerified = this.certValidationService - .verify(testPeerCertificate, testPeerCertificateIssuer, 1); - Assert.assertTrue(isVerified); - } - - @Test(description = "when valid certificate provided, then should return true") - public void testUpdatedVerifyWithValidCertificate() throws Exception { - Map validators = new HashMap<>(); - validators.put(1, "OCSP"); - - Mockito.when(openBankingConfigParser.getCertificateRevocationValidators()).thenReturn(validators); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - PowerMockito.mockStatic(OCSPValidator.class); - PowerMockito.when(OCSPValidator.getOCSPRevocationStatus(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class), Mockito.anyInt(), Mockito.anyListOf(String.class), - Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyInt())) - .thenReturn(RevocationStatus.GOOD); - - boolean isVerified = this.certValidationService - .verify(testPeerCertificate, testPeerCertificateIssuer, 1, 5000, - 5000, 5000); - Assert.assertTrue(isVerified); - } - - @Test(description = "when invalid certificate provided, then should return false") - public void testVerifyWithValidInvalidCertificate() throws Exception { - Map validators = new HashMap<>(); - validators.put(1, "OCSP"); - - Mockito.when(openBankingConfigParser.getCertificateRevocationValidators()).thenReturn(validators); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - PowerMockito.mockStatic(OCSPValidator.class); - PowerMockito.when(OCSPValidator.getOCSPRevocationStatus(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class), Mockito.anyInt(), Mockito.anyListOf(String.class), - Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyInt())) - .thenReturn(RevocationStatus.REVOKED); - - boolean isVerified = this.certValidationService - .verify(testPeerCertificate, testPeerCertificateIssuer, 1); - Assert.assertFalse(isVerified); - - boolean isVerifiedUpdated = this.certValidationService - .verify(testPeerCertificate, testPeerCertificateIssuer, 1, - 5000, 5000, 5000); - Assert.assertFalse(isVerifiedUpdated); - } - - @Test(description = "when invalid validator configured, then should return false") - public void testVerifyWithInvalidValidator() throws Exception { - Map validators = new HashMap<>(); - validators.put(1, "INVALID VALIDATOR"); - - Mockito.when(openBankingConfigParser.getCertificateRevocationValidators()).thenReturn(validators); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - boolean isVerified = this.certValidationService - .verify(testPeerCertificate, testPeerCertificateIssuer, 1); - Assert.assertFalse(isVerified); - - boolean isVerifiedUpdated = this.certValidationService - .verify(testPeerCertificate, testPeerCertificateIssuer, 1, - 5000, 5000, 5000); - Assert.assertFalse(isVerifiedUpdated); - } - - @Test(description = "when cert roles and scope roles are equal, then return true") - public void testIsRequiredRolesMatchWithValidScopes() throws Exception { - boolean isValid = WhiteboxImpl.invokeMethod(this.certValidationService, - "isRequiredRolesMatchWithScopes", eidasPeerCertificate, - Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP)); - - Assert.assertTrue(isValid); - } - - @Test(description = "when cert roles and scope roles are not equal, then throw TPPValidationException", - expectedExceptions = {TPPValidationException.class}) - public void testIsRequiredRolesMatchWithInvalidScopes() throws Exception { - WhiteboxImpl.invokeMethod(this.certValidationService, - "isRequiredRolesMatchWithScopes", eidasPeerCertificate, - Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP, PSD2RoleEnum.ASPSP)); - } - - @Test(description = "When tpp certificate and roles are valid, then should return true") - public void testValidateTPPWithValidRoles() throws TPPValidationException, - CertificateValidationException, OpenBankingException { - Mockito.when(tppCertValidatorDataHolder.isTppValidationEnabled()).thenReturn(true); - Mockito.when(tppCertValidatorDataHolder.getTPPValidationServiceImpl()).thenReturn("/dummy/path"); - - TPPValidationService mockTppValidationService = Mockito.mock(TPPValidationService.class); - Mockito.when(mockTppValidationService.getCacheKey(Mockito.any(X509Certificate.class), - Mockito.anyListOf(PSD2RoleEnum.class), Mockito.anyMapOf(String.class, Object.class))) - .thenReturn("dummy-cache-key"); - Mockito.when(mockTppValidationService.validate(Mockito.any(X509Certificate.class), - Mockito.anyListOf(PSD2RoleEnum.class), Mockito.anyMapOf(String.class, Object.class))).thenReturn(true); - - Mockito.when(tppCertValidatorDataHolder.getTppValidationService()).thenReturn(mockTppValidationService); - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - PowerMockito.mockStatic(TppValidationCache.class); - PowerMockito.when(TppValidationCache.getInstance()) - .thenReturn(tppValidationCache); - - Assert.assertTrue(certValidationService.validateTppRoles(eidasPeerCertificate, - Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP))); - } - - @Test(description = "When role is failing, then should return false ") - public void testValidateTPPWithValidationError() throws TPPValidationException, - CertificateValidationException, OpenBankingException { - Mockito.when(tppCertValidatorDataHolder.isTppValidationEnabled()).thenReturn(true); - Mockito.when(tppCertValidatorDataHolder.getTPPValidationServiceImpl()).thenReturn("/dummy/path"); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - TPPValidationService mockTppValidationService = Mockito.mock(TPPValidationService.class); - Mockito.when(mockTppValidationService.getCacheKey(Mockito.any(X509Certificate.class), - Mockito.anyListOf(PSD2RoleEnum.class), Mockito.anyMapOf(String.class, Object.class))) - .thenReturn("dummy-cache-key"); - - Mockito.when(tppCertValidatorDataHolder.getTppValidationService()).thenReturn(mockTppValidationService); - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - Mockito.when(tppValidationCache.getFromCacheOrRetrieve(Mockito.any(GatewayCacheKey.class), - Mockito.any(OpenBankingBaseCache.OnDemandRetriever.class))).thenThrow(OpenBankingException.class); - PowerMockito.mockStatic(TppValidationCache.class); - PowerMockito.when(TppValidationCache.getInstance()) - .thenReturn(tppValidationCache); - - Assert.assertFalse(certValidationService.validateTppRoles(eidasPeerCertificate, - Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP))); - } - - @Test(description = "When TPPValidationImpl path configuration is empty, then should throw TPPValidationException", - expectedExceptions = {TPPValidationException.class}) - public void testValidateTPPWithEmptyImplConfig() throws TPPValidationException, CertificateValidationException { - Mockito.when(tppCertValidatorDataHolder.isTppValidationEnabled()).thenReturn(true); - Mockito.when(tppCertValidatorDataHolder.getTPPValidationServiceImpl()).thenReturn(""); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - Assert.assertFalse(certValidationService - .validateTppRoles(eidasPeerCertificate, Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP))); - } - - @Test(description = "When TPPValidationImpl path configuration is invalid, then throw TPPValidationException", - expectedExceptions = {TPPValidationException.class}) - public void testValidateTPPWithInvalidImplConfig() throws TPPValidationException, CertificateValidationException { - Mockito.when(tppCertValidatorDataHolder.isTppValidationEnabled()).thenReturn(true); - Mockito.when(tppCertValidatorDataHolder.getTPPValidationServiceImpl()).thenReturn("dummy-path"); - Mockito.when(tppCertValidatorDataHolder.getTppValidationService()).thenReturn(null); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - Assert.assertFalse(certValidationService - .validateTppRoles(eidasPeerCertificate, Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP))); - } - - @Test(description = "When tpp certificate and roles are valid, then should return true") - public void testValidateTPPWithCustomRoleValidation() - throws TPPValidationException, CertificateValidationException { - Mockito.when(tppCertValidatorDataHolder.isTppValidationEnabled()).thenReturn(false); - Mockito.when(tppCertValidatorDataHolder.isPsd2RoleValidationEnabled()).thenReturn(true); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - Assert.assertTrue(certValidationService - .validateTppRoles(eidasPeerCertificate, Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP))); - } - - @Test(description = "When both tppValidationEnabled and psd2RoleValidationEnabled are false, " + - "then should throw TPPValidationException", expectedExceptions = TPPValidationException.class) - public void testValidateTPPWithInvalidConfigs() throws TPPValidationException, CertificateValidationException { - Mockito.when(tppCertValidatorDataHolder.isTppValidationEnabled()).thenReturn(false); - Mockito.when(tppCertValidatorDataHolder.isPsd2RoleValidationEnabled()).thenReturn(false); - - PowerMockito.mockStatic(TPPCertValidatorDataHolder.class); - PowerMockito.when(TPPCertValidatorDataHolder.getInstance()) - .thenReturn(tppCertValidatorDataHolder); - - Assert.assertTrue(certValidationService - .validateTppRoles(eidasPeerCertificate, Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP))); - } - - @Test(description = "when valid certificate and roles provided, then return true") - public void testIsRequiredRolesMatchWithScopes() throws Exception { - List requiredPSD2Roles = Arrays.asList(PSD2RoleEnum.AISP, PSD2RoleEnum.PISP); - - boolean isValid = WhiteboxImpl.invokeMethod(this.certValidationService, - "isRequiredRolesMatchWithScopes", eidasPeerCertificate, requiredPSD2Roles); - - Assert.assertTrue(isValid); - } - - @Test(description = "when invalid certificate and roles provided, then throw TPPValidationException", - expectedExceptions = {TPPValidationException.class}) - public void testIsRequiredRolesMatchWithScopesWithInvalidRoles() throws Exception { - WhiteboxImpl.invokeMethod(this.certValidationService, - "isRequiredRolesMatchWithScopes", eidasPeerCertificate, Collections.singletonList(PSD2RoleEnum.ASPSP)); - } - - @Test(description = "when valid certificate provided, then should return GOOD revocation status") - public void testIsRevokedWithValidCert() throws Exception { - OCSPValidator mockOCSPValidator = Mockito.mock(OCSPValidator.class); - Mockito.when(mockOCSPValidator.checkRevocationStatus(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class))).thenReturn(RevocationStatus.GOOD); - - RevocationStatus result = WhiteboxImpl.invokeMethod(this.certValidationService, - "isRevoked", mockOCSPValidator, eidasPeerCertificate, testPeerCertificateIssuer); - - Assert.assertSame(result, RevocationStatus.GOOD); - } - - @Test(description = "when valid certificate provided, then should return UNKNOWN revocation status") - public void testIsRevokedWithInvalidCert() throws Exception { - OCSPValidator mockOCSPValidator = Mockito.mock(OCSPValidator.class); - Mockito.when(mockOCSPValidator.checkRevocationStatus(Mockito.any(X509Certificate.class), - Mockito.any(X509Certificate.class))).thenThrow(CertificateValidationException.class); - - RevocationStatus result = WhiteboxImpl.invokeMethod(this.certValidationService, - "isRevoked", mockOCSPValidator, eidasPeerCertificate, testPeerCertificateIssuer); - - Assert.assertSame(result, RevocationStatus.UNKNOWN); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/service/RevocationValidatorFactoryTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/service/RevocationValidatorFactoryTest.java deleted file mode 100644 index bb429dc1..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/service/RevocationValidatorFactoryTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.service; - -import com.wso2.openbanking.accelerator.gateway.executor.revocation.CRLValidator; -import com.wso2.openbanking.accelerator.gateway.executor.revocation.OCSPValidator; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -/** - * Test for revocation validation service. - */ -public class RevocationValidatorFactoryTest { - - private RevocationValidatorFactory revocationValidatorFactory; - - @BeforeClass - public void init() { - this.revocationValidatorFactory = new RevocationValidatorFactory(); - } - - @Test(description = "when valid revocation validator, then return valid validator object") - public void testGetValidatorWithValidStr() { - Assert.assertTrue(revocationValidatorFactory - .getValidator("OCSP", 1) instanceof OCSPValidator); - Assert.assertTrue(revocationValidatorFactory - .getValidator("CRL", 1) instanceof CRLValidator); - } - - @Test(description = "when invalid revocation validator, then return null") - public void testGetValidatorWithInvalidStr() { - Assert.assertNull(revocationValidatorFactory - .getValidator("INVALID", 1)); - } - - @Test(description = "when valid revocation validator, then return valid validator object") - public void testUpdatedGetValidatorWithValidStr() { - Assert.assertTrue(revocationValidatorFactory - .getValidator("OCSP", 1, 5000, 5000, 5000) instanceof OCSPValidator); - Assert.assertTrue(revocationValidatorFactory - .getValidator("CRL", 1, 5000, 5000, 5000) instanceof CRLValidator); - } - - @Test(description = "when invalid revocation validator, then return null") - public void testUpdatedGetValidatorWithInvalidStr() { - Assert.assertNull(revocationValidatorFactory - .getValidator("INVALID", 1, 5000, 5000, 5000)); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/TestConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/TestConstants.java deleted file mode 100644 index 34dc3767..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/TestConstants.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.test; - -import java.util.AbstractMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Constants for testing. - */ -public class TestConstants { - - public static final String INVALID_EXECUTOR_CLASS = - "com.wso2.openbanking.accelerator.gateway.executor.test.executor.InvalidClass"; - public static final String VALID_EXECUTOR_CLASS = - "com.wso2.openbanking.accelerator.gateway.executor.test.executor.MockOBExecutor"; - - public static final Map VALID_EXECUTOR_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>(1, VALID_EXECUTOR_CLASS)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - public static final Map INVALID_EXECUTOR_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>(1, INVALID_EXECUTOR_CLASS)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - public static final String CUSTOM_PAYLOAD = "{\"custom\":\"payload\"}"; - public static final Map> FULL_VALIDATOR_MAP = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("Default", VALID_EXECUTOR_MAP), - new AbstractMap.SimpleImmutableEntry<>("DCR", VALID_EXECUTOR_MAP)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - public static String authHeader = "eyJ4NXQiOiJNell4TW1Ga09HWXdNV0kwWldObU5EY3hOR1l3WW1NNFpUQ" + - "TNNV0kyTkRBelpHUXpOR00wWkdSbE5qSmtPREZrWkRSaU9URmtNV0ZoTXpVMlpHVmxOZyIsImtpZCI6Ik16" + - "WXhNbUZrT0dZd01XSTBaV05tTkRjeE5HWXdZbU00WlRBM01XSTJOREF6WkdRek5HTTBaR1JsTmpKa09ERmt" + - "aRFJpT1RGa01XRmhNelUyWkdWbE5nX1JTMjU2IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF" + - "1dCI6IkFQUExJQ0FUSU9OIiwiYXVkIjoiaENQUHFwbndTMWFKajd0Zkd6ckVVY3J0R2M0YSIsIm5iZiI6MT" + - "YxNDU5MDE4NSwiYXpwIjoiaENQUHFwbndTMWFKajd0Zkd6ckVVY3J0R2M0YSIsInNjb3BlIjoicmVhZDpwZ" + - "XRzIHdyaXRlOnBldHMiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0NDNcL29hdXRoMlwvdG9rZW4i" + - "LCJleHAiOjE2MTQ1OTM3ODUsImlhdCI6MTYxNDU5MDE4NSwianRpIjoiZGU3M2E3MzUtNmQzZi00MWI2LWE" + - "yYTYtN2U0ZTI1YWQxYTQxIn0.Jsz_0Wo79oBcVb2ibIVuJZ7pnsmIvU1r-RlFANiUYbjyTm8gF5b5CBf5uT" + - "JvKBM5BkqOSRbfgZdCMKZ7l83yZ5OSYDckwJ7rYKlcyzz50DKXlNW2-4J6d87uC1EOA10mg4pPC9LAH7Zdm" + - "MtN1JMY13xevKzoYB9FyuFgdLIHI4ALQOxeMAJZm_Y5_qBJgj1usE1FUmQUCdTc4aY3EbYkM9gZRO8Oc4HI" + - "7nn8eLwVShQqEdVDdtzsn0GJXLUlljxCfSAkVmP3vkxW1ZyC9OmmroONhdeEoJmy4Dr3JWwMNNNuzzFbT8K" + - "ycU1HwUqHTD5nL5Gs5jzSx8E-JxvdRotUCw"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/executor/MockOBExecutor.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/executor/MockOBExecutor.java deleted file mode 100644 index 7180e681..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/executor/MockOBExecutor.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.test.executor; - -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; - -/** - * Mock Open banking executor for testing. - */ -public class MockOBExecutor implements OpenBankingGatewayExecutor { - - @Override - public void preProcessRequest(OBAPIRequestContext obapiRequestContext) { - - obapiRequestContext.setModifiedPayload("{}"); - } - - @Override - public void preProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post response. - * - * @param obapiResponseContext OB response context object - */ - @Override - public void postProcessResponse(OBAPIResponseContext obapiResponseContext) { - - } - - /** - * Method to handle post request. - * - * @param obapiRequestContext OB request context object - */ - @Override - public void postProcessRequest(OBAPIRequestContext obapiRequestContext) { - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/executor/TestRouter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/executor/TestRouter.java deleted file mode 100644 index c46fe4c3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/executor/TestRouter.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.test.executor; - -import com.wso2.openbanking.accelerator.gateway.executor.core.AbstractRequestRouter; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIResponseContext; - -import java.util.List; - -/** - * Router for testing. - */ -public class TestRouter extends AbstractRequestRouter { - - @Override - public List getExecutorsForRequest(OBAPIRequestContext requestContext) { - - return super.getExecutorMap().get(requestContext.getMsgInfo().getHeaders().get("test-prop")); - } - - @Override - public List getExecutorsForResponse(OBAPIResponseContext requestContext) { - - return super.getExecutorMap().get("VALID"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/util/TestUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/util/TestUtil.java deleted file mode 100644 index 94e1016d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/test/util/TestUtil.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.test.util; - -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.gateway.executor.core.OpenBankingGatewayExecutor; -import com.wso2.openbanking.accelerator.gateway.executor.test.TestConstants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Util for testing. - */ -public class TestUtil { - - public static Map> initExecutors() { - - Map> executors = new HashMap<>(); - Map> fullValidatorMap = TestConstants.FULL_VALIDATOR_MAP; - for (Map.Entry> stringMapEntry : fullValidatorMap.entrySet()) { - List executorList = new ArrayList<>(); - Map executorNames = stringMapEntry.getValue(); - for (Map.Entry executorEntity : executorNames.entrySet()) { - OpenBankingGatewayExecutor object = (OpenBankingGatewayExecutor) - OpenBankingUtils.getClassInstanceFromFQN(executorEntity.getValue()); - executorList.add(object); - } - executors.put(stringMapEntry.getKey(), executorList); - } - return executors; - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/util/CertificateValidationUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/util/CertificateValidationUtilsTest.java deleted file mode 100644 index d171b6b9..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/util/CertificateValidationUtilsTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.util; - -import com.wso2.openbanking.accelerator.common.exception.CertificateValidationException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.gateway.executor.model.OBAPIRequestContext; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.io.File; -import java.io.IOException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Date; -import java.util.Optional; - -import javax.security.cert.CertificateEncodingException; - -/** - * Test for certificate validation utils. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest(KeyStore.class) -public class CertificateValidationUtilsTest extends PowerMockTestCase { - - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - - @Test(description = "when valid certificate, then return java.security.cert.X509Certificate") - public void testConvertWithValidCert() { - javax.security.cert.X509Certificate testCert = TestValidationUtil - .getCertFromStr(TestValidationUtil.TEST_CLIENT_CERT); - - Assert.assertNotNull(CertificateValidationUtils.convert(testCert)); - Assert.assertTrue(CertificateValidationUtils.convert(testCert).orElse(null) instanceof X509Certificate); - } - - @Test(description = "when null certificate, then return Optional empty") - public void testConvertWithNullCert() { - Assert.assertFalse(CertificateValidationUtils.convert(null) - .isPresent()); - } - - @Test(description = "when valid certificate, then return java.security.cert.X509Certificate") - public void testConvertCertWithValidCert() throws CertificateException { - javax.security.cert.X509Certificate testCert = TestValidationUtil - .getCertFromStr(TestValidationUtil.TEST_CLIENT_CERT); - - Assert.assertNotNull(CertificateValidationUtils.convertCert(testCert)); - Assert.assertTrue(CertificateValidationUtils.convertCert(testCert) - .orElse(null) instanceof X509Certificate); - } - - @Test(description = "when null certificate, then return Optional empty") - public void testConvertCertWithNullCert() throws CertificateException { - Assert.assertFalse(CertificateValidationUtils.convertCert(null) - .isPresent()); - } - - @Test(description = "when client store is null, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testGetIssuerCertificateFromNullTruststore() throws CertificateValidationException, - OpenBankingException { - - X509Certificate peerCertificate = CertificateUtils.parseCertificate(TestValidationUtil.TEST_CLIENT_CERT); - - X509Certificate issuerCertificate = CertificateValidationUtils - .getIssuerCertificateFromTruststore(peerCertificate); - - Assert.assertNotNull(issuerCertificate); - } - - @Test(description = "when valid peer certificate, then issuer certificate should return") - public void testGetIssuerCertificateFromTruststore() throws CertificateException, NoSuchAlgorithmException, - KeyStoreException, IOException, CertificateValidationException, OpenBankingException { - - X509Certificate peerCertificate = CertificateUtils.parseCertificate(TestValidationUtil.TEST_CLIENT_CERT); - - CertificateValidationUtils.loadTrustStore(absolutePathForTestResources + "/client-truststore.jks", - "wso2carbon".toCharArray()); - X509Certificate issuerCertificate = CertificateValidationUtils - .getIssuerCertificateFromTruststore(peerCertificate); - - Assert.assertNotNull(issuerCertificate); - Assert.assertEquals(issuerCertificate.getSubjectDN().getName(), peerCertificate.getIssuerDN().getName()); - } - - @Test(description = "when error occured, then should set error true in OBAPIRequestContext object") - public void testHandleExecutorErrors() { - OBAPIRequestContext obapiRequestContext = Mockito.mock(OBAPIRequestContext.class); - CertificateValidationException exception = new CertificateValidationException("dummy exception"); - - CertificateValidationUtils.handleExecutorErrors(exception, obapiRequestContext); - - Mockito.verify(obapiRequestContext, Mockito.times(1)).setError(true); - Mockito.verify(obapiRequestContext, Mockito.times(1)) - .setErrors(Mockito.any(ArrayList.class)); - } - - @Test(description = "should return current date") - public void testGetNewDate() { - Instant actual = CertificateValidationUtils.getNewDate().toInstant().truncatedTo(ChronoUnit.DAYS); - Instant expected = new Date().toInstant().truncatedTo(ChronoUnit.DAYS); - Assert.assertEquals(actual, expected); - } - - @Test(description = "when uninitialized keystore, then throw CertificateValidationException", - expectedExceptions = CertificateValidationException.class) - public void testRetrieveCertificateFromTruststore() throws KeyStoreException, CertificateValidationException { - PowerMockito.mockStatic(KeyStore.class); - KeyStore keyStoreMock = PowerMockito.mock(KeyStore.class); - - CertificateValidationUtils.retrieveCertificateFromTruststore(null, keyStoreMock); - } - - @Test(description = "when invalid encoded certificate, then return empty", - expectedExceptions = CertificateException.class) - public void testConvertWithInvalidCertEncoding() throws CertificateEncodingException, CertificateException { - javax.security.cert.X509Certificate x509CertificateMock = Mockito - .mock(javax.security.cert.X509Certificate.class); - Mockito.doThrow(CertificateEncodingException.class).when(x509CertificateMock).getEncoded(); - - Optional convertedCert = CertificateValidationUtils.convertCert(x509CertificateMock); - Assert.assertFalse(convertedCert.isPresent()); - } - - @Test(description = "when error occurred while converting, then return empty", - expectedExceptions = CertificateException.class) - public void testConvertWithInvalidCert() throws CertificateEncodingException, CertificateException { - javax.security.cert.X509Certificate x509CertificateMock = Mockito - .mock(javax.security.cert.X509Certificate.class); - Mockito.doThrow(CertificateException.class).when(x509CertificateMock).getEncoded(); - - Optional convertedCert = CertificateValidationUtils.convertCert(x509CertificateMock); - Assert.assertFalse(convertedCert.isPresent()); - } - - @Test(description = "when valid java.security.cert.Certificate is provided, " + - "then return java.security.cert.X509Certificate") - public void testConvertCertToX509CertWithValidCert() throws OpenBankingException, CertificateException { - Certificate testCert = TestValidationUtil.getTestClientCertificate(); - - Assert.assertTrue(CertificateValidationUtils.convertCertToX509Cert(testCert).isPresent()); - Assert.assertTrue(CertificateValidationUtils.convertCertToX509Cert(testCert).get() instanceof X509Certificate); - } - - @Test(expectedExceptions = CertificateException.class, description = "When an invalid certificate is provided, " + - "throw a CertificateException") - public void testConvertCertToX509CertException() throws CertificateException { - - CertificateValidationUtils.convertCertToX509Cert(TestValidationUtil.getEmptyTestCertificate()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/util/TestValidationUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/util/TestValidationUtil.java deleted file mode 100644 index cbc787ff..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/executor/util/TestValidationUtil.java +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.executor.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.util.Base64; - -import javax.security.cert.CertificateException; -import javax.security.cert.X509Certificate; - -/** - * Test for validation utils. - */ -public class TestValidationUtil { - - public static final String TEST_CLIENT_CERT = "-----BEGIN CERTIFICATE-----" + - "MIIFODCCBCCgAwIBAgIEWcZEPjANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJH" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNVBAMTJU9wZW5CYW5raW5nIFBy" + - "ZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwHhcNMjEwOTA4MDUyODEyWhcNMjIxMDA4" + - "MDU1ODEyWjBhMQswCQYDVQQGEwJHQjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxGzAZ" + - "BgNVBAsTEjAwMTU4MDAwMDFIUVFyWkFBWDEfMB0GA1UEAxMWdTNaV2xmOVl0NDJk" + - "eVpnSXZ6a3ZxYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALqlz2yg" + - "mP4yqmWfvSkus6LrSvB1kknauQAnU3MgL7Eg+ZrlGljtgL0PJ3gPR9kkRG4fts2v" + - "sxbnrART4YTs/AVagSxahnXrVnj/GlFVbO+cWpMadnYLl+pe7k4n1IdtD7m3WIpV" + - "Zlwwgj/LQSD+b57Te+MkpCRoKFIWQMW0Eh5M6Mftb1MIN5h3zR/QLmEuREUzPshB" + - "3CIMHv9LX2St8mA6n5sH/gIJOQW7breP7N7QAsOjKhgOhy4vEWx+Ig7VjCH4EU7I" + - "AIHKSYhLICTBPKF5c1yTp/gMCE086VyMDu7i52jNKz2VsVX13qNr/7t2wVKaoQ2Z" + - "frUA3uq7HX0vEe8CAwEAAaOCAgQwggIAMA4GA1UdDwEB/wQEAwIHgDAgBgNVHSUB" + - "Af8EFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwgeAGA1UdIASB2DCB1TCB0gYLKwYB" + - "BAGodYEGAWQwgcIwKgYIKwYBBQUHAgEWHmh0dHA6Ly9vYi50cnVzdGlzLmNvbS9w" + - "b2xpY2llczCBkwYIKwYBBQUHAgIwgYYMgYNVc2Ugb2YgdGhpcyBDZXJ0aWZpY2F0" + - "ZSBjb25zdGl0dXRlcyBhY2NlcHRhbmNlIG9mIHRoZSBPcGVuQmFua2luZyBSb290" + - "IENBIENlcnRpZmljYXRpb24gUG9saWNpZXMgYW5kIENlcnRpZmljYXRlIFByYWN0" + - "aWNlIFN0YXRlbWVudDBtBggrBgEFBQcBAQRhMF8wJgYIKwYBBQUHMAGGGmh0dHA6" + - "Ly9vYi50cnVzdGlzLmNvbS9vY3NwMDUGCCsGAQUFBzAChilodHRwOi8vb2IudHJ1" + - "c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNydDA6BgNVHR8EMzAxMC+gLaArhilo" + - "dHRwOi8vb2IudHJ1c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNybDAfBgNVHSME" + - "GDAWgBRQc5HGIXLTd/T+ABIGgVx5eW4/UDAdBgNVHQ4EFgQUt/iQ/+ksD95pZUol" + - "YF8R+2838bgwDQYJKoZIhvcNAQELBQADggEBAH7/dvG7jm6xN1G0nziOHN/GSdJt" + - "6wxodmRr/nDGBiHjONS2qq6wSSaN/QfUfe5OPbICi6dDNDgJpk1ZJKWXpdBW3K0e" + - "3mjOvEjMSC6V/iu8T6NT4PWF9IGc10I93z/NbVYFahjfLtuBzBKwr7DbASYawzVF" + - "rUa7CGbzk+nUGoqoMV/0eF+UtjDx2NYoGov7WK07XDFxsJJOjq0lA7SB3/3BqttW" + - "J+iX9CafGYP2v9hjjOz1y7Jbr66Kd9tBK9C0+5bHvO84VoupUl8iateeBiFPqd+p" + - "gLzORyiwIa7lsLvx273Fz3iOvX2Ksg9I/qhWABZ4adm//G45+GDGKFebzLo=" + - "-----END CERTIFICATE-----"; - - public static final String TEST_CLIENT_CERT_ISSUER = "-----BEGIN CERTIFICATE-----" + - "MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl" + - "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3" + - "d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv" + - "b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG" + - "EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl" + - "cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi" + - "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c" + - "JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP" + - "mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+" + - "wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4" + - "VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/" + - "AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB" + - "AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW" + - "BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun" + - "pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC" + - "dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf" + - "fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm" + - "NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx" + - "H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe" + - "+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g==" + - "-----END CERTIFICATE-----"; - - public static final String EXPIRED_SELF_CERT = "-----BEGIN CERTIFICATE-----" + - "MIIDiTCCAnGgAwIBAgIENx3SZjANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJs" + - "azEQMA4GA1UECBMHd2VzdGVybjEQMA4GA1UEBxMHY29sb21ibzENMAsGA1UEChME" + - "d3NvMjEUMBIGA1UECxMLb3BlbmJhbmtpbmcxHTAbBgNVBAMTFG9wZW5iYW5raW5n" + - "LndzbzIuY29tMB4XDTIwMDMwMTEyMjE1MVoXDTIwMDUzMDEyMjE1MVowdTELMAkG" + - "A1UEBhMCbGsxEDAOBgNVBAgTB3dlc3Rlcm4xEDAOBgNVBAcTB2NvbG9tYm8xDTAL" + - "BgNVBAoTBHdzbzIxFDASBgNVBAsTC29wZW5iYW5raW5nMR0wGwYDVQQDExRvcGVu" + - "YmFua2luZy53c28yLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB" + - "AKWMb1mhSthxi5vmQcvEnt0rauYv8uFWjGyiuCkk5wQbArybGXyC8rrZf5qNNY4s" + - "RG2+Yimxph2Z8MWWPFBebTIABPuRcVDquX7fL4+8FZJTH3JLwfT+slunAA4473mZ" + - "9s2fAVu6CmQf1V09+fEbMGI9WWh53g19wg5WdlToOX4g5lh4QtGRpbWpEWaYrKzS" + - "B5EWOUI7lroFtv6s9OpEO59VAkXWKUbT98T8TCYqiDH+nMy3k+GbVawxXeHYHQr+" + - "XlbcChPaCwhMXspqKG49xaJmrOuRMoAWCBGUW8r2RDhQ+FP5V/sTRMqKmBv9gTe6" + - "RJwoKPlDt+0aX9vaFjKpjPcCAwEAAaMhMB8wHQYDVR0OBBYEFGH0gyeHIz1+ONGI" + - "PuGnAhrS3apoMA0GCSqGSIb3DQEBCwUAA4IBAQCVEakh1SLnZOz2IK0ISbAV5UBb" + - "nerLNDl+X+YSYsCQM1SBcXDjlkSAeP3ErJEO3RW3wdRQjLRRHomwSCSRE84SUfSL" + - "VPIbeR7jm4sS9x5rnlGF6iqhYh2MlZD/hFxdrGoYv8g/JN4FFFMXRmmaQ8ouYJwc" + - "4ZoxRdCXszeI5Zp2+b14cs/nf4geYliHtcDr/w7fkvQ0hn+c1lTihbW0/eE32aUK" + - "SULAmjx0sCDfDAQItP79CC7jCW0TFN0CMORw/+fzp/dnVboSZ2MgcuRIH1Ez+6/1" + - "1QJD2SrkkaRSEaXI6fe9jgHVhnqK9V3y3WAuzEKjaKw6jV8BjkXAA4dQj1Re" + - "-----END CERTIFICATE-----"; - public static final String EIDAS_CERT = "-----BEGIN CERTIFICATE-----" + - "MIIF2DCCBMCgAwIBAgIEWcYJGDANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJH" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNVBAMTJU9wZW5CYW5raW5nIFBy" + - "ZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwHhcNMjAxMjE1MDY1ODMxWhcNMjIwMTE1" + - "MDcyODMxWjBzMQswCQYDVQQGEwJHQjEaMBgGA1UEChMRV1NPMiAoVUspIExJTUlU" + - "RUQxKzApBgNVBGETIlBTREdCLU9CLVVua25vd24wMDE1ODAwMDAxSFFRclpBQVgx" + - "GzAZBgNVBAMTEjAwMTU4MDAwMDFIUVFyWkFBWDCCASIwDQYJKoZIhvcNAQEBBQAD" + - "ggEPADCCAQoCggEBAN4RybsCYch4OAzJz3bfVAsz04lcuGYz1DE21l6PKkrABU3k" + - "AYWUw9YtLWDVfA4nemSd5vb9dNJJoY6bvLTBbWBpWqOmq+lzXB4WrGuF5v4BaE8U" + - "OeuVoIxKg9sV2mHAOaflVX8cz0dZSAbf1h+lvRRzIlX4TgN2ApZACIdtcBZfooOj" + - "1F070MM9gyLw2A3cOew4MXaaZZFHP0CzQWlRyftaw0mYrx7m2iUK+4d4zEgEjC05" + - "kdEpkdTtXvuTla/ER9O7DSnx++qKoRcEkqloOF/Rz7uhRhGfQHy6JwrNrZOr9khS" + - "90pEejBnr8Is9BLqaRwE6COAPq/C+w5ZQ4pd9oMCAwEAAaOCApIwggKOMA4GA1Ud" + - "DwEB/wQEAwIHgDCBiwYIKwYBBQUHAQMEfzB9MBMGBgQAjkYBBjAJBgcEAI5GAQYD" + - "MGYGBgQAgZgnAjBcMDUwMwYHBACBmCcBAgwGUFNQX1BJBgcEAIGYJwEDDAZQU1Bf" + - "QUkGBwQAgZgnAQQMBlBTUF9JQwwbRmluYW5jaWFsIENvbmR1Y3QgQXV0aG9yaXR5" + - "DAZHQi1GQ0EwIAYDVR0lAQH/BBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMIHgBgNV" + - "HSAEgdgwgdUwgdIGCysGAQQBqHWBBgFkMIHCMCoGCCsGAQUFBwIBFh5odHRwOi8v" + - "b2IudHJ1c3Rpcy5jb20vcG9saWNpZXMwgZMGCCsGAQUFBwICMIGGDIGDVXNlIG9m" + - "IHRoaXMgQ2VydGlmaWNhdGUgY29uc3RpdHV0ZXMgYWNjZXB0YW5jZSBvZiB0aGUg" + - "T3BlbkJhbmtpbmcgUm9vdCBDQSBDZXJ0aWZpY2F0aW9uIFBvbGljaWVzIGFuZCBD" + - "ZXJ0aWZpY2F0ZSBQcmFjdGljZSBTdGF0ZW1lbnQwbQYIKwYBBQUHAQEEYTBfMCYG" + - "CCsGAQUFBzABhhpodHRwOi8vb2IudHJ1c3Rpcy5jb20vb2NzcDA1BggrBgEFBQcw" + - "AoYpaHR0cDovL29iLnRydXN0aXMuY29tL29iX3BwX2lzc3VpbmdjYS5jcnQwOgYD" + - "VR0fBDMwMTAvoC2gK4YpaHR0cDovL29iLnRydXN0aXMuY29tL29iX3BwX2lzc3Vp" + - "bmdjYS5jcmwwHwYDVR0jBBgwFoAUUHORxiFy03f0/gASBoFceXluP1AwHQYDVR0O" + - "BBYEFN0LLFBaqNtl17Ds7a+4EwedY69oMA0GCSqGSIb3DQEBCwUAA4IBAQBpyV93" + - "NoWNDg8PhcTWrxQFRLSvNCaDfKQw7MVzK7pl9cFnugZPXUg67KmLiJ+GzI9HHym/" + - "yfd3Vwx5SNtfQVACmStKsLGv6kRGJcUAIgICV8ZGVlbsWpKam2ck7wR2138QD8s1" + - "igAIaSWzHyHlkPjy44hRDbLpEYhRf9c2bUYGYnkMUBhmhI3ZhbopR3Zac/1/VBlA" + - "VR7G0VQiloTHoQUL6OkaTnfdOEjU9Eeo8lQgrGjob5aCWrrPe4ExCyAZdn0NgE69" + - "womfyrqwLoQpiUGmOSZCuOgWmPe8OrbpGIaodZz2Wk5qgR5xrVkNDfvgM/nXm1r8" + - "HxriBi5shkweEW6g" + - "-----END CERTIFICATE-----"; - - public static final String EIDAS_CERT_ISSUER = "-----BEGIN CERTIFICATE-----" + - "MIIGEzCCA/ugAwIBAgIEWcT9RzANBgkqhkiG9w0BAQsFADBQMQswCQYDVQQGEwJH" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxKzApBgNVBAMTIk9wZW5CYW5raW5nIFBy" + - "ZS1Qcm9kdWN0aW9uIFJvb3QgQ0EwHhcNMTcwOTIyMTI0NjU3WhcNMjcwOTIyMTMx" + - "NjU3WjBTMQswCQYDVQQGEwJHQjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNV" + - "BAMTJU9wZW5CYW5raW5nIFByZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwggEiMA0G" + - "CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCyyrRg2jF01jXhX3IR44p338ZBozn8" + - "WkZaCN8MB+AlBfuXHD6mC/0v+N/Z4XI6E5pzArmTho8D6a6JDpAHmmefqGSqOXVb" + - "clYv1tHFjmC1FtKqkFHTTMyhl41nEMo0dnvWA45bMsGm0yMi/tEM5Vb5dSY4Zr/2" + - "LWgUTDFUisgUbyIIHT+L6qxPUPCpNuEd+AWVc9K0SlmhaC+UIfVO83gE1+9ar2dO" + - "NSFaK/a445Us6MnqgKvfkvKdaR06Ok/EhGgiAZORcyZ61EYFVVzJewy5NrFSF3mw" + - "iPYvMxoT5bxcwAEvxqBXpTDv8njQfR+cgZDeloeK1UqmW/DpR+jj3KNHAgMBAAGj" + - "ggHwMIIB7DAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADCB4AYD" + - "VR0gBIHYMIHVMIHSBgsrBgEEAah1gQYBZDCBwjAqBggrBgEFBQcCARYeaHR0cDov" + - "L29iLnRydXN0aXMuY29tL3BvbGljaWVzMIGTBggrBgEFBQcCAjCBhgyBg1VzZSBv" + - "ZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhl" + - "IE9wZW5CYW5raW5nIFJvb3QgQ0EgQ2VydGlmaWNhdGlvbiBQb2xpY2llcyBhbmQg" + - "Q2VydGlmaWNhdGUgUHJhY3RpY2UgU3RhdGVtZW50MGoGCCsGAQUFBwEBBF4wXDAy" + - "BggrBgEFBQcwAoYmaHR0cDovL29iLnRydXN0aXMuY29tL29idGVzdHJvb3RjYS5j" + - "cnQwJgYIKwYBBQUHMAGGGmh0dHA6Ly9vYi50cnVzdGlzLmNvbS9vY3NwMDcGA1Ud" + - "HwQwMC4wLKAqoCiGJmh0dHA6Ly9vYi50cnVzdGlzLmNvbS9vYl9wcF9yb290Y2Eu" + - "Y3JsMB8GA1UdIwQYMBaAFOw4jgva8/k3PpDefV9q5mDNeUKDMB0GA1UdDgQWBBRQ" + - "c5HGIXLTd/T+ABIGgVx5eW4/UDANBgkqhkiG9w0BAQsFAAOCAgEAdRg2H9uLwzlG" + - "qvHGjIz0ydM1tElujEcWJp5MeiorikK0rMOlxVU6ZFBlXPfO1APu0cZXxfHwWs91" + - "zoNCpGXebC6tiDFQ3+mI4qywtippjBqb6Sft37NlkXDzQETomsY7wETuUJ31xFA0" + - "FccI8WlAUzUOBE8OAGo5kAZ4FTa/nkd8c2wmuwSp+9/s+gQe0K9BkxywoP1WAEdU" + - "AaKW3RE9yuTbHA/ZF/zz4/Rpw/FB/hYhOxvDV6qInl5B7ErSH4r4v4D2jiE6apAc" + - "n5LT+e0aBa/EgGAxgyAgrYpw1s+TCUJot+227xRvXxeeZzXa2igsd+C845BGiSlt" + - "hzr0mqYDYEWJMfApZ+BlMtxa7K9T3D2l6XMv12RoNnEWe6H5xazTvBLiTibW3c5i" + - "j8WWKJNtQbgmooRPaKJIl+0rm54MFH0FDxJ+P4mAR6qa8JS911nS26iCsE9FQVK5" + - "1djuct349FYBOVM595/GkkTz9k1vXw1BdD71lNjI00Yjf73AAtvL/X4CpRz92Nag" + - "shS2Ia5a3qjjFrjx7z4h7QtMJGjuUsjTI/c+yjIYwAZ5gelF5gz7l2dn3g6B40pu" + - "7y1EewlfIQh/HVMF0ZpF29XL6+7siYQCGhP5cNJ04fotzqDPaT2XlOhE3yNkjp82" + - "uzCWvhLUJgE3D9V9PL0XD/ykNEP0Fio=" + - "-----END CERTIFICATE-----"; - - public static final String REQUEST_BODY_WITH_SSA = "eyJ0eXAiOiJKV1QiLCJhbGciOiJQUzI1NiIsImtpZCI6IkR3TUtk" + - "V01tajdQV2ludm9xZlF5WFZ6eVo2USJ9.eyJpc3MiOiI5YjV1c0RwYk50bXhEY1R6czdHektwIiwiaWF0IjoxNjAxOTgy" + - "MDQyLCJleHAiOjE2MDcyNTI0NDIsImp0aSI6IjE2MDE5ODIwNDYiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo4MjQzL" + - "3Rva2VuIiwic2NvcGUiOiJhY2NvdW50cyBwYXltZW50cyIsInRva2VuX2VuZHBvaW50X2F1dGhfbWV0aG9kIjoicHJpdm" + - "F0ZV9rZXlfand0IiwiZ3JhbnRfdHlwZXMiOlsiYXV0aG9yaXphdGlvbl9jb2RlIiwicmVmcmVzaF90b2tlbiJdLCJyZXN" + - "wb25zZV90eXBlcyI6WyJjb2RlIGlkX3Rva2VuIl0sImlkX3Rva2VuX3NpZ25lZF9yZXNwb25zZV9hbGciOiJQUzI1NiIs" + - "InJlcXVlc3Rfb2JqZWN0X3NpZ25pbmdfYWxnIjoiUFMyNTYiLCJzb2Z0d2FyZV9pZCI6IjliNXVzRHBiTnRteERjVHpzN" + - "0d6S3AiLCJhcHBsaWNhdGlvbl90eXBlIjoid2ViIiwicmVkaXJlY3RfdXJpcyI6WyJodHRwczovL3dzbzIuY29tIl0sIn" + - "Rva2VuX2VuZHBvaW50X2F1dGhfc2lnbmluZ19hbGciOiJQUzI1NiIsInNvZnR3YXJlX3N0YXRlbWVudCI6ImV5SmhiR2N" + - "pT2lKUVV6STFOaUlzSW10cFpDSTZJa2g2WVRsMk5XSm5SRXBqVDI1b1kxVmFOMEpOZDJKVFRGODBUbFl3WjFOR2RrbHFZ" + - "Vk5ZWkVNdE1XTTlJaXdpZEhsd0lqb2lTbGRVSW4wLmV5SnBjM01pT2lKUGNHVnVRbUZ1YTJsdVp5Qk1kR1FpTENKcFlYU" + - "WlPakUxT1RJek5qUTFOamdzSW1wMGFTSTZJak5rTVdJek5UazFaV1poWXpSbE16WWlMQ0p6YjJaMGQyRnlaVjlsYm5acG" + - "NtOXViV1Z1ZENJNkluTmhibVJpYjNnaUxDSnpiMlowZDJGeVpWOXRiMlJsSWpvaVZHVnpkQ0lzSW5OdlpuUjNZWEpsWDJ" + - "sa0lqb2lPV0kxZFhORWNHSk9kRzE0UkdOVWVuTTNSM3BMY0NJc0luTnZablIzWVhKbFgyTnNhV1Z1ZEY5cFpDSTZJamxp" + - "TlhWelJIQmlUblJ0ZUVSalZIcHpOMGQ2UzNBaUxDSnpiMlowZDJGeVpWOWpiR2xsYm5SZmJtRnRaU0k2SWxkVFR6SWdUM" + - "0JsYmlCQ1lXNXJhVzVuSUZSUVVDQW9VMkZ1WkdKdmVDa2lMQ0p6YjJaMGQyRnlaVjlqYkdsbGJuUmZaR1Z6WTNKcGNIUn" + - "BiMjRpT2lKVWFHbHpJRlJRVUNCSmN5QmpjbVZoZEdWa0lHWnZjaUIwWlhOMGFXNW5JSEIxY25CdmMyVnpMaUFpTENKemI" + - "yWjBkMkZ5WlY5MlpYSnphVzl1SWpveExqVXNJbk52Wm5SM1lYSmxYMk5zYVdWdWRGOTFjbWtpT2lKb2RIUndjem92TDNk" + - "emJ6SXVZMjl0SWl3aWMyOW1kSGRoY21WZmNtVmthWEpsWTNSZmRYSnBjeUk2V3lKb2RIUndjem92TDNkemJ6SXVZMjl0S" + - "Wwwc0luTnZablIzWVhKbFgzSnZiR1Z6SWpwYklrRkpVMUFpTENKUVNWTlFJbDBzSW05eVoyRnVhWE5oZEdsdmJsOWpiMj" + - "F3WlhSbGJuUmZZWFYwYUc5eWFYUjVYMk5zWVdsdGN5STZleUpoZFhSb2IzSnBkSGxmYVdRaU9pSlBRa2RDVWlJc0luSmx" + - "aMmx6ZEhKaGRHbHZibDlwWkNJNklsVnVhMjV2ZDI0d01ERTFPREF3TURBeFNGRlJjbHBCUVZnaUxDSnpkR0YwZFhNaU9p" + - "SkJZM1JwZG1VaUxDSmhkWFJvYjNKcGMyRjBhVzl1Y3lJNlczc2liV1Z0WW1WeVgzTjBZWFJsSWpvaVIwSWlMQ0p5YjJ4b" + - "GN5STZXeUpCU1ZOUUlpd2lVRWxUVUNKZGZTeDdJbTFsYldKbGNsOXpkR0YwWlNJNklrbEZJaXdpY205c1pYTWlPbHNpUV" + - "VsVFVDSXNJbEJKVTFBaVhYMHNleUp0WlcxaVpYSmZjM1JoZEdVaU9pSk9UQ0lzSW5KdmJHVnpJanBiSWtGSlUxQWlMQ0p" + - "RU1ZOUUlsMTlYWDBzSW5OdlpuUjNZWEpsWDJ4dloyOWZkWEpwSWpvaWFIUjBjSE02THk5M2MyOHlMbU52YlM5M2MyOHlM" + - "bXB3WnlJc0ltOXlaMTl6ZEdGMGRYTWlPaUpCWTNScGRtVWlMQ0p2Y21kZmFXUWlPaUl3TURFMU9EQXdNREF4U0ZGUmNsc" + - "EJRVmdpTENKdmNtZGZibUZ0WlNJNklsZFRUeklnS0ZWTEtTQk1TVTFKVkVWRUlpd2liM0puWDJOdmJuUmhZM1J6SWpwYm" + - "V5SnVZVzFsSWpvaVZHVmphRzVwWTJGc0lpd2laVzFoYVd3aU9pSnpZV05vYVc1cGMwQjNjMjh5TG1OdmJTSXNJbkJvYjI" + - "1bElqb2lLemswTnpjME1qYzBNemMwSWl3aWRIbHdaU0k2SWxSbFkyaHVhV05oYkNKOUxIc2libUZ0WlNJNklrSjFjMmx1" + - "WlhOeklpd2laVzFoYVd3aU9pSnpZV05vYVc1cGMwQjNjMjh5TG1OdmJTSXNJbkJvYjI1bElqb2lLemswTnpjME1qYzBNe" + - "mMwSWl3aWRIbHdaU0k2SWtKMWMybHVaWE56SW4xZExDSnZjbWRmYW5kcmMxOWxibVJ3YjJsdWRDSTZJbWgwZEhCek9pOH" + - "ZhMlY1YzNSdmNtVXViM0JsYm1KaGJtdHBibWQwWlhOMExtOXlaeTUxYXk4d01ERTFPREF3TURBeFNGRlJjbHBCUVZndk1" + - "EQXhOVGd3TURBd01VaFJVWEphUVVGWUxtcDNhM01pTENKdmNtZGZhbmRyYzE5eVpYWnZhMlZrWDJWdVpIQnZhVzUwSWpv" + - "aWFIUjBjSE02THk5clpYbHpkRzl5WlM1dmNHVnVZbUZ1YTJsdVozUmxjM1F1YjNKbkxuVnJMekF3TVRVNE1EQXdNREZJV" + - "VZGeVdrRkJXQzl5WlhadmEyVmtMekF3TVRVNE1EQXdNREZJVVZGeVdrRkJXQzVxZDJ0eklpd2ljMjltZEhkaGNtVmZhbm" + - "RyYzE5bGJtUndiMmx1ZENJNkltaDBkSEJ6T2k4dmEyVjVjM1J2Y21VdWIzQmxibUpoYm10cGJtZDBaWE4wTG05eVp5NTF" + - "heTh3TURFMU9EQXdNREF4U0ZGUmNscEJRVmd2T1dJMWRYTkVjR0pPZEcxNFJHTlVlbk0zUjNwTGNDNXFkMnR6SWl3aWMy" + - "OW1kSGRoY21WZmFuZHJjMTl5WlhadmEyVmtYMlZ1WkhCdmFXNTBJam9pYUhSMGNITTZMeTlyWlhsemRHOXlaUzV2Y0dWd" + - "VltRnVhMmx1WjNSbGMzUXViM0puTG5Wckx6QXdNVFU0TURBd01ERklVVkZ5V2tGQldDOXlaWFp2YTJWa0x6bGlOWFZ6Uk" + - "hCaVRuUnRlRVJqVkhwek4wZDZTM0F1YW5kcmN5SXNJbk52Wm5SM1lYSmxYM0J2YkdsamVWOTFjbWtpT2lKb2RIUndjem9" + - "2TDNkemJ6SXVZMjl0SWl3aWMyOW1kSGRoY21WZmRHOXpYM1Z5YVNJNkltaDBkSEJ6T2k4dmQzTnZNaTVqYjIwaUxDSnpi" + - "MlowZDJGeVpWOXZibDlpWldoaGJHWmZiMlpmYjNKbklqb2lWMU5QTWlCUGNHVnVJRUpoYm10cGJtY2lmUS5DQTE0b2dkY" + - "3BOd29IaUlKb3o2bVR4TnBNMndScnFpWkFjYm1LMFJuRHgyR0ROM0JIWW5aRzBFcTZWZ3lQYlByY1J5ZldsOGpRczJFU3" + - "NXYzVKU0J3ZWpIYnZwbng3a1ZCeVlrRzQ0ZGhvemFQQU5FWmx0Tmo0TTkxMkNnSGVLUGRfZDB1SUQ4ZElVcThfczJrWU1" + - "zb0NjY0JxR3lGVEl5bVZLMDFIWF9YXy1UN25wR19vdkU4Q0xnaWxNRmtpank1UGlGQzgzaG9weGl4ZVFmUmdkbUhDUl8x" + - "Ym9rc2JGREszUlBJRWU1UGlPRHZYOHZsV0I4aVVHeTdQR3paMGlrWEJEMGx4OXAxQUpFeVlGM3gxcENqc1NIOHRKQzVFN" + - "UNHMHhaTFFQUGtUM0FfU3BqaVVoNUVsTmROY21UUG93MkxWU3hQOVF1c040dldwRU1VTmQ5cHcifQ.kq8UsDUcb6Ee55w" + - "4U4JhiifyUB0sSiTAnobLV1bwujfS2msdUfxDHqVjyrvx4NvPd54sXg3_k1EIRHLT4vT-zUkojqtWiB_v2ndo5UqvPUrI" + - "FoqY0IQznKBfD6cLlGQ0laYqxm_GJWAEdEv_O8Ggw_z1DMiZZRHF9Oln9zZtT95JcGeJ8JCQVDkaX_AM-fZrVaixfD4iB" + - "fy-n4H6LHCy94c1DrCM9wEGr7XfHLAVNdZe2Qbyjf1sVEPukK_ccw4AYcWUo3UJQ2WIKxZL4fBmb_3Z0ez9k31k6in86H" + - "g4tHO9itXSVJvvzn8oAaYXXQrxfk4N1CojV3zk1bkhy6In3Q"; - - public static final String REQUEST_BODY_WITH_SSA_SINGLE_ROLE = "eyJ0eXAiOiJKV1QiLCJhbGciOiJQUzI1NiIsIm" + - "tpZCI6IkR3TUtkV01tajdQV2ludm9xZlF5WFZ6eVo2USJ9.eyJpc3MiOiI5YjV1c0RwYk50bXhEY1R6czdHektwIiwiaW" + - "F0IjoxNjAxOTgyMDQyLCJleHAiOjE2MDcyNTI0NDIsImp0aSI6IjE2MDE5ODIwNDYiLCJhdWQiOiJodHRwczovL2xvY2F" + - "saG9zdDo4MjQzL3Rva2VuIiwic2NvcGUiOiJhY2NvdW50cyBwYXltZW50cyIsInRva2VuX2VuZHBvaW50X2F1dGhfbWV0" + - "aG9kIjoicHJpdmF0ZV9rZXlfand0IiwiZ3JhbnRfdHlwZXMiOlsiYXV0aG9yaXphdGlvbl9jb2RlIiwicmVmcmVzaF90b" + - "2tlbiJdLCJyZXNwb25zZV90eXBlcyI6WyJjb2RlIGlkX3Rva2VuIl0sImlkX3Rva2VuX3NpZ25lZF9yZXNwb25zZV9hbG" + - "ciOiJQUzI1NiIsInJlcXVlc3Rfb2JqZWN0X3NpZ25pbmdfYWxnIjoiUFMyNTYiLCJzb2Z0d2FyZV9pZCI6IjliNXVzRHB" + - "iTnRteERjVHpzN0d6S3AiLCJhcHBsaWNhdGlvbl90eXBlIjoid2ViIiwicmVkaXJlY3RfdXJpcyI6WyJodHRwczovL3dz" + - "bzIuY29tIl0sInRva2VuX2VuZHBvaW50X2F1dGhfc2lnbmluZ19hbGciOiJQUzI1NiIsInNvZnR3YXJlX3N0YXRlbWVud" + - "CI6ImV5SmhiR2NpT2lKUVV6STFOaUlzSW10cFpDSTZJa2g2WVRsMk5XSm5SRXBqVDI1b1kxVmFOMEpOZDJKVFRGODBUbF" + - "l3WjFOR2RrbHFZVk5ZWkVNdE1XTTlJaXdpZEhsd0lqb2lTbGRVSW4wLmV5SnBjM01pT2lKUGNHVnVRbUZ1YTJsdVp5Qk1" + - "kR1FpTENKcFlYUWlPakUxT1RJek5qUTFOamdzSW1wMGFTSTZJak5rTVdJek5UazFaV1poWXpSbE16WWlMQ0p6YjJaMGQy" + - "RnlaVjlsYm5acGNtOXViV1Z1ZENJNkluTmhibVJpYjNnaUxDSnpiMlowZDJGeVpWOXRiMlJsSWpvaVZHVnpkQ0lzSW5Od" + - "lpuUjNZWEpsWDJsa0lqb2lPV0kxZFhORWNHSk9kRzE0UkdOVWVuTTNSM3BMY0NJc0luTnZablIzWVhKbFgyTnNhV1Z1ZE" + - "Y5cFpDSTZJamxpTlhWelJIQmlUblJ0ZUVSalZIcHpOMGQ2UzNBaUxDSnpiMlowZDJGeVpWOWpiR2xsYm5SZmJtRnRaU0k" + - "2SWxkVFR6SWdUM0JsYmlCQ1lXNXJhVzVuSUZSUVVDQW9VMkZ1WkdKdmVDa2lMQ0p6YjJaMGQyRnlaVjlqYkdsbGJuUmZa" + - "R1Z6WTNKcGNIUnBiMjRpT2lKVWFHbHpJRlJRVUNCSmN5QmpjbVZoZEdWa0lHWnZjaUIwWlhOMGFXNW5JSEIxY25CdmMyV" + - "npMaUFpTENKemIyWjBkMkZ5WlY5MlpYSnphVzl1SWpveExqVXNJbk52Wm5SM1lYSmxYMk5zYVdWdWRGOTFjbWtpT2lKb2" + - "RIUndjem92TDNkemJ6SXVZMjl0SWl3aWMyOW1kSGRoY21WZmNtVmthWEpsWTNSZmRYSnBjeUk2V3lKb2RIUndjem92TDN" + - "kemJ6SXVZMjl0SWwwc0luTnZablIzWVhKbFgzSnZiR1Z6SWpvaVFVbFRVQ0lzSW05eVoyRnVhWE5oZEdsdmJsOWpiMjF3" + - "WlhSbGJuUmZZWFYwYUc5eWFYUjVYMk5zWVdsdGN5STZleUpoZFhSb2IzSnBkSGxmYVdRaU9pSlBRa2RDVWlJc0luSmxaM" + - "mx6ZEhKaGRHbHZibDlwWkNJNklsVnVhMjV2ZDI0d01ERTFPREF3TURBeFNGRlJjbHBCUVZnaUxDSnpkR0YwZFhNaU9pSk" + - "JZM1JwZG1VaUxDSmhkWFJvYjNKcGMyRjBhVzl1Y3lJNlczc2liV1Z0WW1WeVgzTjBZWFJsSWpvaVIwSWlMQ0p5YjJ4bGN" + - "5STZXeUpCU1ZOUUlpd2lVRWxUVUNKZGZTeDdJbTFsYldKbGNsOXpkR0YwWlNJNklrbEZJaXdpY205c1pYTWlPbHNpUVVs" + - "VFVDSXNJbEJKVTFBaVhYMHNleUp0WlcxaVpYSmZjM1JoZEdVaU9pSk9UQ0lzSW5KdmJHVnpJanBiSWtGSlUxQWlMQ0pRU" + - "1ZOUUlsMTlYWDBzSW5OdlpuUjNZWEpsWDJ4dloyOWZkWEpwSWpvaWFIUjBjSE02THk5M2MyOHlMbU52YlM5M2MyOHlMbX" + - "B3WnlJc0ltOXlaMTl6ZEdGMGRYTWlPaUpCWTNScGRtVWlMQ0p2Y21kZmFXUWlPaUl3TURFMU9EQXdNREF4U0ZGUmNscEJ" + - "RVmdpTENKdmNtZGZibUZ0WlNJNklsZFRUeklnS0ZWTEtTQk1TVTFKVkVWRUlpd2liM0puWDJOdmJuUmhZM1J6SWpwYmV5" + - "SnVZVzFsSWpvaVZHVmphRzVwWTJGc0lpd2laVzFoYVd3aU9pSnpZV05vYVc1cGMwQjNjMjh5TG1OdmJTSXNJbkJvYjI1b" + - "Elqb2lLemswTnpjME1qYzBNemMwSWl3aWRIbHdaU0k2SWxSbFkyaHVhV05oYkNKOUxIc2libUZ0WlNJNklrSjFjMmx1Wl" + - "hOeklpd2laVzFoYVd3aU9pSnpZV05vYVc1cGMwQjNjMjh5TG1OdmJTSXNJbkJvYjI1bElqb2lLemswTnpjME1qYzBNemM" + - "wSWl3aWRIbHdaU0k2SWtKMWMybHVaWE56SW4xZExDSnZjbWRmYW5kcmMxOWxibVJ3YjJsdWRDSTZJbWgwZEhCek9pOHZh" + - "MlY1YzNSdmNtVXViM0JsYm1KaGJtdHBibWQwWlhOMExtOXlaeTUxYXk4d01ERTFPREF3TURBeFNGRlJjbHBCUVZndk1EQ" + - "XhOVGd3TURBd01VaFJVWEphUVVGWUxtcDNhM01pTENKdmNtZGZhbmRyYzE5eVpYWnZhMlZrWDJWdVpIQnZhVzUwSWpvaW" + - "FIUjBjSE02THk5clpYbHpkRzl5WlM1dmNHVnVZbUZ1YTJsdVozUmxjM1F1YjNKbkxuVnJMekF3TVRVNE1EQXdNREZJVVZ" + - "GeVdrRkJXQzl5WlhadmEyVmtMekF3TVRVNE1EQXdNREZJVVZGeVdrRkJXQzVxZDJ0eklpd2ljMjltZEhkaGNtVmZhbmRy" + - "YzE5bGJtUndiMmx1ZENJNkltaDBkSEJ6T2k4dmEyVjVjM1J2Y21VdWIzQmxibUpoYm10cGJtZDBaWE4wTG05eVp5NTFhe" + - "Th3TURFMU9EQXdNREF4U0ZGUmNscEJRVmd2T1dJMWRYTkVjR0pPZEcxNFJHTlVlbk0zUjNwTGNDNXFkMnR6SWl3aWMyOW" + - "1kSGRoY21WZmFuZHJjMTl5WlhadmEyVmtYMlZ1WkhCdmFXNTBJam9pYUhSMGNITTZMeTlyWlhsemRHOXlaUzV2Y0dWdVl" + - "tRnVhMmx1WjNSbGMzUXViM0puTG5Wckx6QXdNVFU0TURBd01ERklVVkZ5V2tGQldDOXlaWFp2YTJWa0x6bGlOWFZ6UkhC" + - "aVRuUnRlRVJqVkhwek4wZDZTM0F1YW5kcmN5SXNJbk52Wm5SM1lYSmxYM0J2YkdsamVWOTFjbWtpT2lKb2RIUndjem92T" + - "DNkemJ6SXVZMjl0SWl3aWMyOW1kSGRoY21WZmRHOXpYM1Z5YVNJNkltaDBkSEJ6T2k4dmQzTnZNaTVqYjIwaUxDSnpiMl" + - "owZDJGeVpWOXZibDlpWldoaGJHWmZiMlpmYjNKbklqb2lWMU5QTWlCUGNHVnVJRUpoYm10cGJtY2lmUS5vc1RWRlBqa1h" + - "CNnh3SDNJVE04OTVpRXNOamgyMnJjR1pSdnFQOWh6cV9TX2l6UENQNTJLQ3U0ZWJkZ1o5WnpXTmdBVkp4X3hKY2dZajhs" + - "TXV6S3VWa3RFX1M0bnl2REhsSU1sblBvRGd0UlNZcElDM05LcDVWY3QyaVd0bzhkNVpWVXZJQUhDTXpXZjllVDdGSURZQ" + - "2syUEhhWHNmblNLSVM3NWE4WEJXbUo1ckgzT0xoZ0RudFhHalduNW0wdVdYUDhmOWZ0TmNvSUdMa050bEp0cXV3S2dYcF" + - "JULWJIQVNSWUE4c0lsMnFETTUtay00TEY3S1hhZDBWR2ZfcmJxclVjWnlMbEt6bldaRmM4X1Q3bHZEbnEwQVJIYWtLaUU" + - "yZGhkUlRHTHhuX21yR2lKRXg0dVFsMTlrNWF0T0FzRlJ0X0liMjdCM1lLS3V6VGxOcDRjQ2cifQ.Z0J-sLdpWmvk5MEOE" + - "We-MwO_-pve2zo0OA-7JfG5cFrsQ1WPuvb-mjjxqSjxtER3IRONRWULmTIDnuu9FCX1oQ4e_0HAmh3AQMa2sp9n8fMwHc" + - "RxmXQcOuAfYajHV5i318xcSveOrapD6jFiqLgLiLtTK3-tJB7wDg-sdxuwSI9HSldR3sBjQDTPLOLFGEJ5jJ4bl8JkKQ6" + - "zHcFkYyxMpJw7zT13hyiWvR--0WVgP8g4yYeCobPXUNmBEI7zZMuYVlO5C6l-RKFPstaasqX81zWG3ES8TVZM8rMFKqN_" + - "QoctY4HMshtk58h2W4NP4UJZyYgsGNNb2hVI5IffCVxqIw"; - - private static final Log log = LogFactory.getLog(TestValidationUtil.class); - private static java.security.cert.X509Certificate testClientCertificate = null; - private static java.security.cert.X509Certificate testClientCertificateIssuer = null; - private static java.security.cert.X509Certificate testEidasCertificate = null; - private static java.security.cert.X509Certificate testEidasCertificateIssuer = null; - private static java.security.cert.X509Certificate expiredSelfCertificate = null; - - protected static X509Certificate getCertFromStr(String pemEncodedCert) { - byte[] decodedTransportCert = Base64.getDecoder().decode(pemEncodedCert - .replace(CertificateValidationUtils.BEGIN_CERT, "") - .replace(CertificateValidationUtils.END_CERT, "")); - - InputStream inputStream = new ByteArrayInputStream(decodedTransportCert); - X509Certificate x509Certificate = null; - try { - x509Certificate = X509Certificate.getInstance(inputStream); - } catch (CertificateException e) { - log.error("Exception occured while parsing test certificate. Caused by, ", e); - } - return x509Certificate; - } - - public static synchronized java.security.cert.X509Certificate getTestClientCertificate() - throws OpenBankingException { - if (testClientCertificate == null) { - testClientCertificate = CertificateUtils.parseCertificate(TEST_CLIENT_CERT); - } - return testClientCertificate; - } - - public static synchronized java.security.cert.X509Certificate getTestClientCertificateIssuer() - throws OpenBankingException { - if (testClientCertificateIssuer == null) { - testClientCertificateIssuer = CertificateUtils.parseCertificate(TEST_CLIENT_CERT_ISSUER); - } - return testClientCertificateIssuer; - } - - public static synchronized java.security.cert.X509Certificate getTestEidasCertificate() - throws OpenBankingException { - if (testEidasCertificate == null) { - testEidasCertificate = CertificateUtils.parseCertificate(EIDAS_CERT); - } - return testEidasCertificate; - } - - public static synchronized java.security.cert.X509Certificate getTestEidasCertificateIssuer() - throws OpenBankingException { - if (testEidasCertificateIssuer == null) { - testEidasCertificateIssuer = CertificateUtils.parseCertificate(EIDAS_CERT_ISSUER); - } - return testEidasCertificateIssuer; - } - - public static synchronized java.security.cert.X509Certificate getExpiredSelfCertificate() - throws OpenBankingException { - if (expiredSelfCertificate == null) { - expiredSelfCertificate = CertificateUtils.parseCertificate(EXPIRED_SELF_CERT); - } - return expiredSelfCertificate; - } - - public static Certificate getEmptyTestCertificate() { - - return new Certificate("X.509") { - @Override - public byte[] getEncoded() { - return new byte[0]; - } - - @Override - public void verify(PublicKey key) { - - } - - @Override - public void verify(PublicKey key, String sigProvider) { - - } - - @Override - public String toString() { - return null; - } - - @Override - public PublicKey getPublicKey() { - return null; - } - }; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/handler/JwsResponseSignatureHandlerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/handler/JwsResponseSignatureHandlerTest.java deleted file mode 100644 index b202442a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/handler/JwsResponseSignatureHandlerTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.handler; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.gateway.executor.exception.OpenBankingExecutorException; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.axiom.soap.SOAPBody; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axis2.context.MessageContext; -import org.apache.commons.io.IOUtils; -import org.apache.synapse.commons.json.JsonUtil; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.core.axis2.Axis2Sender; -import org.apache.synapse.transport.passthru.util.RelayUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Optional; - -import static org.mockito.Mockito.doReturn; - -/** - * Test Handler class for Signing Responses. - */ -@PrepareForTest({OpenBankingConfigParser.class, GatewayUtils.class, JsonUtil.class, IOUtils.class, - RelayUtils.class, Axis2Sender.class}) -@PowerMockIgnore({"jdk.internal.reflect.*"}) -public class JwsResponseSignatureHandlerTest extends PowerMockTestCase { - - private MessageContext messageContext; - private HashMap headers = new HashMap<>(); - OpenBankingConfigParser openBankingConfigParserMock; - - @BeforeClass - public void init() { - - messageContext = Mockito.mock(MessageContext.class); - openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - headers = new HashMap<>(); - doReturn(headers).when(messageContext).getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); - } - - @Test(priority = 1) - public void testHandleResponseOutFlow() { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.when(openBankingConfigParserMock.isJwsResponseSigningEnabled()).thenReturn(true); - Axis2MessageContext msgCtx = Mockito.mock(Axis2MessageContext.class); - doReturn(messageContext).when(msgCtx).getAxis2MessageContext(); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(msgCtx).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - doReturn("Schema validation failed").when(soapBody).toString(); - Assert.assertTrue(new JwsResponseSignatureHandler().handleResponseOutFlow(msgCtx)); - } - - @Test(priority = 1) - public void testHandleResponseOutFlowWithPayloadError() throws Exception { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.mockStatic(GatewayUtils.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.when(openBankingConfigParserMock.isJwsResponseSigningEnabled()).thenReturn(true); - Axis2MessageContext msgCtx = Mockito.mock(Axis2MessageContext.class); - doReturn(messageContext).when(msgCtx).getAxis2MessageContext(); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(msgCtx).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - doReturn("Schema validation failed").when(soapBody).toString(); - PowerMockito.doThrow(new OpenBankingException("")).when(GatewayUtils.class, - "buildMessagePayloadFromMessageContext", Mockito.any(), Mockito.anyMap()); - PowerMockito.doReturn("test").when(GatewayUtils.class, "constructJWSSignature", - "msgCtx", new HashMap<>()); - PowerMockito.doNothing().when(GatewayUtils.class, "returnSynapseHandlerJSONError", - Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Assert.assertTrue(new JwsResponseSignatureHandler().handleResponseOutFlow(msgCtx)); - } - - @Test(priority = 1) - public void testHandleResponseOutFlowWithPayload() throws Exception { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.mockStatic(GatewayUtils.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.when(openBankingConfigParserMock.isJwsResponseSigningEnabled()).thenReturn(true); - Axis2MessageContext msgCtx = Mockito.mock(Axis2MessageContext.class); - doReturn(messageContext).when(msgCtx).getAxis2MessageContext(); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(msgCtx).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - doReturn("Schema validation failed").when(soapBody).toString(); - PowerMockito.doReturn(Optional.of("test")).when(GatewayUtils.class, "buildMessagePayloadFromMessageContext", - Mockito.any(), Mockito.anyMap()); - PowerMockito.doReturn("test").when(GatewayUtils.class, "constructJWSSignature", - "msgCtx", new HashMap<>()); - Assert.assertTrue(new JwsResponseSignatureHandler().handleResponseOutFlow(msgCtx)); - } - - @Test(priority = 1) - public void testGenerateJWSSignature() throws Exception { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.mockStatic(GatewayUtils.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.when(openBankingConfigParserMock.isJwsResponseSigningEnabled()).thenReturn(true); - PowerMockito.doReturn("test").when(GatewayUtils.class, "constructJWSSignature", - "msgCtx", new HashMap<>()); - Assert.assertNotNull(new JwsResponseSignatureHandler().generateJWSSignature(Optional.of("msgCtx"))); - } - - @Test(priority = 1) - public void testGenerateJWSSignatureWhenPayloadIsNull() throws Exception { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.mockStatic(GatewayUtils.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.when(openBankingConfigParserMock.isJwsResponseSigningEnabled()).thenReturn(true); - PowerMockito.doReturn("test").when(GatewayUtils.class, "constructJWSSignature", - "msgCtx", new HashMap<>()); - Assert.assertNull(new JwsResponseSignatureHandler().generateJWSSignature(Optional.of(""))); - } - - @Test(priority = 1) - public void testGenerateJWSSignatureForErrorCase() throws Exception { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.mockStatic(GatewayUtils.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.when(openBankingConfigParserMock.isJwsResponseSigningEnabled()).thenReturn(true); - PowerMockito.doThrow(new OpenBankingExecutorException("")).when(GatewayUtils.class, "constructJWSSignature", - "msgCtx", new HashMap<>()); - Assert.assertNull(new JwsResponseSignatureHandler().generateJWSSignature(Optional.of(""))); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorDataHolderTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorDataHolderTest.java deleted file mode 100644 index 435fa609..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/internal/TPPCertValidatorDataHolderTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.gateway.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.File; - -/** - * Test for TPP certificate validator data holder. - */ -public class TPPCertValidatorDataHolderTest { - - private TPPCertValidatorDataHolder tppCertValidatorDataHolder; - - @BeforeClass - public void init() { - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - //CommonTestUtil.injectEnvironmentVariable("CARBON_HOME", "."); - - File file = new File("src/test/resources"); - String dummyConfigFile = file.getAbsolutePath() + "/open-banking.xml"; - OpenBankingConfigParser openBankingConfigParser = OpenBankingConfigParser.getInstance(dummyConfigFile); - - OpenBankingConfigurationService openBankingConfigurationServiceMock - = Mockito.mock(OpenBankingConfigurationService.class); - Mockito.doReturn(openBankingConfigParser.getConfiguration()) - .when(openBankingConfigurationServiceMock).getConfigurations(); - - tppCertValidatorDataHolder = TPPCertValidatorDataHolder.getInstance(); - tppCertValidatorDataHolder.setOpenBankingConfigurationService(openBankingConfigurationServiceMock); - tppCertValidatorDataHolder.initializeTPPValidationDataHolder(); - } - - @Test - public void testConfigs() { - Assert.assertEquals(tppCertValidatorDataHolder.getCertificateRevocationValidationRetryCount(), 3); - Assert.assertEquals(tppCertValidatorDataHolder.getCertificateRevocationProxyPort(), 8080); - Assert.assertEquals(tppCertValidatorDataHolder.getTppCertRevocationCacheExpiry(), 3600); - Assert.assertEquals(tppCertValidatorDataHolder.getTppValidationCacheExpiry(), 3600); - Assert.assertTrue(tppCertValidatorDataHolder.isCertificateRevocationValidationEnabled()); - Assert.assertTrue(tppCertValidatorDataHolder.isCertificateRevocationProxyEnabled()); - Assert.assertTrue(tppCertValidatorDataHolder.isTransportCertIssuerValidationEnabled()); - Assert.assertTrue(tppCertValidatorDataHolder.isPsd2RoleValidationEnabled()); - Assert.assertFalse(tppCertValidatorDataHolder.isTppValidationEnabled()); - Assert.assertNotNull(tppCertValidatorDataHolder.getCertificateRevocationValidationExcludedIssuers()); - Assert.assertNull(tppCertValidatorDataHolder.getTPPValidationServiceImpl()); - Assert.assertEquals(tppCertValidatorDataHolder.getCertificateRevocationProxyHost(), "PROXY_HOSTNAME"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/mediator/BasicAuthMediatorTests.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/mediator/BasicAuthMediatorTests.java deleted file mode 100644 index 3991b923..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/mediator/BasicAuthMediatorTests.java +++ /dev/null @@ -1,387 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.mediator; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axis2.AxisFault; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.addressing.RelatesTo; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.synapse.ContinuationState; -import org.apache.synapse.FaultHandler; -import org.apache.synapse.Mediator; -import org.apache.synapse.MessageContext; -import org.apache.synapse.config.SynapseConfiguration; -import org.apache.synapse.core.SynapseEnvironment; -import org.apache.synapse.endpoints.Endpoint; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import static org.mockito.Mockito.doReturn; - -/** - * Unit tests for Basic Auth Mediator. - */ -public class BasicAuthMediatorTests { - - @Test - public void testBasicAuthMediator() { - - MockitoAnnotations.initMocks(this); - BasicAuthMediator basicAuthMediator = Mockito.spy(BasicAuthMediator.class); - MessageContext messageContext = new MessageContextMock(); - doReturn("admin").when(basicAuthMediator).getAPIMConfigFromKey(Mockito.anyString()); - basicAuthMediator.mediate(messageContext); - Assert.assertTrue(StringUtils.equals((CharSequence) messageContext.getProperty("basicAuthentication"), - "Basic " + Base64.getEncoder().encodeToString("admin:admin".getBytes(StandardCharsets.UTF_8)))); - } - - // A mock class of MessageContext is created to mimic the behaviour - static class MessageContextMock implements MessageContext { - - Map properties = new HashMap<>(); - - @Override - public SynapseConfiguration getConfiguration() { - return null; - } - - @Override - public void setConfiguration(SynapseConfiguration synapseConfiguration) { - - } - - @Override - public SynapseEnvironment getEnvironment() { - return null; - } - - @Override - public void setEnvironment(SynapseEnvironment synapseEnvironment) { - - } - - @Override - public Map getContextEntries() { - return null; - } - - @Override - public void setContextEntries(Map map) { - - } - - @Override - public Mediator getMainSequence() { - return null; - } - - @Override - public Mediator getFaultSequence() { - return null; - } - - @Override - public Mediator getSequence(String s) { - return null; - } - - @Override - public OMElement getFormat(String s) { - return null; - } - - @Override - public Mediator getSequenceTemplate(String s) { - return null; - } - - @Override - public Endpoint getEndpoint(String s) { - return null; - } - - @Override - public Object getProperty(String s) { - return properties.get(s); - } - - @Override - public Object getEntry(String s) { - return null; - } - - @Override - public Object getLocalEntry(String s) { - return null; - } - - @Override - public void setProperty(String s, Object o) { - - this.properties.put(s, o); - } - - @Override - public Set getPropertyKeySet() { - return null; - } - - @Override - public SOAPEnvelope getEnvelope() { - return null; - } - - @Override - public void setEnvelope(SOAPEnvelope soapEnvelope) throws AxisFault { - - } - - @Override - public EndpointReference getFaultTo() { - return null; - } - - @Override - public void setFaultTo(EndpointReference endpointReference) { - - } - - @Override - public EndpointReference getFrom() { - return null; - } - - @Override - public void setFrom(EndpointReference endpointReference) { - - } - - @Override - public String getMessageID() { - return null; - } - - @Override - public void setMessageID(String s) { - - } - - @Override - public RelatesTo getRelatesTo() { - return null; - } - - @Override - public void setRelatesTo(RelatesTo[] relatesTos) { - - } - - @Override - public EndpointReference getReplyTo() { - return null; - } - - @Override - public void setReplyTo(EndpointReference endpointReference) { - - } - - @Override - public EndpointReference getTo() { - return null; - } - - @Override - public void setTo(EndpointReference endpointReference) { - - } - - @Override - public void setWSAAction(String s) { - - } - - @Override - public String getWSAAction() { - return null; - } - - @Override - public String getSoapAction() { - return null; - } - - @Override - public void setSoapAction(String s) { - - } - - @Override - public void setWSAMessageID(String s) { - - } - - @Override - public String getWSAMessageID() { - return null; - } - - @Override - public boolean isDoingMTOM() { - return false; - } - - @Override - public boolean isDoingSWA() { - return false; - } - - @Override - public void setDoingMTOM(boolean b) { - - } - - @Override - public void setDoingSWA(boolean b) { - - } - - @Override - public boolean isDoingPOX() { - return false; - } - - @Override - public void setDoingPOX(boolean b) { - - } - - @Override - public boolean isDoingGET() { - return false; - } - - @Override - public void setDoingGET(boolean b) { - - } - - @Override - public boolean isSOAP11() { - return false; - } - - @Override - public void setResponse(boolean b) { - - } - - @Override - public boolean isResponse() { - return false; - } - - @Override - public void setFaultResponse(boolean b) { - - } - - @Override - public boolean isFaultResponse() { - return false; - } - - @Override - public int getTracingState() { - return 0; - } - - @Override - public void setTracingState(int i) { - - } - - @Override - public Stack getFaultStack() { - return null; - } - - @Override - public void pushFaultHandler(FaultHandler faultHandler) { - - } - - @Override - public Stack getContinuationStateStack() { - return null; - } - - @Override - public void pushContinuationState(ContinuationState continuationState) { - - } - - @Override - public boolean isContinuationEnabled() { - return false; - } - - @Override - public void setContinuationEnabled(boolean b) { - - } - - @Override - public Log getServiceLog() { - return null; - } - - @Override - public Mediator getDefaultConfiguration(String s) { - return null; - } - - @Override - public String getMessageString() { - return null; - } - - @Override - public int getMessageFlowTracingState() { - return 0; - } - - @Override - public void setMessageFlowTracingState(int i) { - - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/reporter/OBAnalyticsMetricReporterTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/reporter/OBAnalyticsMetricReporterTest.java deleted file mode 100644 index 3c3b35a8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/reporter/OBAnalyticsMetricReporterTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.reporter; - -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.wso2.am.analytics.publisher.exception.MetricCreationException; -import org.wso2.am.analytics.publisher.exception.MetricReportingException; -import org.wso2.am.analytics.publisher.reporter.CounterMetric; - -import java.util.HashMap; -import java.util.Map; - -/** - * Test for Open Banking analytics metric reporter. - */ -public class OBAnalyticsMetricReporterTest { - - private OBAnalyticsMetricReporter obMetricReporter; - private GatewayDataHolder dataHolder; - - @Test - public void createOBMetricReporter() throws MetricCreationException { - - dataHolder = GatewayDataHolder.getInstance(); - dataHolder.setWorkerThreadCount("1"); - dataHolder.setOBDataPublishingEnabled("true"); - obMetricReporter = new OBAnalyticsMetricReporter(new HashMap<>()); - obMetricReporter.createTimer("testTimer"); - } - - @Test(dependsOnMethods = "createOBMetricReporter") - public void createCounterMetric() throws MetricCreationException, MetricReportingException { - - CounterMetric counterMetric = obMetricReporter.createCounter("testCounter", Mockito.any()); - Assert.assertEquals(counterMetric.getName(), "testCounter"); - counterMetric.incrementCount(Mockito.any()); - counterMetric.getSchema(); - } - - @Test(dependsOnMethods = "createOBMetricReporter") - public void createReporterForAPIMAnalytics() throws MetricCreationException { - - dataHolder.setAPIMAnalyticsEnabled("true"); - Map prop = new HashMap<>(); - prop.put("auth.api.token", "testToken"); - prop.put("auth.api.url", "testUrl"); - new OBAnalyticsMetricReporter(prop); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/reporter/TimestampPublishingTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/reporter/TimestampPublishingTest.java deleted file mode 100644 index 5bdc0a38..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/reporter/TimestampPublishingTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.reporter; - -import org.testng.Assert; -import org.testng.annotations.Test; -import org.wso2.am.analytics.publisher.exception.MetricReportingException; -import org.wso2.am.analytics.publisher.reporter.MetricEventBuilder; -import org.wso2.am.analytics.publisher.reporter.cloud.DefaultResponseMetricEventBuilder; - -import java.sql.Timestamp; -import java.util.Date; -import java.util.Map; -import java.util.UUID; - -/** - * Test class for timestamp publishing. - */ -public class TimestampPublishingTest { - - private static final String CORRELATION_ID = "correlationId"; - private static final String REQUEST_TIMESTAMP = "requestTimestamp"; - private static final String BACKEND_LATENCY = "backendLatency"; - private static final String REQUEST_MEDIATION_LATENCY = "requestMediationLatency"; - private static final String RESPONSE_LATENCY = "responseLatency"; - private static final String RESPONSE_MEDIATION_LATENCY = "responseMediationLatency"; - private final Timestamp currentTimestamp = new Timestamp(new Date().getTime()); - - @Test - public void createMetricReporter() throws MetricReportingException { - - MetricEventBuilder metricEventBuilder = new MockEventBuilder(); - - metricEventBuilder.addAttribute(CORRELATION_ID, UUID.randomUUID()); - metricEventBuilder.addAttribute(REQUEST_TIMESTAMP, currentTimestamp); - metricEventBuilder.addAttribute(BACKEND_LATENCY, 10); - metricEventBuilder.addAttribute(REQUEST_MEDIATION_LATENCY, 20); - metricEventBuilder.addAttribute(RESPONSE_LATENCY, 30); - metricEventBuilder.addAttribute(RESPONSE_MEDIATION_LATENCY, 40); - - OBTimestampPublisher obTimestampPublisher = new MockOBTimestampPublisher(metricEventBuilder); - obTimestampPublisher.run(); - } - - private void validateData(Map analyticsData) { - Assert.assertTrue(analyticsData.get(REQUEST_TIMESTAMP).equals(currentTimestamp)); - Assert.assertTrue(analyticsData.get(BACKEND_LATENCY).equals(10)); - Assert.assertTrue(analyticsData.get(REQUEST_MEDIATION_LATENCY).equals(20)); - Assert.assertTrue(analyticsData.get(RESPONSE_LATENCY).equals(30)); - Assert.assertTrue(analyticsData.get(RESPONSE_MEDIATION_LATENCY).equals(40)); - } - - class MockEventBuilder extends DefaultResponseMetricEventBuilder { - @Override - public boolean validate() throws MetricReportingException { - return true; - } - - @Override - protected Map buildEvent() { - this.eventMap.put("eventType", "response"); - String userAgentHeader = (String) this.eventMap.remove("userAgentHeader"); - return this.eventMap; - } - } - - class MockOBTimestampPublisher extends OBTimestampPublisher { - - public MockOBTimestampPublisher(MetricEventBuilder builder) { - - super(builder); - } - - @Override - protected void publishLatencyData(Map analyticsData) { - // validate - validateData(analyticsData); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/synapse/handler/DisputeResolutionSynapseHandlerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/synapse/handler/DisputeResolutionSynapseHandlerTest.java deleted file mode 100644 index 8b025734..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/synapse/handler/DisputeResolutionSynapseHandlerTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.synapse.handler; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import com.wso2.openbanking.accelerator.gateway.util.GatewayConstants; -import com.wso2.openbanking.accelerator.gateway.util.GatewayUtils; -import org.apache.axiom.om.OMElement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.synapse.MessageContext; -import org.apache.synapse.commons.json.JsonUtil; -import org.apache.synapse.config.SynapseConfiguration; -import org.apache.synapse.core.SynapseEnvironment; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.impl.APIConstants; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import javax.xml.parsers.ParserConfigurationException; - -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - - -/** - * Test for Dispute Resolution Synapse Handler. - */ -@PrepareForTest({OpenBankingConfigParser.class, OBDataPublisherUtil.class, JsonUtil.class, GatewayUtils.class}) -@PowerMockIgnore({"jdk.internal.reflect.*", "javax.management.*"}) -public class DisputeResolutionSynapseHandlerTest extends PowerMockTestCase { - private static final Log log = LogFactory.getLog(DisputeResolutionSynapseHandlerTest.class); - private static final String REQUEST_BODY = "requestBody"; - private Axis2MessageContext axis2MessageContextMock; - - Map sampleRequestHeaders = new HashMap<>(); - - DisputeResolutionSynapseHandler disputeResolutionSynapseHandler = new DisputeResolutionSynapseHandler(); - public DisputeResolutionSynapseHandlerTest() throws ParserConfigurationException, IOException { - - sampleRequestHeaders.put("Accept-Encoding", "gzip, deflate, br"); - sampleRequestHeaders.put("Access-Control-Allow-Headers", "authorization, Access-Control-Allow-Origin," + - " Content-Type, SOAPAction, apikey, Authorization"); - sampleRequestHeaders.put("Access-Control-Allow-Methods", "POST"); - sampleRequestHeaders.put("Access-Control-Allow-Origin", "*"); - sampleRequestHeaders.put("Access-Control-Expose-Headers", ""); - sampleRequestHeaders.put("Content-Type", "application/json"); - sampleRequestHeaders.put("WWW-Authenticate", "Internal API Key realm=\"WSO2 API Manager\"," + - " Bearer realm=\"WSO2 API Manager\", error=\"invalid_token\", error_description=\"The " + - "provided token is invalid\""); - } - - String sampleRequestBody = "{\"Data\":{\"Permissions\":[\"ReadAccountsDetail\",\"ReadTransactionsDetail\"," - + "\"ReadBalances\"]," - + "\"Risk\":{}}"; - String sampleResponseBody = "{\"code\": \"900902\"," + - "\"message\": \"Missing Credentials\"," + - "\"description\": \"Invalid Credentials." - + "Make sure your API invocation call has a header: " - + "'Authorization : Bearer ACCESS_TOKEN' or 'Authorization :" - + " Basic ACCESS_TOKEN' or 'apikey: API_KEY'\"}"; - - @BeforeClass - public void initClass() { - - MockitoAnnotations.initMocks(this); - - } - - @Test - public void testSynapseHandlerForResponseFlow() throws Exception { - - MessageContext messageContext = getResponseData(); - Assert.assertTrue(disputeResolutionSynapseHandler.handleResponseOutFlow(messageContext)); - } - @Test - public void testSynapseHandlerForRequestFlow() throws Exception { - - MessageContext messageContext = getRequestData(); - Assert.assertTrue(disputeResolutionSynapseHandler.handleRequestInFlow(messageContext)); - } - - - private MessageContext getResponseData() throws Exception { - - PowerMockito.mockStatic(GatewayUtils.class); - mockStatic(OpenBankingConfigParser.class); - OpenBankingConfigParser openBankingConfigParserMock = mock(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.doReturn(true).when(openBankingConfigParserMock).isDisputeResolutionEnabled(); - Mockito.doReturn(true).when(openBankingConfigParserMock) - .isNonErrorDisputeDataPublishingEnabled(); - - SynapseConfiguration synapseConfigurationMock = mock(SynapseConfiguration.class); - SynapseEnvironment synapseEnvironmentMock = mock(SynapseEnvironment.class); - org.apache.axis2.context.MessageContext messageContextMock = - mock(org.apache.axis2.context.MessageContext.class); - MessageContext messageContext = new Axis2MessageContext(messageContextMock, synapseConfigurationMock, - synapseEnvironmentMock); - - messageContext.setProperty(APIConstants.API_ELECTED_RESOURCE, "/register"); - messageContext.setProperty(GatewayConstants.HTTP_METHOD, "POST"); - messageContext.setProperty(GatewayConstants.UNKNOWN, "unknown"); - - when(GatewayUtils.buildMessagePayloadFromMessageContext(Mockito.anyObject(), Mockito.anyMap())) - .thenReturn(Optional.of(sampleResponseBody)); - - Map contextEntries = new HashMap<>(); - contextEntries.put(REQUEST_BODY, sampleRequestBody); - messageContext.setContextEntries(contextEntries); - - org.apache.axis2.context.MessageContext axis2MessageContext = new org.apache.axis2.context.MessageContext(); - axis2MessageContext.setProperty(GatewayConstants.HTTP_SC, 401); - axis2MessageContext.setProperty(org.apache.axis2.context.MessageContext - .TRANSPORT_HEADERS, sampleRequestHeaders); - ((Axis2MessageContext) messageContext).setAxis2MessageContext(axis2MessageContext); - - mockStatic(OBDataPublisherUtil.class); - doNothing().when(OBDataPublisherUtil.class, "publishData", Mockito.anyString(), Mockito.anyString(), - Mockito.anyObject()); - - mockStatic(JsonUtil.class); - OMElement omElementMock = mock(OMElement.class); - when(JsonUtil.getNewJsonPayload(Mockito.anyObject(), Mockito.anyString(), Mockito.anyBoolean(), - Mockito.anyBoolean())).thenReturn(omElementMock); - - return messageContext; - } - - private MessageContext getRequestData() throws Exception { - - PowerMockito.mockStatic(GatewayUtils.class); - mockStatic(OpenBankingConfigParser.class); - OpenBankingConfigParser openBankingConfigParserMock = mock(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - Mockito.doReturn(true).when(openBankingConfigParserMock).isDisputeResolutionEnabled(); - - SynapseConfiguration synapseConfigurationMock = mock(SynapseConfiguration.class); - SynapseEnvironment synapseEnvironmentMock = mock(SynapseEnvironment.class); - org.apache.axis2.context.MessageContext messageContextMock = - mock(org.apache.axis2.context.MessageContext.class); - MessageContext messageContext = new Axis2MessageContext(messageContextMock, synapseConfigurationMock, - synapseEnvironmentMock); - - org.apache.axis2.context.MessageContext axis2MessageContext = new org.apache.axis2.context.MessageContext(); - ((Axis2MessageContext) messageContext).setAxis2MessageContext(axis2MessageContext); - axis2MessageContext.setProperty(org.apache.axis2.context.MessageContext - .TRANSPORT_HEADERS, sampleRequestHeaders); - - mockStatic(JsonUtil.class); - OMElement omElementMock = mock(OMElement.class); - when(JsonUtil.getNewJsonPayload(Mockito.anyObject(), Mockito.anyString(), Mockito.anyBoolean(), - Mockito.anyBoolean())).thenReturn(omElementMock); - - when(GatewayUtils.buildMessagePayloadFromMessageContext(Mockito.anyObject(), Mockito.anyMap())) - .thenReturn(Optional.of(sampleRequestBody)); - return messageContext; - } - - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/throttling/OBThrottlingExtensionImplTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/throttling/OBThrottlingExtensionImplTest.java deleted file mode 100644 index 69bda5f4..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/throttling/OBThrottlingExtensionImplTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.throttling; - -import com.wso2.openbanking.accelerator.gateway.internal.GatewayDataHolder; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.common.gateway.dto.ExtensionResponseDTO; -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; - -/** - * Test for Open Banking throttling extension implementation. - */ -public class OBThrottlingExtensionImplTest { - - OBThrottlingExtensionImpl obThrottlingExtension; - RequestContextDTO requestContextDTO; - - @BeforeClass - public void beforeClass() { - - GatewayDataHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisherTestImpl()); - obThrottlingExtension = new OBThrottlingExtensionImpl(); - requestContextDTO = Mockito.mock(RequestContextDTO.class); - } - - @Test(priority = 1) - public void testAddCustomThrottlingKeys() { - - ExtensionResponseDTO extensionResponseDTO = obThrottlingExtension.preProcessRequest(requestContextDTO); - Assert.assertEquals(extensionResponseDTO.getCustomProperty().get("open"), "banking"); - Assert.assertEquals(extensionResponseDTO.getCustomProperty().get("wso2"), "ob"); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/throttling/ThrottleDataPublisherTestImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/throttling/ThrottleDataPublisherTestImpl.java deleted file mode 100644 index bce43d59..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/throttling/ThrottleDataPublisherTestImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.throttling; - -import org.wso2.carbon.apimgt.common.gateway.dto.RequestContextDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * Test for throttle data publisher implementation. - */ -public class ThrottleDataPublisherTestImpl implements ThrottleDataPublisher { - - @Override - public Map getCustomProperties(RequestContextDTO requestContextDTO) { - - Map customPropertyMap = new HashMap<>(); - customPropertyMap.put("open", "banking"); - customPropertyMap.put("wso2", "OB"); - return customPropertyMap; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/util/GatewayUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/util/GatewayUtilsTest.java deleted file mode 100644 index 9b2b195b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/java/com/wso2/openbanking/accelerator/gateway/util/GatewayUtilsTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.gateway.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.soap.SOAPBody; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.MessageContext; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpHeaders; -import org.apache.synapse.commons.json.JsonUtil; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.core.axis2.Axis2Sender; -import org.apache.synapse.transport.passthru.PassThroughConstants; -import org.apache.synapse.transport.passthru.util.RelayUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Optional; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -/** - * Utility methods used in gateway. - */ -@PrepareForTest({JsonUtil.class, IOUtils.class, RelayUtils.class, Axis2Sender.class}) -@PowerMockIgnore({"jdk.internal.reflect.*"}) -public class GatewayUtilsTest extends PowerMockTestCase { - - private MessageContext messageContext; - private HashMap headers = new HashMap<>(); - - @BeforeClass - public void init() { - - messageContext = Mockito.mock(MessageContext.class); - headers = new HashMap<>(); - doReturn(headers).when(messageContext).getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); - - } - - @Test(priority = 1) - public void testBuildMessagePayloadFromMessageContextForXML() throws OpenBankingException { - - doReturn(false).when(messageContext).getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(messageContext).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - OMElement element = Mockito.spy(OMElement.class); - doReturn(element).when(soapBody).getFirstElement(); - headers.put(HttpHeaders.CONTENT_TYPE, GatewayConstants.APPLICATION_XML_CONTENT_TYPE); - Optional payload = GatewayUtils.buildMessagePayloadFromMessageContext(messageContext, headers); - Assert.assertTrue(payload.isPresent()); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testBuildMessageErrorPayloadFromMessageContextForXML() throws Exception { - - PowerMockito.mockStatic(RelayUtils.class); - PowerMockito.doThrow(new IOException()).when(RelayUtils.class, "buildMessage", messageContext); - - doReturn(false).when(messageContext).getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(messageContext).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - OMElement element = Mockito.spy(OMElement.class); - doReturn(element).when(soapBody).getFirstElement(); - headers.put(HttpHeaders.CONTENT_TYPE, GatewayConstants.APPLICATION_XML_CONTENT_TYPE); - Optional payload = GatewayUtils.buildMessagePayloadFromMessageContext(messageContext, headers); - Assert.assertTrue(payload.isPresent()); - } - - @Test(priority = 1) - public void testBuildMessagePayloadFromMessageContextForJWT() throws OpenBankingException { - - doReturn(false).when(messageContext).getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(messageContext).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - OMElement element = Mockito.spy(OMElement.class); - doReturn(element).when(soapBody).getFirstElement(); - headers.put(HttpHeaders.CONTENT_TYPE, GatewayConstants.JWT_CONTENT_TYPE); - Optional payload = GatewayUtils.buildMessagePayloadFromMessageContext(messageContext, headers); - Assert.assertTrue(payload.isPresent()); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testNegativeBuildMessagePayloadFromMessageContextForJSON() throws Exception { - - PowerMockito.mockStatic(JsonUtil.class); - doReturn(false).when(messageContext).getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(messageContext).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - OMElement element = Mockito.spy(OMElement.class); - doReturn(element).when(soapBody).getFirstElement(); - headers.put(HttpHeaders.CONTENT_TYPE, GatewayConstants.JSON_CONTENT_TYPE); - PowerMockito.when(JsonUtil.getJsonPayload(messageContext)).thenReturn(Mockito.mock(InputStream.class)); - Optional payload = GatewayUtils.buildMessagePayloadFromMessageContext(messageContext, headers); - } - - @Test(priority = 1) - public void testBuildMessagePayloadFromMessageContextForJSON() throws Exception { - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - doReturn(false).when(messageContext).getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED); - SOAPEnvelope soapEnvelope = Mockito.spy(SOAPEnvelope.class); - doReturn(soapEnvelope).when(messageContext).getEnvelope(); - SOAPBody soapBody = Mockito.spy(SOAPBody.class); - doReturn(soapBody).when(soapEnvelope).getBody(); - OMElement element = Mockito.spy(OMElement.class); - doReturn(element).when(soapBody).getFirstElement(); - headers.put(HttpHeaders.CONTENT_TYPE, GatewayConstants.JSON_CONTENT_TYPE); - PowerMockito.when(JsonUtil.getJsonPayload(messageContext)).thenReturn( - new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8))); - Optional payload = GatewayUtils.buildMessagePayloadFromMessageContext(messageContext, headers); - Assert.assertFalse(payload.isPresent()); - } - - - @Test(priority = 1) - public void testReturnSynapseHandlerJSONError() throws Exception { - - Axis2MessageContext msgCtx = Mockito.mock(Axis2MessageContext.class); - PowerMockito.mockStatic(Axis2Sender.class); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.doReturn(mock(OMElement.class)).when(JsonUtil.class, "getNewJsonPayload", Mockito.any(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean()); - PowerMockito.doNothing().when(Axis2Sender.class, "sendBack", msgCtx); - doReturn(messageContext).when(msgCtx).getAxis2MessageContext(); - GatewayUtils.returnSynapseHandlerJSONError(msgCtx, "", ""); - } - - @Test(priority = 1) - public void testReturnSynapseHandlerJSONErrorWithAxisFault() throws Exception { - - PowerMockito.mockStatic(RelayUtils.class); - PowerMockito.doThrow(new AxisFault("")).when(RelayUtils.class, "discardRequestMessage", messageContext); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.doReturn(mock(OMElement.class)).when(JsonUtil.class, "getNewJsonPayload", Mockito.any(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean()); - Axis2MessageContext msgCtx = Mockito.mock(Axis2MessageContext.class); - PowerMockito.mockStatic(Axis2Sender.class); - PowerMockito.doNothing().when(Axis2Sender.class, "sendBack", msgCtx); - doReturn(messageContext).when(msgCtx).getAxis2MessageContext(); - GatewayUtils.returnSynapseHandlerJSONError(msgCtx, "", ""); - } - - @Test(priority = 1) - public void testReturnSynapseHandlerJSONErrorWithAxisFaultForJsonPayload() throws Exception { - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.doThrow(new AxisFault("")).when(JsonUtil.class, "getNewJsonPayload", Mockito.any(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean()); - Axis2MessageContext msgCtx = Mockito.mock(Axis2MessageContext.class); - PowerMockito.mockStatic(Axis2Sender.class); - PowerMockito.doNothing().when(Axis2Sender.class, "sendBack", msgCtx); - doReturn(messageContext).when(msgCtx).getAxis2MessageContext(); - GatewayUtils.returnSynapseHandlerJSONError(msgCtx, "", ""); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/client-truststore.jks b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/client-truststore.jks deleted file mode 100644 index 4672372b..00000000 Binary files a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/client-truststore.jks and /dev/null differ diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/open-banking.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/open-banking.xml deleted file mode 100644 index 19c1d17c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/open-banking.xml +++ /dev/null @@ -1,153 +0,0 @@ - - - - - - - - sampleDataSourceName - - - - - - - sampleRequestObjectValidator - - - - - - DummyValue - ${some.property} - - ${carbon.home} - - - - Nothing - Everything - Anything - - - - - - - - - - - - - - - - - - - - - - - - - false - - - - - true - - - - - - - - - - 3600 - 3600 - 86400 - - true - 3 - - - true - PROXY_HOSTNAME - 8080 - - - - - - - - - CN=Test Pre-Production Issuing CA, O=Test, C=GB - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - Sample - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/test_crl_entries.pem b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/test_crl_entries.pem deleted file mode 100644 index 846a2b17..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/test_crl_entries.pem +++ /dev/null @@ -1,1225 +0,0 @@ ------BEGIN X509 CRL----- -MILlNDCC5BwCAQEwDQYJKoZIhvcNAQELBQAwUzELMAkGA1UEBhMCR0IxFDASBgNV -BAoTC09wZW5CYW5raW5nMS4wLAYDVQQDEyVPcGVuQmFua2luZyBQcmUtUHJvZHVj -dGlvbiBJc3N1aW5nIENBFw0yMTAzMTUwNjM3NDdaFw0yMTAzMTgwNjM3NDdaMILj -YTAjAgRZxhtAFw0yMTAzMTAxNTAzNTdaMAwwCgYDVR0VBAMKAQUwIwIEWcYbPxcN -MjEwMzEwMTQ1OTA0WjAMMAoGA1UdFQQDCgEFMCMCBFnGGv4XDTIxMDMxMjE2Mzgx -OVowDDAKBgNVHRUEAwoBBTAjAgRZxhr9Fw0yMTAzMTIxNjM4MjRaMAwwCgYDVR0V -BAMKAQUwIwIEWcYayBcNMjEwMzA5MTAzNjU2WjAMMAoGA1UdFQQDCgEFMCMCBFnG -GhQXDTIxMDMwOTE0NTgxM1owDDAKBgNVHRUEAwoBBTAjAgRZxhoSFw0yMTAzMDkx -NDU4MDRaMAwwCgYDVR0VBAMKAQUwIwIEWcYaERcNMjEwMzA5MTQ1NzUyWjAMMAoG -A1UdFQQDCgEFMCMCBFnGGd0XDTIxMDMwNDE2MjQ0MVowDDAKBgNVHRUEAwoBBTAj -AgRZxhnaFw0yMTAzMDMxNDE5MzhaMAwwCgYDVR0VBAMKAQUwIwIEWcYZ2RcNMjEw -MzAzMTQxODUxWjAMMAoGA1UdFQQDCgEFMCMCBFnGGdgXDTIxMDMwMzE0MjIxMFow -DDAKBgNVHRUEAwoBBTAjAgRZxhnXFw0yMTAzMDMxNDIxMjlaMAwwCgYDVR0VBAMK -AQUwIwIEWcYZ1RcNMjEwMzAzMTQwNjA3WjAMMAoGA1UdFQQDCgEFMCMCBFnGGdQX -DTIxMDMwMzE0MDUyOVowDDAKBgNVHRUEAwoBBTAjAgRZxhnRFw0yMTAzMDMxMzU1 -MTBaMAwwCgYDVR0VBAMKAQUwIwIEWcYZqBcNMjEwMzAzMTM0NTA0WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGGacXDTIxMDMwMzEzNDM1N1owDDAKBgNVHRUEAwoBBTAjAgRZ -xhmmFw0yMTAzMDMxMzQ4MzBaMAwwCgYDVR0VBAMKAQUwIwIEWcYZpRcNMjEwMzAz -MTM0NzIzWjAMMAoGA1UdFQQDCgEFMCMCBFnGGaEXDTIxMDMwMzEzMDg1MFowDDAK -BgNVHRUEAwoBBTAjAgRZxhmgFw0yMTAzMDMxMzA2MTJaMAwwCgYDVR0VBAMKAQUw -IwIEWcYZnxcNMjEwMzAzMTMxNTE2WjAMMAoGA1UdFQQDCgEFMCMCBFnGGZ0XDTIx -MDMwMzEzMTIzOFowDDAKBgNVHRUEAwoBBTAjAgRZxhmYFw0yMTAzMDMxMjI4NDda -MAwwCgYDVR0VBAMKAQUwIwIEWcYZlxcNMjEwMzAzMTIyNTE5WjAMMAoGA1UdFQQD -CgEFMCMCBFnGGZIXDTIxMDMwMzExMzgyOVowDDAKBgNVHRUEAwoBBTAjAgRZxhmR -Fw0yMTAzMDMxMTM1NTFaMAwwCgYDVR0VBAMKAQUwIwIEWcYZjxcNMjEwMzAzMTE0 -MTIwWjAMMAoGA1UdFQQDCgEFMCMCBFnGGY0XDTIxMDMwMzExMDU1OVowDDAKBgNV -HRUEAwoBBTAjAgRZxhmMFw0yMTAzMDMxMTA0MjJaMAwwCgYDVR0VBAMKAQUwIwIE -WcYZihcNMjEwMzAzMTEwNzQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnGGX0XDTIxMDMw -MzEwMDMyM1owDDAKBgNVHRUEAwoBBTAjAgRZxhl8Fw0yMTAzMDMxMDAyMzFaMAww -CgYDVR0VBAMKAQUwIwIEWcYZehcNMjEwMzAzMTAwNDI3WjAMMAoGA1UdFQQDCgEF -MCMCBFnGGREXDTIxMDMwMTE2NDg0OFowDDAKBgNVHRUEAwoBBTAjAgRZxhkQFw0y -MTAzMDExNjQ4MTZaMAwwCgYDVR0VBAMKAQUwIwIEWcYY5xcNMjEwMzAzMTM1NjQ1 -WjAMMAoGA1UdFQQDCgEFMCMCBFnGGOYXDTIxMDMwMzEzNTYzN1owDDAKBgNVHRUE -AwoBBTAjAgRZxhjlFw0yMTAzMDMxMzQzNDBaMAwwCgYDVR0VBAMKAQUwIwIEWcYY -4RcNMjEwMjI4MTY1MjE5WjAMMAoGA1UdFQQDCgEFMCMCBFnGGFEXDTIxMDIyNTEw -NDIyM1owDDAKBgNVHRUEAwoBBTAjAgRZxhglFw0yMTAzMDIyMDM0MjVaMAwwCgYD -VR0VBAMKAQUwIwIEWcYYIhcNMjEwMzAyMjAzNDMyWjAMMAoGA1UdFQQDCgEFMCMC -BFnGGBQXDTIxMDMwMTEzNTgyM1owDDAKBgNVHRUEAwoBBTAjAgRZxhgQFw0yMTAz -MDExNDA3MzhaMAwwCgYDVR0VBAMKAQUwIwIEWcYYCBcNMjEwMjIzMjE0MDU3WjAM -MAoGA1UdFQQDCgEFMCMCBFnGGAcXDTIxMDIyMzIxNDAwNlowDDAKBgNVHRUEAwoB -BTAjAgRZxhgGFw0yMTAyMjUxMTIwMzdaMAwwCgYDVR0VBAMKAQUwIwIEWcYYBRcN -MjEwMjIzMjE0MjE0WjAMMAoGA1UdFQQDCgEFMCMCBFnGGAMXDTIxMDIyMzIxMjcw -OVowDDAKBgNVHRUEAwoBBTAjAgRZxhgCFw0yMTAyMjMyMTI2MTVaMAwwCgYDVR0V -BAMKAQUwIwIEWcYYARcNMjEwMjI1MTExNzA5WjAMMAoGA1UdFQQDCgEFMCMCBFnG -GAAXDTIxMDIyNTExMTcxMVowDDAKBgNVHRUEAwoBBTAjAgRZxhf+Fw0yMTAyMjUx -MTA5MDlaMAwwCgYDVR0VBAMKAQUwIwIEWcYX/RcNMjEwMjI1MTEwOTA3WjAMMAoG -A1UdFQQDCgEFMCMCBFnGF/wXDTIxMDIyNTExMTcwMFowDDAKBgNVHRUEAwoBBTAj -AgRZxhf7Fw0yMTAyMjUxMTE3MDZaMAwwCgYDVR0VBAMKAQUwIwIEWcYX+BcNMjEw -MjIzMjEwMDI2WjAMMAoGA1UdFQQDCgEFMCMCBFnGF/cXDTIxMDIyMzIwNTkzMFow -DDAKBgNVHRUEAwoBBTAjAgRZxhf2Fw0yMTAyMjUxMTI3MDhaMAwwCgYDVR0VBAMK -AQUwIwIEWcYX9RcNMjEwMjI1MTEyNzAwWjAMMAoGA1UdFQQDCgEFMCMCBFnGF/MX -DTIxMDIyMzIwNDM0MVowDDAKBgNVHRUEAwoBBTAjAgRZxhfyFw0yMTAyMjMyMDQy -NDNaMAwwCgYDVR0VBAMKAQUwIwIEWcYX8RcNMjEwMjI1MTExNjQ3WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGF/AXDTIxMDIyMzIwNDQ1OVowDDAKBgNVHRUEAwoBBTAjAgRZ -xhfuFw0yMTAyMjMyMDI2MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcYX7RcNMjEwMjIz -MjAyNTEwWjAMMAoGA1UdFQQDCgEFMCMCBFnGF+wXDTIxMDIyNTExMTY0MlowDDAK -BgNVHRUEAwoBBTAjAgRZxhfrFw0yMTAyMjMyMDI3MjVaMAwwCgYDVR0VBAMKAQUw -IwIEWcYXvhcNMjEwMjI1MTExNjM4WjAMMAoGA1UdFQQDCgEFMCMCBFnGF70XDTIx -MDIyNTExMTYzNFowDDAKBgNVHRUEAwoBBTAjAgRZxhdlFw0yMTAyMjUxMTE2MzFa -MAwwCgYDVR0VBAMKAQUwIwIEWcYXZBcNMjEwMjI1MTExNjI4WjAMMAoGA1UdFQQD -CgEFMCMCBFnGF14XDTIxMDIyMjA3MjUxOVowDDAKBgNVHRUEAwoBBTAjAgRZxhbT -Fw0yMTAyMTkwNjMxMjZaMAwwCgYDVR0VBAMKAQUwIwIEWcYWqRcNMjEwMjE4MTQ1 -ODA1WjAMMAoGA1UdFQQDCgEFMCMCBFnGFmcXDTIxMDIxNzEwMTEwN1owDDAKBgNV -HRUEAwoBBTAjAgRZxhWZFw0yMTAzMDExNjM3MjdaMAwwCgYDVR0VBAMKAQUwIwIE -WcYVkRcNMjEwMjEyMTE1MjAyWjAMMAoGA1UdFQQDCgEFMCMCBFnGFZAXDTIxMDIx -MjExNTAzNFowDDAKBgNVHRUEAwoBBTAjAgRZxhWOFw0yMTAyMTIxMTIyNTFaMAww -CgYDVR0VBAMKAQUwIwIEWcYVjRcNMjEwMjEyMTEyMTMwWjAMMAoGA1UdFQQDCgEF -MCMCBFnGFYwXDTIxMDIxMjExMjYyMFowDDAKBgNVHRUEAwoBBTAjAgRZxhWLFw0y -MTAyMTIxMTI0NTVaMAwwCgYDVR0VBAMKAQUwIwIEWcYVihcNMjEwMjI1MTExNjI0 -WjAMMAoGA1UdFQQDCgEFMCMCBFnGFYkXDTIxMDIyNTExMTYyMFowDDAKBgNVHRUE -AwoBBTAjAgRZxhWHFw0yMTAyMTIxMTAwMjZaMAwwCgYDVR0VBAMKAQUwIwIEWcYV -hhcNMjEwMjEyMTEwMDIzWjAMMAoGA1UdFQQDCgEFMCMCBFnGFYQXDTIxMDIyNTEx -Mzk0OFowDDAKBgNVHRUEAwoBBTAjAgRZxhWDFw0yMTAyMTIxMTAwMzJaMAwwCgYD -VR0VBAMKAQUwIwIEWcYVghcNMjEwMjEyMTEwMDI4WjAMMAoGA1UdFQQDCgEFMCMC -BFnGFYEXDTIxMDIyNTExMzk0NlowDDAKBgNVHRUEAwoBBTAjAgRZxhWAFw0yMTAy -MjUxMTE2MTZaMAwwCgYDVR0VBAMKAQUwIwIEWcYVfxcNMjEwMjI1MTExNjEzWjAM -MAoGA1UdFQQDCgEFMCMCBFnGFX4XDTIxMDIxMjEwNTM1MVowDDAKBgNVHRUEAwoB -BTAjAgRZxhV8Fw0yMTAyMTIxMDUzNDZaMAwwCgYDVR0VBAMKAQUwIwIEWcYVexcN -MjEwMjEyMTA1MzU1WjAMMAoGA1UdFQQDCgEFMCMCBFnGFXoXDTIxMDIyNTExMTYw -OFowDDAKBgNVHRUEAwoBBTAjAgRZxhV5Fw0yMTAyMTIxMDUzNTBaMAwwCgYDVR0V -BAMKAQUwIwIEWcYVeBcNMjEwMjI1MTExNjA1WjAMMAoGA1UdFQQDCgEFMCMCBFnG -FXYXDTIxMDIyNTExMzk0M1owDDAKBgNVHRUEAwoBBTAjAgRZxhV1Fw0yMTAyMTIx -MDUzNDNaMAwwCgYDVR0VBAMKAQUwIwIEWcYVdBcNMjEwMjI1MTEzOTQxWjAMMAoG -A1UdFQQDCgEFMCMCBFnGFXMXDTIxMDIyNTExMTYwMVowDDAKBgNVHRUEAwoBBTAj -AgRZxhVyFw0yMTAyMjUxMTE1NThaMAwwCgYDVR0VBAMKAQUwIwIEWcYVcRcNMjEw -MjEyMTA0MzU5WjAMMAoGA1UdFQQDCgEFMCMCBFnGFXAXDTIxMDIxMjEwNDM1NVow -DDAKBgNVHRUEAwoBBTAjAgRZxhVuFw0yMTAyMjUxMTA4NTdaMAwwCgYDVR0VBAMK -AQUwIwIEWcYVbRcNMjEwMjI1MTEwODU1WjAMMAoGA1UdFQQDCgEFMCMCBFnGFWwX -DTIxMDIyNTExMTU1NFowDDAKBgNVHRUEAwoBBTAjAgRZxhVrFw0yMTAyMjUxMTE1 -NTFaMAwwCgYDVR0VBAMKAQUwIwIEWcYVahcNMjEwMjE4MTAxMzM0WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGFWkXDTIxMDIxODEwMTM0M1owDDAKBgNVHRUEAwoBBTAjAgRZ -xhVoFw0yMTAyMjUxMTE1NDdaMAwwCgYDVR0VBAMKAQUwIwIEWcYVZxcNMjEwMjI1 -MTExNTQxWjAMMAoGA1UdFQQDCgEFMCMCBFnGFWYXDTIxMDIyNTExMTUzN1owDDAK -BgNVHRUEAwoBBTAjAgRZxhUDFw0yMTAyMTAwMDU5NTFaMAwwCgYDVR0VBAMKAQUw -IwIEWcYVAhcNMjEwMjEwMDA1OTQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnGFQEXDTIx -MDIxMDAxMDAwMlowDDAKBgNVHRUEAwoBBTAjAgRZxhUAFw0yMTAyMTAwMDU5NTda -MAwwCgYDVR0VBAMKAQUwIwIEWcYU/xcNMjEwMjI1MTIwMTU0WjAMMAoGA1UdFQQD -CgEFMCMCBFnGFP4XDTIxMDIyNTEyMDIwNFowDDAKBgNVHRUEAwoBBTAjAgRZxhT9 -Fw0yMTAyMTAwMDU2MjJaMAwwCgYDVR0VBAMKAQUwIwIEWcYU/BcNMjEwMjEwMDA1 -NjE2WjAMMAoGA1UdFQQDCgEFMCMCBFnGFPoXDTIxMDIxMDAwNDQyOFowDDAKBgNV -HRUEAwoBBTAjAgRZxhT5Fw0yMTAyMTAwMDQ0MjVaMAwwCgYDVR0VBAMKAQUwIwIE -WcYU+BcNMjEwMjEwMDA0NDM2WjAMMAoGA1UdFQQDCgEFMCMCBFnGFPcXDTIxMDIx -MDAwNDQzMlowDDAKBgNVHRUEAwoBBTAjAgRZxhT1Fw0yMTAyMTAwMDM3MTRaMAww -CgYDVR0VBAMKAQUwIwIEWcYU9BcNMjEwMjEwMDAzNzEyWjAMMAoGA1UdFQQDCgEF -MCMCBFnGFPMXDTIxMDIxODEwMTM1NlowDDAKBgNVHRUEAwoBBTAjAgRZxhTyFw0y -MTAyMTgxMDEzNTlaMAwwCgYDVR0VBAMKAQUwIwIEWcYU8BcNMjEwMjEwMDAyNjUx -WjAMMAoGA1UdFQQDCgEFMCMCBFnGFO8XDTIxMDIxMDAwMjY0OVowDDAKBgNVHRUE -AwoBBTAjAgRZxhTtFw0yMTAyMTcxMDE2MDFaMAwwCgYDVR0VBAMKAQUwIwIEWcYU -7BcNMjEwMjE3MTAxNTU4WjAMMAoGA1UdFQQDCgEFMCMCBFnGFOsXDTIxMDIxNzEw -MTYxMVowDDAKBgNVHRUEAwoBBTAjAgRZxhTqFw0yMTAyMTAwMDEwMjhaMAwwCgYD -VR0VBAMKAQUwIwIEWcYU6BcNMjEwMjEwMDAxMDI0WjAMMAoGA1UdFQQDCgEFMCMC -BFnGFOcXDTIxMDIxMDAwMTAzNVowDDAKBgNVHRUEAwoBBTAjAgRZxhTmFw0yMTAy -MTAwMDEwMzNaMAwwCgYDVR0VBAMKAQUwIwIEWcYU5RcNMjEwMjI1MTEwOTM1WjAM -MAoGA1UdFQQDCgEFMCMCBFnGFOQXDTIxMDIyNTExMTUzM1owDDAKBgNVHRUEAwoB -BTAjAgRZxhTjFw0yMTAyMjUxMTE1MzBaMAwwCgYDVR0VBAMKAQUwIwIEWcYU4hcN -MjEwMjI1MTExNTI2WjAMMAoGA1UdFQQDCgEFMCMCBFnGFOEXDTIxMDIyNTExMTUy -M1owDDAKBgNVHRUEAwoBBTAjAgRZxhTgFw0yMTAyMjUxMTE1MTlaMAwwCgYDVR0V -BAMKAQUwIwIEWcYU3xcNMjEwMjI1MTExNTE1WjAMMAoGA1UdFQQDCgEFMCMCBFnG -FN0XDTIxMDIwOTIzNDkzN1owDDAKBgNVHRUEAwoBBTAjAgRZxhTcFw0yMTAyMDky -MzQ5MzVaMAwwCgYDVR0VBAMKAQUwIwIEWcYU2xcNMjEwMjI1MTExNTExWjAMMAoG -A1UdFQQDCgEFMCMCBFnGFNoXDTIxMDIyNTExMTUwN1owDDAKBgNVHRUEAwoBBTAj -AgRZxhTYFw0yMTAyMDkyMzQxMjhaMAwwCgYDVR0VBAMKAQUwIwIEWcYU1xcNMjEw -MjA5MjM0MDQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnGFNUXDTIxMDIwOTIzMzEwMlow -DDAKBgNVHRUEAwoBBTAjAgRZxhTUFw0yMTAyMDkyMzMwMTlaMAwwCgYDVR0VBAMK -AQUwIwIEWcYU0xcNMjEwMjA5MjMzMjQxWjAMMAoGA1UdFQQDCgEFMCMCBFnGFNIX -DTIxMDIwOTIzMzIwMlowDDAKBgNVHRUEAwoBBTAjAgRZxhTRFw0yMTAyMjUxMTE1 -MDRaMAwwCgYDVR0VBAMKAQUwIwIEWcYU0BcNMjEwMjI1MTExNDU0WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGFM8XDTIxMDIyNTExMTQ1MFowDDAKBgNVHRUEAwoBBTAjAgRZ -xhTNFw0yMTAyMDkyMzE2MzJaMAwwCgYDVR0VBAMKAQUwIwIEWcYUzBcNMjEwMjA5 -MjMxNTQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnGFMoXDTIxMDIwOTIzMDk0NlowDDAK -BgNVHRUEAwoBBTAjAgRZxhTJFw0yMTAyMDkyMzA5MDJaMAwwCgYDVR0VBAMKAQUw -IwIEWcYUxxcNMjEwMjA5MjI1MzQwWjAMMAoGA1UdFQQDCgEFMCMCBFnGFMYXDTIx -MDIwOTIyNTI1N1owDDAKBgNVHRUEAwoBBTAjAgRZxhTFFw0yMTAyMDkyMjU1NDFa -MAwwCgYDVR0VBAMKAQUwIwIEWcYUxBcNMjEwMjA5MjI1NDUzWjAMMAoGA1UdFQQD -CgEFMCMCBFnGFMIXDTIxMDIwOTIyMzU0MVowDDAKBgNVHRUEAwoBBTAjAgRZxhTB -Fw0yMTAyMDkyMjM0NTdaMAwwCgYDVR0VBAMKAQUwIwIEWcYUwBcNMjEwMjA5MjIz -NzU0WjAMMAoGA1UdFQQDCgEFMCMCBFnGFL8XDTIxMDIwOTIyMzY1M1owDDAKBgNV -HRUEAwoBBTAjAgRZxhS+Fw0yMTAyMjUxMTE0NDZaMAwwCgYDVR0VBAMKAQUwIwIE -WcYUvRcNMjEwMjI1MTExNDQzWjAMMAoGA1UdFQQDCgEFMCMCBFnGFLwXDTIxMDIy -NTExMTQzOVowDDAKBgNVHRUEAwoBBTAjAgRZxhS7Fw0yMTAyMjUxMTE0MzRaMAww -CgYDVR0VBAMKAQUwIwIEWcYUuRcNMjEwMjE3MDkyMTQ3WjAMMAoGA1UdFQQDCgEF -MCMCBFnGFLgXDTIxMDIxNzA5MjEzN1owDDAKBgNVHRUEAwoBBTAjAgRZxhS3Fw0y -MTAyMjUxMTE0MzFaMAwwCgYDVR0VBAMKAQUwIwIEWcYUtRcNMjEwMjE3MDkwMTEy -WjAMMAoGA1UdFQQDCgEFMCMCBFnGFLQXDTIxMDIxNzA5MDA1NlowDDAKBgNVHRUE -AwoBBTAjAgRZxhSzFw0yMTAyMTcxMDE2MDhaMAwwCgYDVR0VBAMKAQUwIwIEWcYU -hxcNMjEwMjA4MjAxNTM5WjAMMAoGA1UdFQQDCgEFMCMCBFnGFIYXDTIxMDIwODIw -MTUzMlowDDAKBgNVHRUEAwoBBTAjAgRZxhSEFw0yMTAyMDgyMDEyMzZaMAwwCgYD -VR0VBAMKAQUwIwIEWcYUgxcNMjEwMjA4MjAxMjIxWjAMMAoGA1UdFQQDCgEFMCMC -BFnGFF0XDTIxMDIwODIwMTMwOVowDDAKBgNVHRUEAwoBBTAjAgRZxhRcFw0yMTAy -MDgyMDEyNDZaMAwwCgYDVR0VBAMKAQUwIwIEWcYUWxcNMjEwMjA4MjAxNTM3WjAM -MAoGA1UdFQQDCgEFMCMCBFnGFFoXDTIxMDIwODIwMTUzMFowDDAKBgNVHRUEAwoB -BTAjAgRZxhRYFw0yMTAyMDgxNTUwNTFaMAwwCgYDVR0VBAMKAQUwIwIEWcYUVxcN -MjEwMjA4MTU1MDMwWjAMMAoGA1UdFQQDCgEFMCMCBFnGFFUXDTIxMDIwODE1NDY0 -NlowDDAKBgNVHRUEAwoBBTAjAgRZxhRUFw0yMTAyMDgxNTQ2MjhaMAwwCgYDVR0V -BAMKAQUwIwIEWcYUUxcNMjEwMjA4MTMzNTU5WjAMMAoGA1UdFQQDCgEFMCMCBFnG -FEUXDTIxMDIwODEwMzAyMlowDDAKBgNVHRUEAwoBBTAjAgRZxhO/Fw0yMTAyMDgw -OTA5NTdaMAwwCgYDVR0VBAMKAQUwIwIEWcYTRRcNMjEwMjAzMTI0ODQ3WjAMMAoG -A1UdFQQDCgEFMCMCBFnGE0QXDTIxMDIwMzEyNDgzNFowDDAKBgNVHRUEAwoBBTAj -AgRZxhNCFw0yMTAyMjUxMTE0MjdaMAwwCgYDVR0VBAMKAQUwIwIEWcYTQRcNMjEw -MjI1MTExNDIzWjAMMAoGA1UdFQQDCgEFMCMCBFnGEz8XDTIxMDIyNTExMTA1MVow -DDAKBgNVHRUEAwoBBTAjAgRZxhM+Fw0yMTAyMjUxMTEwNDlaMAwwCgYDVR0VBAMK -AQUwIwIEWcYTPRcNMjEwMjI1MTExNDE5WjAMMAoGA1UdFQQDCgEFMCMCBFnGEzwX -DTIxMDIyNTExMTQxNVowDDAKBgNVHRUEAwoBBTAjAgRZxhM6Fw0yMTAyMjUxMTA2 -MzNaMAwwCgYDVR0VBAMKAQUwIwIEWcYTORcNMjEwMjI1MTEwNjI5WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGEzgXDTIxMDIyNTExMTQxMVowDDAKBgNVHRUEAwoBBTAjAgRZ -xhM3Fw0yMTAyMjUxMTE0MDhaMAwwCgYDVR0VBAMKAQUwIwIEWcYTNRcNMjEwMjI1 -MTExMjE0WjAMMAoGA1UdFQQDCgEFMCMCBFnGEzQXDTIxMDIyNTExMTIxM1owDDAK -BgNVHRUEAwoBBTAjAgRZxhMzFw0yMTAyMDMwODUyMDBaMAwwCgYDVR0VBAMKAQUw -IwIEWcYTMhcNMjEwMjAzMDg1MDQwWjAMMAoGA1UdFQQDCgEFMCMCBFnGEzAXDTIx -MDIwMzA4NDkzNlowDDAKBgNVHRUEAwoBBTAjAgRZxhMvFw0yMTAyMDMwODQ4MjBa -MAwwCgYDVR0VBAMKAQUwIwIEWcYTLhcNMjEwMjI1MTExNDA0WjAMMAoGA1UdFQQD -CgEFMCMCBFnGEy0XDTIxMDIyNTExMTQwMFowDDAKBgNVHRUEAwoBBTAjAgRZxhMr -Fw0yMTAyMDMwODM1MzNaMAwwCgYDVR0VBAMKAQUwIwIEWcYTKhcNMjEwMjAzMDgz -NDQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnGEykXDTIxMDIwMzA4MjM1NFowDDAKBgNV -HRUEAwoBBTAjAgRZxhMoFw0yMTAyMDMwODIyNDJaMAwwCgYDVR0VBAMKAQUwIwIE -WcYTJhcNMjEwMjAzMDgyMTM4WjAMMAoGA1UdFQQDCgEFMCMCBFnGEyUXDTIxMDIw -MzA4MjAyNVowDDAKBgNVHRUEAwoBBTAjAgRZxhMkFw0yMTAyMjUxMTEzNTZaMAww -CgYDVR0VBAMKAQUwIwIEWcYTIxcNMjEwMjI1MTExMzUxWjAMMAoGA1UdFQQDCgEF -MCMCBFnGEyEXDTIxMDIyNTExMTAzOVowDDAKBgNVHRUEAwoBBTAjAgRZxhMgFw0y -MTAyMjUxMTEwMzdaMAwwCgYDVR0VBAMKAQUwIwIEWcYTHhcNMjEwMjI1MTExNzMy -WjAMMAoGA1UdFQQDCgEFMCMCBFnGEx0XDTIxMDIyNTExMDcyOFowDDAKBgNVHRUE -AwoBBTAjAgRZxhMcFw0yMTAyMjUxMTEzNDhaMAwwCgYDVR0VBAMKAQUwIwIEWcYT -GxcNMjEwMjI1MTExMzQyWjAMMAoGA1UdFQQDCgEFMCMCBFnGExkXDTIxMDIyNTEx -Mzc0NlowDDAKBgNVHRUEAwoBBTAjAgRZxhMYFw0yMTAyMjUxMTM3NDRaMAwwCgYD -VR0VBAMKAQUwIwIEWcYTFxcNMjEwMjI1MTExMzM4WjAMMAoGA1UdFQQDCgEFMCMC -BFnGExYXDTIxMDIyNTExMTMzNFowDDAKBgNVHRUEAwoBBTAjAgRZxhMUFw0yMTAy -MjUxMTE2MzFaMAwwCgYDVR0VBAMKAQUwIwIEWcYTExcNMjEwMjI1MTExNjI5WjAM -MAoGA1UdFQQDCgEFMCMCBFnGEw0XDTIxMDIwMzEyNDgyMFowDDAKBgNVHRUEAwoB -BTAjAgRZxhMMFw0yMTAyMDMxMjQ3NTlaMAwwCgYDVR0VBAMKAQUwIwIEWcYTCBcN -MjEwMjAyMTk0MzM5WjAMMAoGA1UdFQQDCgEFMCMCBFnGEtUXDTIxMDIwMzEyNDcz -OFowDDAKBgNVHRUEAwoBBTAjAgRZxhLUFw0yMTAyMDMxMjQ3MjBaMAwwCgYDVR0V -BAMKAQUwIwIEWcYSoBcNMjEwMjI1MTIwMjM2WjAMMAoGA1UdFQQDCgEFMCMCBFnG -EbEXDTIxMDEyNjIwMjc0NlowDDAKBgNVHRUEAwoBBTAjAgRZxhGwFw0yMTAxMjYy -MDI2MjhaMAwwCgYDVR0VBAMKAQUwIwIEWcYRrhcNMjEwMTI2MjAyNTE5WjAMMAoG -A1UdFQQDCgEFMCMCBFnGEa0XDTIxMDEyNjIwMjQzNVowDDAKBgNVHRUEAwoBBTAj -AgRZxhGsFw0yMTAxMjYyMDExNTlaMAwwCgYDVR0VBAMKAQUwIwIEWcYRqxcNMjEw -MTI2MjAxMDQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnGEakXDTIxMDEyNjIwMDkzOVow -DDAKBgNVHRUEAwoBBTAjAgRZxhGoFw0yMTAxMjYyMDA4NTBaMAwwCgYDVR0VBAMK -AQUwIwIEWcYRpxcNMjEwMjI1MTEzNzMxWjAMMAoGA1UdFQQDCgEFMCMCBFnGEXsX -DTIxMDIyNTExMTMzMFowDDAKBgNVHRUEAwoBBTAjAgRZxhF6Fw0yMTAyMjUxMTEz -MjZaMAwwCgYDVR0VBAMKAQUwIwIEWcYReBcNMjEwMjI1MTExMzU0WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGEXcXDTIxMDIyNTExMTM1MlowDDAKBgNVHRUEAwoBBTAjAgRZ -xhFwFw0yMTAyMjUxMTEzMjJaMAwwCgYDVR0VBAMKAQUwIwIEWcYRbxcNMjEwMjI1 -MTExMzE4WjAMMAoGA1UdFQQDCgEFMCMCBFnGEW0XDTIxMDIyNTExMTYyN1owDDAK -BgNVHRUEAwoBBTAjAgRZxhFsFw0yMTAxMjYxMTU1MjRaMAwwCgYDVR0VBAMKAQUw -IwIEWcYRaxcNMjEwMjI1MTEyMDM0WjAMMAoGA1UdFQQDCgEFMCMCBFnGEWoXDTIx -MDIyNTExMTc0NFowDDAKBgNVHRUEAwoBBTAjAgRZxhFoFw0yMTAyMjUxMTM5MjZa -MAwwCgYDVR0VBAMKAQUwIwIEWcYRZxcNMjEwMjI1MTEzOTI0WjAMMAoGA1UdFQQD -CgEFMCMCBFnGEWYXDTIxMDIyNTExMTc0MVowDDAKBgNVHRUEAwoBBTAjAgRZxhFk -Fw0yMTAyMjUxMTA2NTdaMAwwCgYDVR0VBAMKAQUwIwIEWcYRYxcNMjEwMjI1MTEw -NjU2WjAMMAoGA1UdFQQDCgEFMCMCBFnGEWIXDTIxMDIyNTExMTczOFowDDAKBgNV -HRUEAwoBBTAjAgRZxhFhFw0yMTAyMjUxMTE3MzVaMAwwCgYDVR0VBAMKAQUwIwIE -WcYRMRcNMjEwMTI1MTQwMjU2WjAMMAoGA1UdFQQDCgEFMCMCBFnGEJ8XDTIxMDMw -MTE2MzY0OVowDDAKBgNVHRUEAwoBBTAjAgRZxhB3Fw0yMTAxMjEyMjQ3MzJaMAww -CgYDVR0VBAMKAQUwIwIEWcYQaRcNMjEwMTIxMTQ1MzQxWjAMMAoGA1UdFQQDCgEF -MCMCBFnGEDoXDTIxMDEyNDIwMTY1NlowDDAKBgNVHRUEAwoBBTAjAgRZxg/PFw0y -MTAyMjUxNzI2NTFaMAwwCgYDVR0VBAMKAQUwIwIEWcYPyhcNMjEwMjA5MTcxOTUy -WjAMMAoGA1UdFQQDCgEGMCMCBFnGD8gXDTIxMDIwOTE3MjA0NlowDDAKBgNVHRUE -AwoBBjAjAgRZxg/HFw0yMTAyMDkxNzIxMjhaMAwwCgYDVR0VBAMKAQYwIwIEWcYP -ORcNMjEwMTE1MTUzMDA1WjAMMAoGA1UdFQQDCgEFMCMCBFnGDzgXDTIxMDExNTE1 -Mjk0MFowDDAKBgNVHRUEAwoBBTAjAgRZxg79Fw0yMTAxMTQxMjM3MDFaMAwwCgYD -VR0VBAMKAQUwIwIEWcYO8BcNMjEwMTE0MDk0MjQ0WjAMMAoGA1UdFQQDCgEFMCMC -BFnGDu8XDTIxMDExNDA5NDEyM1owDDAKBgNVHRUEAwoBBTAjAgRZxg7tFw0yMTAx -MTQwOTQwMjBaMAwwCgYDVR0VBAMKAQUwIwIEWcYO7BcNMjEwMTE0MDkzOTMyWjAM -MAoGA1UdFQQDCgEFMCMCBFnGDusXDTIxMDIyNTExMTE1NFowDDAKBgNVHRUEAwoB -BTAjAgRZxg7qFw0yMTAxMTQwOTI0NDJaMAwwCgYDVR0VBAMKAQUwIwIEWcYO6RcN -MjEwMTE0MDkyMzIzWjAMMAoGA1UdFQQDCgEFMCMCBFnGDucXDTIxMDExNDA5MjE0 -MFowDDAKBgNVHRUEAwoBBTAjAgRZxg7mFw0yMTAxMTQwOTIwNTFaMAwwCgYDVR0V -BAMKAQUwIwIEWcYOuhcNMjEwMjA5MTcyMjE2WjAMMAoGA1UdFQQDCgEGMCMCBFnG -DrkXDTIxMDIwOTE3MjMxN1owDDAKBgNVHRUEAwoBBjAjAgRZxg60Fw0yMTAxMTMx -NDIxMzlaMAwwCgYDVR0VBAMKAQUwIwIEWcYOeRcNMjEwMTE5MTAwMzUyWjAMMAoG -A1UdFQQDCgEFMCMCBFnGDncXDTIxMDExMjIyMjc1NFowDDAKBgNVHRUEAwoBBTAj -AgRZxg5fFw0yMTAyMjUxNzI2NTBaMAwwCgYDVR0VBAMKAQUwIwIEWcYOXRcNMjEw -MjE3MTM0NTA4WjAMMAoGA1UdFQQDCgEFMCMCBFnGDlwXDTIxMDIxNzEzNDUzNVow -DDAKBgNVHRUEAwoBBTAjAgRZxg5aFw0yMTAxMTIxMTM1NDlaMAwwCgYDVR0VBAMK -AQUwIwIEWcYOWRcNMjEwMTEyMTEwMzU3WjAMMAoGA1UdFQQDCgEFMCMCBFnGDk0X -DTIxMDExMjA4NDUxMlowDDAKBgNVHRUEAwoBBTAjAgRZxg5MFw0yMTAxMTIwODA2 -MjVaMAwwCgYDVR0VBAMKAQUwIwIEWcYOSxcNMjEwMTEyMDcyMDIyWjAMMAoGA1Ud -FQQDCgEFMCMCBFnGDiUXDTIxMDExMTE1Mjc1NlowDDAKBgNVHRUEAwoBBTAjAgRZ -xg4hFw0yMTAxMTExNDU2NTZaMAwwCgYDVR0VBAMKAQUwIwIEWcYOHxcNMjEwMTEx -MTQ1NDQwWjAMMAoGA1UdFQQDCgEFMCMCBFnGDhYXDTIxMDExMjE2MDM1MFowDDAK -BgNVHRUEAwoBBTAjAgRZxg4VFw0yMTAxMTIxNjAzNDBaMAwwCgYDVR0VBAMKAQUw -IwIEWcYN6RcNMjEwMTI0MjAxNjM3WjAMMAoGA1UdFQQDCgEFMCMCBFnGDYsXDTIx -MDEwODIyMTQ1NlowDDAKBgNVHRUEAwoBBTAjAgRZxg2KFw0yMTAxMDgyMjE0NTNa -MAwwCgYDVR0VBAMKAQUwIwIEWcYNRhcNMjEwMTEyMTMwNzI1WjAMMAoGA1UdFQQD -CgEFMCMCBFnGDUQXDTIxMDExMjEzMDczOVowDDAKBgNVHRUEAwoBBTAjAgRZxgww -Fw0yMTAxMjQyMDE2MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcYMBxcNMjAxMjMxMTYy -OTM3WjAMMAoGA1UdFQQDCgEFMCMCBFnGC9sXDTIxMDIyNTE4MDAxMVowDDAKBgNV -HRUEAwoBBTAjAgRZxgvaFw0yMTAyMjUxODAwMDNaMAwwCgYDVR0VBAMKAQUwIwIE -WcYL1hcNMjEwMTA3MTY0ODI1WjAMMAoGA1UdFQQDCgEFMCMCBFnGC9UXDTIxMDEw -NzE2NDgzNFowDDAKBgNVHRUEAwoBBTAjAgRZxguAFw0yMTAyMDgwOTA5MzRaMAww -CgYDVR0VBAMKAQUwIwIEWcYKpxcNMjAxMjMwMTUwNzM5WjAMMAoGA1UdFQQDCgEF -MCMCBFnGCqYXDTIwMTIzMDE1MDcyOFowDDAKBgNVHRUEAwoBBTAjAgRZxgp7Fw0y -MTAyMDQxNjAxMTVaMAwwCgYDVR0VBAMKAQUwIwIEWcYKeBcNMjEwMjA0MTYwMDUx -WjAMMAoGA1UdFQQDCgEFMCMCBFnGCnQXDTIxMDIwNDE2MDAxOFowDDAKBgNVHRUE -AwoBBTAjAgRZxgptFw0yMTAxMDgyMjE0NDhaMAwwCgYDVR0VBAMKAQUwIwIEWcYK -RxcNMjAxMjIxMjMyMDI0WjAMMAoGA1UdFQQDCgEFMCMCBFnGCkYXDTIwMTIyMTIy -MzMzMlowDDAKBgNVHRUEAwoBBTAjAgRZxgpFFw0yMDEyMjEyMTE3NDRaMAwwCgYD -VR0VBAMKAQUwIwIEWcYKRBcNMjAxMjIxMjExMTU0WjAMMAoGA1UdFQQDCgEFMCMC -BFnGCkMXDTIwMTIyMTIxMDY0MVowDDAKBgNVHRUEAwoBBTAjAgRZxgpCFw0yMDEy -MjExNzUwNDdaMAwwCgYDVR0VBAMKAQUwIwIEWcYKQBcNMjAxMjIxMTczMzAwWjAM -MAoGA1UdFQQDCgEFMCMCBFnGCGUXDTIxMDIwNDE1NTEwNVowDDAKBgNVHRUEAwoB -BTAjAgRZxghkFw0yMTAyMDQxNTUwNTNaMAwwCgYDVR0VBAMKAQUwIwIEWcYIVBcN -MjEwMjI1MTE1NzUxWjAMMAoGA1UdFQQDCgEFMCMCBFnGCFMXDTIxMDIyNTExNTc0 -NFowDDAKBgNVHRUEAwoBBTAjAgRZxggbFw0yMDEyMTEwNjM4MDlaMAwwCgYDVR0V -BAMKAQUwIwIEWcYIGhcNMjAxMjExMDYzNzUwWjAMMAoGA1UdFQQDCgEFMCMCBFnG -B/IXDTIwMTIwOTIxMzQ0NVowDDAKBgNVHRUEAwoBBTAjAgRZxgfwFw0yMDEyMDky -MTM1NDVaMAwwCgYDVR0VBAMKAQUwIwIEWcYH6BcNMjAxMjA5MTkyNzQ4WjAMMAoG -A1UdFQQDCgEFMCMCBFnGB+cXDTIwMTIwOTE5MjczNlowDDAKBgNVHRUEAwoBBTAj -AgRZxgfmFw0yMDEyMjExNDE5MTBaMAwwCgYDVR0VBAMKAQUwIwIEWcYH4xcNMjEw -MjA4MTE0OTA0WjAMMAoGA1UdFQQDCgEFMCMCBFnGB+IXDTIxMDIwODExNDg0Nlow -DDAKBgNVHRUEAwoBBTAjAgRZxgfeFw0yMDEyMDkxNzAzNTJaMAwwCgYDVR0VBAMK -AQUwIwIEWcYH3RcNMjAxMjA5MTU1MzA0WjAMMAoGA1UdFQQDCgEFMCMCBFnGBwEX -DTIwMTIwNjEyMDQ0MlowDDAKBgNVHRUEAwoBBTAjAgRZxgcAFw0yMDEyMDYxMjA1 -MTNaMAwwCgYDVR0VBAMKAQUwIwIEWcYG0RcNMjAxMjAzMTcwODU5WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGBtAXDTIwMTIwMzE3MDc0N1owDDAKBgNVHRUEAwoBBTAjAgRZ -xgbPFw0yMDEyMDMxNjU2MTJaMAwwCgYDVR0VBAMKAQUwIwIEWcYGzhcNMjAxMjAz -MTY1NDUwWjAMMAoGA1UdFQQDCgEFMCMCBFnGBsgXDTIwMTIwMzE3MDk0NFowDDAK -BgNVHRUEAwoBBTAjAgRZxgbHFw0yMDEyMDMxODE0MjVaMAwwCgYDVR0VBAMKAQUw -IwIEWcYGvBcNMjAxMjAzMDkxMDQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnGBrsXDTIw -MTIwMzEyMzEwMVowDDAKBgNVHRUEAwoBBTAjAgRZxga6Fw0yMDEyMDMxMjMwNTBa -MAwwCgYDVR0VBAMKAQUwIwIEWcYGkRcNMjAxMjAyMTgxMDA4WjAMMAoGA1UdFQQD -CgEFMCMCBFnGBo8XDTIwMTIwMjE4MTEwMlowDDAKBgNVHRUEAwoBBTAjAgRZxgaN -Fw0yMDEyMDIxNzQ2MjdaMAwwCgYDVR0VBAMKAQUwIwIEWcYGVRcNMjAxMjAxMTcx -NTIyWjAMMAoGA1UdFQQDCgEFMCMCBFnGBlQXDTIwMTIwMTE3MDIyMFowDDAKBgNV -HRUEAwoBBTAjAgRZxgZTFw0yMDEyMDExNzAyMTRaMAwwCgYDVR0VBAMKAQUwIwIE -WcYE6hcNMjAxMTI0MjAxMDExWjAMMAoGA1UdFQQDCgEFMCMCBFnGBOkXDTIwMTEy -NDIwMDgzM1owDDAKBgNVHRUEAwoBBTAjAgRZxgTnFw0yMDExMjQyMDA3MjZaMAww -CgYDVR0VBAMKAQUwIwIEWcYE5hcNMjAxMTI0MjAwNjM3WjAMMAoGA1UdFQQDCgEF -MCMCBFnGBOUXDTIwMTEyNDE5NTE0M1owDDAKBgNVHRUEAwoBBTAjAgRZxgTkFw0y -MDExMjQxOTUwMTJaMAwwCgYDVR0VBAMKAQUwIwIEWcYE4hcNMjAxMTI0MTk0OTAz -WjAMMAoGA1UdFQQDCgEFMCMCBFnGBOEXDTIwMTEyNDE5NDgwOVowDDAKBgNVHRUE -AwoBBTAjAgRZxgTeFw0yMDExMjQxOTMzNDlaMAwwCgYDVR0VBAMKAQUwIwIEWcYE -3BcNMjAxMTI0MTkzMjA5WjAMMAoGA1UdFQQDCgEFMCMCBFnGBNsXDTIwMTEyNDE5 -MzExNlowDDAKBgNVHRUEAwoBBTAjAgRZxgSeFw0yMDExMjQxMTQzMTFaMAwwCgYD -VR0VBAMKAQUwIwIEWcYEmxcNMjAxMTI0MTE0MzAwWjAMMAoGA1UdFQQDCgEFMCMC -BFnGBJkXDTIwMTEyNDExNDI1M1owDDAKBgNVHRUEAwoBBTAjAgRZxgSYFw0yMDEx -MjQxMTI1MTVaMAwwCgYDVR0VBAMKAQUwIwIEWcYElRcNMjAxMTI0MTEyMzQ0WjAM -MAoGA1UdFQQDCgEFMCMCBFnGBJMXDTIwMTEyNDExMjIzNVowDDAKBgNVHRUEAwoB -BTAjAgRZxgSSFw0yMDExMjQxMTIxMzlaMAwwCgYDVR0VBAMKAQUwIwIEWcYEkRcN -MjAxMTI0MTE0MjQ0WjAMMAoGA1UdFQQDCgEFMCMCBFnGBI0XDTIxMDIyNTExMDYx -N1owDDAKBgNVHRUEAwoBBTAjAgRZxgSMFw0yMTAyMjUxMTA2MTVaMAwwCgYDVR0V -BAMKAQUwIwIEWcYEiBcNMjEwMjI1MTEzODAzWjAMMAoGA1UdFQQDCgEFMCMCBFnG -BIcXDTIxMDIyNTExMzgwMVowDDAKBgNVHRUEAwoBBTAjAgRZxgQYFw0yMDExMjMx -MTMxNDZaMAwwCgYDVR0VBAMKAQUwIwIEWcYEFxcNMjAxMTIzMTEzMjUwWjAMMAoG -A1UdFQQDCgEFMCMCBFnGBBUXDTIxMDIyNTExMzkxN1owDDAKBgNVHRUEAwoBBTAj -AgRZxgQUFw0yMDExMjMxMTI4NDhaMAwwCgYDVR0VBAMKAQUwIwIEWcYEExcNMjAx -MTIzMTExMTI0WjAMMAoGA1UdFQQDCgEFMCMCBFnGBBIXDTIwMTEyMzExMzcxM1ow -DDAKBgNVHRUEAwoBBTAjAgRZxgQQFw0yMTAyMjUxMTEzMDRaMAwwCgYDVR0VBAMK -AQUwIwIEWcYEDxcNMjEwMjI1MTExMzAyWjAMMAoGA1UdFQQDCgEFMCMCBFnGBA4X -DTIwMTEyMzExMzUzOFowDDAKBgNVHRUEAwoBBTAjAgRZxgQNFw0yMDExMjMxMTMx -NDRaMAwwCgYDVR0VBAMKAQUwIwIEWcYECxcNMjEwMjI1MTExMTM4WjAMMAoGA1Ud -FQQDCgEFMCMCBFnGBAoXDTIxMDIyNTExMTEzNlowDDAKBgNVHRUEAwoBBTAjAgRZ -xgQJFw0yMDExMjMxMTI4NDBaMAwwCgYDVR0VBAMKAQUwIwIEWcYECBcNMjAxMTIz -MTEyODUzWjAMMAoGA1UdFQQDCgEFMCMCBFnGBAYXDTIxMDIyNTExMTE1NlowDDAK -BgNVHRUEAwoBBTAjAgRZxgQFFw0yMTAyMjUxMTExNTRaMAwwCgYDVR0VBAMKAQUw -IwIEWcYEBBcNMjAxMTIzMTEzMjQ0WjAMMAoGA1UdFQQDCgEFMCMCBFnGBAEXDTIw -MTEyMzExNDAwMVowDDAKBgNVHRUEAwoBBTAjAgRZxgP/Fw0yMTAyMjUxMTA3NDda -MAwwCgYDVR0VBAMKAQUwIwIEWcYD/BcNMjEwMjI1MTEwNzQ1WjAMMAoGA1UdFQQD -CgEFMCMCBFnGA0gXDTIxMDIyMzE0MjcyM1owDDAKBgNVHRUEAwoBBTAjAgRZxgNH -Fw0yMTAyMjMxNDI3MjJaMAwwCgYDVR0VBAMKAQUwIwIEWcYDGRcNMjEwMjI1MTEx -MTE1WjAMMAoGA1UdFQQDCgEFMCMCBFnGAxgXDTIwMTEyMzExMjgzNlowDDAKBgNV -HRUEAwoBBTAjAgRZxgMWFw0yMDExMTgxMzMxNTZaMAwwCgYDVR0VBAMKAQUwIwIE -WcYCERcNMjAxMTE4MTYxOTE2WjAMMAoGA1UdFQQDCgEFMCMCBFnGAgoXDTIwMTEx -ODE1MTExNVowDDAKBgNVHRUEAwoBBTAjAgRZxgHSFw0yMDExMTgxNDM3MDFaMAww -CgYDVR0VBAMKAQUwIwIEWcYB0RcNMjAxMTE4MTQyNDQ3WjAMMAoGA1UdFQQDCgEF -MCMCBFnGAdAXDTIwMTExODE0MjQzM1owDDAKBgNVHRUEAwoBBTAjAgRZxgHPFw0y -MDExMTgxNDM2MTZaMAwwCgYDVR0VBAMKAQUwIwIEWcYBzRcNMjAxMTExMTQwMjM4 -WjAMMAoGA1UdFQQDCgEFMCMCBFnGAaIXDTIwMTExODE2MTkwNFowDDAKBgNVHRUE -AwoBBTAjAgRZxgGbFw0yMDExMTAxOTQxNTdaMAwwCgYDVR0VBAMKAQUwIwIEWcYB -cRcNMjAxMTEyMTAyNzM4WjAMMAoGA1UdFQQDCgEFMCMCBFnGAWMXDTIwMTEwOTE5 -NDY1M1owDDAKBgNVHRUEAwoBBTAjAgRZxgFgFw0yMDExMDkxODI5MjdaMAwwCgYD -VR0VBAMKAQUwIwIEWcYBXxcNMjAxMjA3MTYyMDQ2WjAMMAoGA1UdFQQDCgEFMCMC -BFnGAVsXDTIwMTEwOTE2MjAwN1owDDAKBgNVHRUEAwoBBTAjAgRZxgEwFw0yMDEx -MDkxNzUxNDFaMAwwCgYDVR0VBAMKAQUwIwIEWcYBLhcNMjAxMTA5MTc1MTMxWjAM -MAoGA1UdFQQDCgEFMCMCBFnGASkXDTIwMTIyMzA3NTMzNVowDDAKBgNVHRUEAwoB -BTAjAgRZxgEoFw0yMDEyMjMwNzUzMjNaMAwwCgYDVR0VBAMKAQUwIwIEWcYA0RcN -MjAxMTEwMTE0NDQzWjAMMAoGA1UdFQQDCgEFMCMCBFnGAKgXDTIwMTEwNjEwNTgx -M1owDDAKBgNVHRUEAwoBBTAjAgRZxgBGFw0yMDExMTAxOTQzNDBaMAwwCgYDVR0V -BAMKAQUwIwIEWcX/lBcNMjEwMzEzMjAyNDU0WjAMMAoGA1UdFQQDCgEFMCMCBFnF -/zUXDTIwMTAzMDE2MDQ1OVowDDAKBgNVHRUEAwoBBTAjAgRZxf80Fw0yMTAyMjUx -MjAxMDlaMAwwCgYDVR0VBAMKAQUwIwIEWcX/MxcNMjEwMjI1MTIwMTAyWjAMMAoG -A1UdFQQDCgEFMCMCBFnF/y8XDTIwMTEyNzExMjI0NVowDDAKBgNVHRUEAwoBBTAj -AgRZxf8uFw0yMDEwMzAwNzU0MzlaMAwwCgYDVR0VBAMKAQUwIwIEWcX/LRcNMjAx -MDMwMDc1MzA5WjAMMAoGA1UdFQQDCgEFMCMCBFnF/ysXDTIwMTAzMDA3NTE1Nlow -DDAKBgNVHRUEAwoBBTAjAgRZxf8qFw0yMDEwMzAwNzUxMDJaMAwwCgYDVR0VBAMK -AQUwIwIEWcX/KRcNMjEwMjI1MTEzNzUzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/vwX -DTIwMTExNjEwNDMyMVowDDAKBgNVHRUEAwoBBTAjAgRZxf77Fw0yMDExMTYxMDQz -MjZaMAwwCgYDVR0VBAMKAQUwIwIEWcX++hcNMjAxMTE2MTA0MzMxWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF/vkXDTIwMTExNjEwNDMzNVowDDAKBgNVHRUEAwoBBTAjAgRZ -xf73Fw0yMTAyMjUxMTA4NDRaMAwwCgYDVR0VBAMKAQUwIwIEWcX+9hcNMjEwMjI1 -MTEwODQzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/vQXDTIwMTExNjE0Mjc0NlowDDAK -BgNVHRUEAwoBBTAjAgRZxf7zFw0yMDExMTYxNDI3NDJaMAwwCgYDVR0VBAMKAQUw -IwIEWcX+8hcNMjAxMTIzMTEzNjE3WjAMMAoGA1UdFQQDCgEFMCMCBFnF/vEXDTIw -MTEyMzExMzEzOVowDDAKBgNVHRUEAwoBBTAjAgRZxf7tFw0yMDExMTYxNDI4MDJa -MAwwCgYDVR0VBAMKAQUwIwIEWcX+7BcNMjAxMTE2MTQyODAwWjAMMAoGA1UdFQQD -CgEFMCMCBFnF/uoXDTIxMDIyNTExMDgxNFowDDAKBgNVHRUEAwoBBTAjAgRZxf7o -Fw0yMTAyMjUxMTA4MTBaMAwwCgYDVR0VBAMKAQUwIwIEWcX+5hcNMjAxMTIzMTEz -ODEzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/uUXDTIwMTEyMzExMzUwMFowDDAKBgNV -HRUEAwoBBTAjAgRZxf7jFw0yMDExMTYxNDI4MzlaMAwwCgYDVR0VBAMKAQUwIwIE -WcX+4RcNMjAxMTE2MTQyODM2WjAMMAoGA1UdFQQDCgEFMCMCBFnF/t8XDTIxMDIy -NTExMDgzMlowDDAKBgNVHRUEAwoBBTAjAgRZxf7eFw0yMTAyMjUxMTA4MzBaMAww -CgYDVR0VBAMKAQUwIwIEWcX+3BcNMjEwMjI1MTEzOTAzWjAMMAoGA1UdFQQDCgEF -MCMCBFnF/tsXDTIxMDIyNTExMzkwMVowDDAKBgNVHRUEAwoBBTAjAgRZxf7aFw0y -MDExMjMxMTM1MzRaMAwwCgYDVR0VBAMKAQUwIwIEWcX+2RcNMjAxMTIzMTEzNzEw -WjAMMAoGA1UdFQQDCgEFMCMCBFnF/tYXDTIxMDIyNTExMTM0OVowDDAKBgNVHRUE -AwoBBTAjAgRZxf7UFw0yMTAyMjUxMTEzNDhaMAwwCgYDVR0VBAMKAQUwIwIEWcX+ -0xcNMjAxMTIzMTEzODMzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/tIXDTIwMTEyMzEx -MzI0MVowDDAKBgNVHRUEAwoBBTAjAgRZxf7QFw0yMTAyMjUxMTEyMDVaMAwwCgYD -VR0VBAMKAQUwIwIEWcX+zxcNMjEwMjI1MTExMjAzWjAMMAoGA1UdFQQDCgEFMCMC -BFnF/s4XDTIwMTEyMzExMzgyNFowDDAKBgNVHRUEAwoBBTAjAgRZxf7NFw0yMDEx -MjMxMTM2MTVaMAwwCgYDVR0VBAMKAQUwIwIEWcX+yxcNMjAxMTE2MTQyOTA5WjAM -MAoGA1UdFQQDCgEFMCMCBFnF/soXDTIwMTExNjE0MjkwNlowDDAKBgNVHRUEAwoB -BTAjAgRZxf7JFw0yMDExMjMxMTM1MzFaMAwwCgYDVR0VBAMKAQUwIwIEWcX+yBcN -MjAxMTIzMTEzMjM4WjAMMAoGA1UdFQQDCgEFMCMCBFnF/scXDTIxMDIyNTExMTE0 -NlowDDAKBgNVHRUEAwoBBTAjAgRZxf7GFw0yMDEwMjkxMzE4MDNaMAwwCgYDVR0V -BAMKAQUwIwIEWcX+xRcNMjAxMDI5MTMxODA3WjAMMAoGA1UdFQQDCgEFMCMCBFnF -/sMXDTIwMTAyOTEyNDk0NVowDDAKBgNVHRUEAwoBBTAjAgRZxf7CFw0yMDEwMjkx -MjQ4MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcX+wRcNMjAxMDI5MTI0NjM5WjAMMAoG -A1UdFQQDCgEFMCMCBFnF/sAXDTIwMTAyOTEyMzkzM1owDDAKBgNVHRUEAwoBBTAj -AgRZxf6+Fw0yMDEwMjkxMjQ1MzZaMAwwCgYDVR0VBAMKAQUwIwIEWcX+vRcNMjAx -MDI5MTI0NDUzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/rwXDTIwMTEyMzExMzkxMVow -DDAKBgNVHRUEAwoBBTAjAgRZxf66Fw0yMTAyMjUxMTEyMTdaMAwwCgYDVR0VBAMK -AQUwIwIEWcX+uRcNMjEwMjI1MTExMjE1WjAMMAoGA1UdFQQDCgEFMCMCBFnF/rgX -DTIwMTEyMzExMzcwNlowDDAKBgNVHRUEAwoBBTAjAgRZxf63Fw0yMDExMjMxMTM4 -MDlaMAwwCgYDVR0VBAMKAQUwIwIEWcX+tRcNMjEwMjI1MTEwNzE4WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF/rQXDTIxMDIyNTExMDcxNlowDDAKBgNVHRUEAwoBBTAjAgRZ -xf6zFw0yMDEwMjkxMDQxMzBaMAwwCgYDVR0VBAMKAQUwIwIEWcX+dBcNMjAxMDI4 -MTE0OTAzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/nAXDTIxMDIyNTExMDg0OFowDDAK -BgNVHRUEAwoBBTAjAgRZxf5vFw0yMDEwMjcyMDE0MjRaMAwwCgYDVR0VBAMKAQUw -IwIEWcX+bhcNMjAxMDI3MjAxMzAzWjAMMAoGA1UdFQQDCgEFMCMCBFnF/mwXDTIw -MTAyNzIwMTIwNFowDDAKBgNVHRUEAwoBBTAjAgRZxf5rFw0yMDEwMjcyMDExMjFa -MAwwCgYDVR0VBAMKAQUwIwIEWcX+aRcNMjEwMjI1MTEwOTUwWjAMMAoGA1UdFQQD -CgEFMCMCBFnF/mgXDTIxMDIyNTExMDk0OFowDDAKBgNVHRUEAwoBBTAjAgRZxf5n -Fw0yMDEwMjcxOTU2MTFaMAwwCgYDVR0VBAMKAQUwIwIEWcX+ZhcNMjAxMDI3MTk1 -NDU0WjAMMAoGA1UdFQQDCgEFMCMCBFnF/mQXDTIwMTAyNzE5NTM1NVowDDAKBgNV -HRUEAwoBBTAjAgRZxf5jFw0yMDEwMjcxOTUzMTJaMAwwCgYDVR0VBAMKAQUwIwIE -WcX+YhcNMjAxMTIzMTEzMjM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF/mEXDTIwMTEy -MzExMzYxMlowDDAKBgNVHRUEAwoBBTAjAgRZxf5fFw0yMTAyMjUxMTM5MzlaMAww -CgYDVR0VBAMKAQUwIwIEWcX+XhcNMjAxMDI3MTk0MzE1WjAMMAoGA1UdFQQDCgEF -MCMCBFnF/jUXDTIwMTAyNzE1NDIzNFowDDAKBgNVHRUEAwoBBTAjAgRZxf4zFw0y -MDEwMjcxNTQxMTlaMAwwCgYDVR0VBAMKAQUwIwIEWcX+MRcNMjAxMDI3MTU0MDE5 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF/jAXDTIwMTAyNzE1MzkzN1owDDAKBgNVHRUE -AwoBBTAjAgRZxf4uFw0yMTAyMjUxMTUyMTlaMAwwCgYDVR0VBAMKAQUwIwIEWcX+ -LRcNMjAxMDI3MTUyNTEwWjAMMAoGA1UdFQQDCgEFMCMCBFnF/iwXDTIwMTAyNzE1 -MjM0OFowDDAKBgNVHRUEAwoBBTAjAgRZxf4qFw0yMDEwMjcxNTIyNDlaMAwwCgYD -VR0VBAMKAQUwIwIEWcX+KRcNMjAxMDI3MTUyMjA2WjAMMAoGA1UdFQQDCgEFMCMC -BFnF/iAXDTIwMTAyNzEyMjAzMlowDDAKBgNVHRUEAwoBBTAjAgRZxf4fFw0yMDEw -MjcxMjIwMzlaMAwwCgYDVR0VBAMKAQUwIwIEWcX9ERcNMjAxMDIyMTMzMjUwWjAM -MAoGA1UdFQQDCgEFMCMCBFnF/G0XDTIwMTEyMzExMzg0NVowDDAKBgNVHRUEAwoB -BTAjAgRZxfxsFw0yMDEwMTkxMDA3MjVaMAwwCgYDVR0VBAMKAQUwIwIEWcX8axcN -MjAxMDE5MTAwNjA2WjAMMAoGA1UdFQQDCgEFMCMCBFnF/GkXDTIwMTAxOTEwMDUw -MlowDDAKBgNVHRUEAwoBBTAjAgRZxfxoFw0yMDEwMTkxMDA0MTlaMAwwCgYDVR0V -BAMKAQUwIwIEWcX8ZxcNMjAxMDE5MDk1MTEzWjAMMAoGA1UdFQQDCgEFMCMCBFnF -/GYXDTIwMTAxOTA5NDk0N1owDDAKBgNVHRUEAwoBBTAjAgRZxfxkFw0yMDEwMTkw -OTQ4NDhaMAwwCgYDVR0VBAMKAQUwIwIEWcX8YxcNMjAxMDE5MDk0ODA2WjAMMAoG -A1UdFQQDCgEFMCMCBFnF+98XDTIwMTEwNTE0MTQ0NVowDDAKBgNVHRUEAwoBBTAj -AgRZxfuZFw0yMDEwMTUwODE4MDlaMAwwCgYDVR0VBAMKAQUwIwIEWcX7mBcNMjAx -MDE1MDgxNzU3WjAMMAoGA1UdFQQDCgEFMCMCBFnF+2QXDTIwMTIyMzExMzcxOVow -DDAKBgNVHRUEAwoBBTAjAgRZxftjFw0yMDEyMjMxMTM3MDhaMAwwCgYDVR0VBAMK -AQUwIwIEWcX7IxcNMjAxMDEzMTExNjE3WjAMMAoGA1UdFQQDCgEFMCMCBFnF+yIX -DTIwMTAxMzExMTQ1MVowDDAKBgNVHRUEAwoBBTAjAgRZxfshFw0yMDEwMTQwODE0 -MzdaMAwwCgYDVR0VBAMKAQUwIwIEWcX7HxcNMjAxMDEzMTExMzU0WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF+x4XDTIwMTAxMzExMTMxMFowDDAKBgNVHRUEAwoBBTAjAgRZ -xfsWFw0yMDEwMTMxMDU1MjdaMAwwCgYDVR0VBAMKAQUwIwIEWcX7FRcNMjAxMDEz -MTA1NDA0WjAMMAoGA1UdFQQDCgEFMCMCBFnF+xMXDTIwMTAxMzEwNTMwNFowDDAK -BgNVHRUEAwoBBTAjAgRZxfsSFw0yMDEwMTMxMDUyMjBaMAwwCgYDVR0VBAMKAQUw -IwIEWcX7DxcNMjAxMDEzMTAzOTIxWjAMMAoGA1UdFQQDCgEFMCMCBFnF+w4XDTIw -MTAxMzEwMzkwOVowDDAKBgNVHRUEAwoBBTAjAgRZxfsNFw0yMDEwMTQwODE0NTBa -MAwwCgYDVR0VBAMKAQUwIwIEWcX63hcNMjAxMDEyMTE0MTQ1WjAMMAoGA1UdFQQD -CgEFMCMCBFnF+t0XDTIwMTAxMjExNDAyM1owDDAKBgNVHRUEAwoBBTAjAgRZxfrb -Fw0yMDEwMTIxMTM5MjJaMAwwCgYDVR0VBAMKAQUwIwIEWcX62hcNMjAxMDEyMTEz -ODQwWjAMMAoGA1UdFQQDCgEFMCMCBFnF+tkXDTIxMDIyNTExMDgxOVowDDAKBgNV -HRUEAwoBBTAjAgRZxfrVFw0yMDEwMTMxMTM1NTVaMAwwCgYDVR0VBAMKAQUwIwIE -WcX61BcNMjAxMTIzMTEzODU0WjAMMAoGA1UdFQQDCgEFMCMCBFnF+tMXDTIwMTEy -MzExMzUyN1owDDAKBgNVHRUEAwoBBTAjAgRZxfrSFw0yMDEwMTIxMTIwMjFaMAww -CgYDVR0VBAMKAQUwIwIEWcX60RcNMjAxMDEyMTEyMDUxWjAMMAoGA1UdFQQDCgEF -MCMCBFnF+k8XDTIwMTAxMzExMDYwNFowDDAKBgNVHRUEAwoBBTAjAgRZxfpOFw0y -MDEwMTMwOTE2NDFaMAwwCgYDVR0VBAMKAQUwIwIEWcX6SxcNMjAxMDEzMTEyMzE2 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF+gsXDTIwMTEwNDEwMzAzN1owDDAKBgNVHRUE -AwoBBTAjAgRZxfoHFw0yMDEwMDgwNzQ2NTdaMAwwCgYDVR0VBAMKAQUwIwIEWcX6 -BhcNMjAxMDA4MDc0NTM2WjAMMAoGA1UdFQQDCgEFMCMCBFnF+gEXDTIwMTAwODA3 -NDQzMlowDDAKBgNVHRUEAwoBBTAjAgRZxfoAFw0yMDEwMDgwNzQzNDhaMAwwCgYD -VR0VBAMKAQUwIwIEWcX5/xcNMjAxMDA4MDczMjE1WjAMMAoGA1UdFQQDCgEFMCMC -BFnF+fsXDTIwMTAwODA3MjIzNlowDDAKBgNVHRUEAwoBBTAjAgRZxfn6Fw0yMDEw -MDgwNzIxMDlaMAwwCgYDVR0VBAMKAQUwIwIEWcX5+BcNMjAxMDA4MDcyMDAzWjAM -MAoGA1UdFQQDCgEFMCMCBFnF+fcXDTIwMTAwODA3MTkxNlowDDAKBgNVHRUEAwoB -BTAjAgRZxfn2Fw0yMDEwMDgwNjU3NDdaMAwwCgYDVR0VBAMKAQUwIwIEWcX59RcN -MjAxMDA4MDY1NjMyWjAMMAoGA1UdFQQDCgEFMCMCBFnF+fMXDTIwMTAwODA2NTUz -NlowDDAKBgNVHRUEAwoBBTAjAgRZxfnyFw0yMDEwMDgwNjU0NTVaMAwwCgYDVR0V -BAMKAQUwIwIEWcX58BcNMjEwMjI1MTExMjU2WjAMMAoGA1UdFQQDCgEFMCMCBFnF -+e8XDTIxMDIyNTExMTI1NFowDDAKBgNVHRUEAwoBBTAjAgRZxfntFw0yMTAyMjUx -MTA4MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcX57BcNMjEwMjI1MTEwODIyWjAMMAoG -A1UdFQQDCgEFMCMCBFnF+egXDTIwMTEyMzExMzIzMVowDDAKBgNVHRUEAwoBBTAj -AgRZxfnnFw0yMDExMjMxMTM3MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcX55RcNMjAx -MDA4MDYzMjU4WjAMMAoGA1UdFQQDCgEFMCMCBFnF+eQXDTIwMTAwODA2MzIyN1ow -DDAKBgNVHRUEAwoBBTAjAgRZxfnjFw0yMDExMjMxMTM2MTBaMAwwCgYDVR0VBAMK -AQUwIwIEWcX54hcNMjAxMTIzMTEzODIxWjAMMAoGA1UdFQQDCgEFMCMCBFnF+eAX -DTIwMTAwODE0MTEzOVowDDAKBgNVHRUEAwoBBTAjAgRZxfnfFw0yMDEwMDgxNDEx -MzZaMAwwCgYDVR0VBAMKAQUwIwIEWcX5pxcNMjAxMDA3MDkxMjUzWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF+aYXDTIxMDIyNTExMDkwNFowDDAKBgNVHRUEAwoBBTAjAgRZ -xfmlFw0yMTAyMjUxMTEyMDhaMAwwCgYDVR0VBAMKAQUwIwIEWcX5dRcNMjAxMDA5 -MTQxOTMwWjAMMAoGA1UdFQQDCgEFMCMCBFnF+XQXDTIwMTAwOTE0Mjk0MFowDDAK -BgNVHRUEAwoBBTAjAgRZxflyFw0yMDEwMDkxMjAzMTRaMAwwCgYDVR0VBAMKAQUw -IwIEWcX5cRcNMjAxMDEzMTEyMzA0WjAMMAoGA1UdFQQDCgEFMCMCBFnF+W8XDTIw -MTAwNzEzNTYyMlowDDAKBgNVHRUEAwoBBTAjAgRZxflnFw0yMDEyMjEwOTU5MTda -MAwwCgYDVR0VBAMKAQUwIwIEWcX5ZhcNMjAxMDA2MTA0ODI0WjAMMAoGA1UdFQQD -CgEFMCMCBFnF+WUXDTIwMTIyMTA5NTkwOFowDDAKBgNVHRUEAwoBBTAjAgRZxfkz -Fw0yMDEwMDUxNDM3MDRaMAwwCgYDVR0VBAMKAQUwIwIEWcX5MhcNMjAxMDA1MTQz -MzQyWjAMMAoGA1UdFQQDCgEFMCMCBFnF+TEXDTIwMTAwNTE0MzMyN1owDDAKBgNV -HRUEAwoBBTAjAgRZxfhCFw0yMDEwMDExMDEyMzRaMAwwCgYDVR0VBAMKAQUwIwIE -WcX4MhcNMjAwOTMwMTEyNzU5WjAMMAoGA1UdFQQDCgEFMCMCBFnF+DEXDTIwMDkz -MDExMjc1MVowDDAKBgNVHRUEAwoBBTAjAgRZxff4Fw0yMDA5MjkyMDAyMTlaMAww -CgYDVR0VBAMKAQUwIwIEWcX39xcNMjAwOTI5MjAwMjExWjAMMAoGA1UdFQQDCgEF -MCMCBFnF9/UXDTIwMDkyOTIwMDE0MFowDDAKBgNVHRUEAwoBBTAjAgRZxff0Fw0y -MDA5MjkyMDAxMzJaMAwwCgYDVR0VBAMKAQUwIwIEWcX38hcNMjAwOTI5MTk0ODAx -WjAMMAoGA1UdFQQDCgEFMCMCBFnF9/EXDTIwMDkyOTE5NDc1MFowDDAKBgNVHRUE -AwoBBTAjAgRZxffwFw0yMDA5MjkxOTQ4NDJaMAwwCgYDVR0VBAMKAQUwIwIEWcX3 -7hcNMjAwOTI5MTk0ODM2WjAMMAoGA1UdFQQDCgEFMCMCBFnF9+kXDTIwMTAxMjA5 -MTA1MFowDDAKBgNVHRUEAwoBBTAjAgRZxffnFw0yMDExMjMxMTMyMjhaMAwwCgYD -VR0VBAMKAQUwIwIEWcX3vBcNMjAxMjE0MDk1NTQxWjAMMAoGA1UdFQQDCgEFMCMC -BFnF97sXDTIwMTIxNDA5NDUxOVowDDAKBgNVHRUEAwoBBTAjAgRZxfe5Fw0yMTAy -MjUxMjAwMjZaMAwwCgYDVR0VBAMKAQUwIwIEWcX3uBcNMjEwMjI1MTIwMDMxWjAM -MAoGA1UdFQQDCgEFMCMCBFnF9pcXDTIwMTEwNTE3MjUyNlowDDAKBgNVHRUEAwoB -BTAjAgRZxfaWFw0yMDExMDUxNzI1MjFaMAwwCgYDVR0VBAMKAQUwIwIEWcX2jhcN -MjAxMTIzMTEzNTI4WjAMMAoGA1UdFQQDCgEFMCMCBFnF9o0XDTIwMTEyMzExMzgw -NlowDDAKBgNVHRUEAwoBBTAjAgRZxfaMFw0yMDA5MjIxOTQzNTFaMAwwCgYDVR0V -BAMKAQUwIwIEWcX2ixcNMjAwOTIyMTk0NDAwWjAMMAoGA1UdFQQDCgEFMCMCBFnF -9ooXDTIwMTEyMzExMzgzMVowDDAKBgNVHRUEAwoBBTAjAgRZxfaIFw0yMDA5MjIx -OTQzMDhaMAwwCgYDVR0VBAMKAQUwIwIEWcX2hxcNMjAwOTIyMTk0MzAwWjAMMAoG -A1UdFQQDCgEFMCMCBFnF9oYXDTIwMDkyMjE5MjAyMFowDDAKBgNVHRUEAwoBBTAj -AgRZxfaFFw0yMDA5MjIxOTIwMDVaMAwwCgYDVR0VBAMKAQUwIwIEWcX2gxcNMjAw -OTIyMTkxOTA0WjAMMAoGA1UdFQQDCgEFMCMCBFnF9oIXDTIwMDkyMjE5MTg1Mlow -DDAKBgNVHRUEAwoBBTAjAgRZxfZVFw0yMDA5MjIxMDIyMTlaMAwwCgYDVR0VBAMK -AQUwIwIEWcX2VBcNMjAwOTIyMTAyMTM3WjAMMAoGA1UdFQQDCgEFMCMCBFnF9lIX -DTIwMDkyMjEwMjAwN1owDDAKBgNVHRUEAwoBBTAjAgRZxfZRFw0yMDA5MjIxMDIw -MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcX2TRcNMjAwOTIyMTAyMDAwWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF9kwXDTIwMDkyMjEwMTk0OVowDDAKBgNVHRUEAwoBBTAjAgRZ -xfZKFw0yMDA5MjIxMDA3MDBaMAwwCgYDVR0VBAMKAQUwIwIEWcX2SRcNMjAwOTIy -MTAwNjQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnF9hMXDTIwMDkyMTEwMTg1N1owDDAK -BgNVHRUEAwoBBTAjAgRZxfYRFw0yMDExMDUxNzI1NDZaMAwwCgYDVR0VBAMKAQUw -IwIEWcX2EBcNMjAxMTA1MTcyNTQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnF9g4XDTIw -MTEwNTE3MjUzNlowDDAKBgNVHRUEAwoBBTAjAgRZxfYNFw0yMDExMDUxNzI1MzNa -MAwwCgYDVR0VBAMKAQUwIwIEWcX2CxcNMjAxMTA1MTcyNTEwWjAMMAoGA1UdFQQD -CgEFMCMCBFnF9goXDTIwMTEwNTE3MjUwN1owDDAKBgNVHRUEAwoBBTAjAgRZxfYI -Fw0yMDExMDUxNzI0NTNaMAwwCgYDVR0VBAMKAQUwIwIEWcX2BxcNMjAxMTA1MTcy -NDQ5WjAMMAoGA1UdFQQDCgEFMCMCBFnF9gYXDTIwMTEwNTE3MjQyN1owDDAKBgNV -HRUEAwoBBTAjAgRZxfYFFw0yMDExMDUxNzI0MjRaMAwwCgYDVR0VBAMKAQUwIwIE -WcX10BcNMjAxMTA1MTcyNDIyWjAMMAoGA1UdFQQDCgEFMCMCBFnF9c8XDTIwMTEw -NTE3MjQxOFowDDAKBgNVHRUEAwoBBTAjAgRZxfV8Fw0yMDExMjMxMTMyMjRaMAww -CgYDVR0VBAMKAQUwIwIEWcX1excNMjAxMTIzMTEzNjA4WjAMMAoGA1UdFQQDCgEF -MCMCBFnF9XkXDTIxMDIyNTExMzc1OVowDDAKBgNVHRUEAwoBBTAjAgRZxfV4Fw0y -MTAyMjUxMTM3NTdaMAwwCgYDVR0VBAMKAQUwIwIEWcX1ahcNMjEwMTIyMTYxMTM5 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF9TcXDTIwMTEyMzExMzUyM1owDDAKBgNVHRUE -AwoBBTAjAgRZxfU2Fw0yMDExMjMxMTM2NTlaMAwwCgYDVR0VBAMKAQUwIwIEWcX1 -NBcNMjEwMjI1MTExMTQ0WjAMMAoGA1UdFQQDCgEFMCMCBFnF9TMXDTIxMDIyNTEx -MTE0MVowDDAKBgNVHRUEAwoBBTAjAgRZxfUyFw0yMDExMjMxMTMyMjJaMAwwCgYD -VR0VBAMKAQUwIwIEWcX1MRcNMjAxMTIzMTEzOTUyWjAMMAoGA1UdFQQDCgEFMCMC -BFnF9S8XDTIxMDIyNTExMDcyNFowDDAKBgNVHRUEAwoBBTAjAgRZxfUuFw0yMTAy -MjUxMTA3MjJaMAwwCgYDVR0VBAMKAQUwIwIEWcX1LBcNMjEwMjI1MTExNjI2WjAM -MAoGA1UdFQQDCgEFMCMCBFnF9SsXDTIxMDIyNTExMDYyMFowDDAKBgNVHRUEAwoB -BTAjAgRZxfUqFw0yMDExMjMxMTM1MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcX1KRcN -MjAxMTIzMTEzMjIwWjAMMAoGA1UdFQQDCgEFMCMCBFnF9ScXDTIxMDIyNTExMTEw -OVowDDAKBgNVHRUEAwoBBTAjAgRZxfUmFw0yMTAyMjUxMTExMDdaMAwwCgYDVR0V -BAMKAQUwIwIEWcX1JRcNMjAxMTIzMTEzNjAxWjAMMAoGA1UdFQQDCgEFMCMCBFnF -9SQXDTIwMTEyMzExMzY1N1owDDAKBgNVHRUEAwoBBTAjAgRZxfUiFw0yMTAyMjUx -MTEyNTFaMAwwCgYDVR0VBAMKAQUwIwIEWcX1IRcNMjEwMjI1MTExMjUwWjAMMAoG -A1UdFQQDCgEFMCMCBFnF9SAXDTIxMDIyNTExMzkyOFowDDAKBgNVHRUEAwoBBTAj -AgRZxfUfFw0yMDExMjMxMTMyMThaMAwwCgYDVR0VBAMKAQUwIwIEWcX1HhcNMjAx -MTIzMTEzODA0WjAMMAoGA1UdFQQDCgEFMCMCBFnF9RwXDTIxMDIyNTExMTI0Nlow -DDAKBgNVHRUEAwoBBTAjAgRZxfUbFw0yMTAyMjUxMTEyNDRaMAwwCgYDVR0VBAMK -AQUwIwIEWcX1GhcNMjAxMTIzMTEzNTE4WjAMMAoGA1UdFQQDCgEFMCMCBFnF9RcX -DTIwMTEyMzExMzIxMlowDDAKBgNVHRUEAwoBBTAjAgRZxfUUFw0yMTAyMjUxMTE2 -NTdaMAwwCgYDVR0VBAMKAQUwIwIEWcX1ExcNMjEwMjI1MTExNjQ5WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF9RIXDTIwMTEyMzExMzgxOVowDDAKBgNVHRUEAwoBBTAjAgRZ -xfURFw0yMDExMjMxMTM1NThaMAwwCgYDVR0VBAMKAQUwIwIEWcX1DxcNMjAwOTE3 -MTYxNzIwWjAMMAoGA1UdFQQDCgEFMCMCBFnF9Q4XDTIwMDkxNzE2MTY1MFowDDAK -BgNVHRUEAwoBBTAjAgRZxfSlFw0yMDA5MTcwNDM2MDRaMAwwCgYDVR0VBAMKAQUw -IwIEWcX0pBcNMjAwOTE3MDQzNTU3WjAMMAoGA1UdFQQDCgEFMCMCBFnF9KMXDTIw -MDkxNTEzNDU1OFowDDAKBgNVHRUEAwoBBTAjAgRZxfSiFw0yMDA5MTUxMzQ1Mjla -MAwwCgYDVR0VBAMKAQUwIwIEWcX0nxcNMjAwOTE1MTAzNTA5WjAMMAoGA1UdFQQD -CgEFMCMCBFnF9J4XDTIwMDkxNTEwMzQ1OVowDDAKBgNVHRUEAwoBBTAjAgRZxfSc -Fw0yMDA5MTUxMDM0NDlaMAwwCgYDVR0VBAMKAQUwIwIEWcX0mhcNMjAwOTE1MTA0 -MDA0WjAMMAoGA1UdFQQDCgEFMCMCBFnF9JkXDTIwMDkxNTEwNDAxNFowDDAKBgNV -HRUEAwoBBTAjAgRZxfSXFw0yMDA5MTUxMDA4MzNaMAwwCgYDVR0VBAMKAQUwIwIE -WcX0lhcNMjAwOTE1MTAwODIzWjAMMAoGA1UdFQQDCgEFMCMCBFnF9JUXDTIwMDkx -NTEwMDkxNFowDDAKBgNVHRUEAwoBBTAjAgRZxfSUFw0yMDA5MTUxMDA5MzNaMAww -CgYDVR0VBAMKAQUwIwIEWcX0kxcNMjEwMjI1MTE1MjU3WjAMMAoGA1UdFQQDCgEF -MCMCBFnF9JIXDTIxMDIyNTExMzczMlowDDAKBgNVHRUEAwoBBTAjAgRZxfSQFw0y -MTAyMjUxMTM3MzBaMAwwCgYDVR0VBAMKAQUwIwIEWcX0jxcNMjEwMjI1MTE1MjU2 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF8+YXDTIwMDkxMTE3MjgxN1owDDAKBgNVHRUE -AwoBBTAjAgRZxfOcFw0yMDA5MDkyMDA1NTNaMAwwCgYDVR0VBAMKAQUwIwIEWcXz -mxcNMjAwOTA5MjAwNTQ0WjAMMAoGA1UdFQQDCgEFMCMCBFnF82MXDTIwMDkxMTE2 -NTUwOFowDDAKBgNVHRUEAwoBBTAjAgRZxfNiFw0yMDA5MTExNjU1MDZaMAwwCgYD -VR0VBAMKAQUwIwIEWcXzYBcNMjAwOTA5MTI1NjQ4WjAMMAoGA1UdFQQDCgEFMCMC -BFnF818XDTIwMDkwOTEyNTY0NlowDDAKBgNVHRUEAwoBBTAjAgRZxfNWFw0yMDA5 -MDkxMjM0NTlaMAwwCgYDVR0VBAMKAQUwIwIEWcXzVRcNMjAwOTA5MTIzNDU3WjAM -MAoGA1UdFQQDCgEFMCMCBFnF81MXDTIwMDkwOTEyMzQ0OVowDDAKBgNVHRUEAwoB -BTAjAgRZxfNSFw0yMDA5MDkxMjM0NDdaMAwwCgYDVR0VBAMKAQUwIwIEWcXzUBcN -MjAwOTA5MTIzNDQwWjAMMAoGA1UdFQQDCgEFMCMCBFnF808XDTIwMDkwOTEyMzQz -OFowDDAKBgNVHRUEAwoBBTAjAgRZxfMSFw0yMDA5MDgxMzM1MDZaMAwwCgYDVR0V -BAMKAQUwIwIEWcXzERcNMjAwOTA4MTMzNTAzWjAMMAoGA1UdFQQDCgEFMCMCBFnF -8w8XDTIwMDkwODEyNDY0OFowDDAKBgNVHRUEAwoBBTAjAgRZxfMOFw0yMDA5MDgx -MjQ2NDVaMAwwCgYDVR0VBAMKAQUwIwIEWcXzBBcNMjAwOTA3MTgzNDIxWjAMMAoG -A1UdFQQDCgEFMCMCBFnF8tkXDTIwMTAxNTA4MzIzM1owDDAKBgNVHRUEAwoBBTAj -AgRZxfLYFw0yMDEwMTUwODMyMzBaMAwwCgYDVR0VBAMKAQUwIwIEWcXyzRcNMjAw -OTA3MTA1MzQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnF8hIXDTIwMDkwMzE3MTcxNVow -DDAKBgNVHRUEAwoBBTAjAgRZxfIRFw0yMDA5MDMxNzE4NDZaMAwwCgYDVR0VBAMK -AQUwIwIEWcXyBBcNMjAwOTAzMTE1ODEyWjAMMAoGA1UdFQQDCgEFMCMCBFnF8gIX -DTIwMDkwMzExNTc1OFowDDAKBgNVHRUEAwoBBTAjAgRZxfHLFw0yMTAyMDIxMDQ1 -MzZaMAwwCgYDVR0VBAMKAQUwIwIEWcXxyhcNMjEwMjAyMTA0NTMwWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF8cQXDTIwMDkwMjEzMDc0M1owDDAKBgNVHRUEAwoBBTAjAgRZ -xfGPFw0yMDA5MDExMDI5MzNaMAwwCgYDVR0VBAMKAQUwIwIEWcXxjhcNMjAwOTAx -MTAxMzU3WjAMMAoGA1UdFQQDCgEFMCMCBFnF8VwXDTIwMDgzMTA3MjQwMFowDDAK -BgNVHRUEAwoBBTAjAgRZxfFbFw0yMDA4MzEwNjUxMzZaMAwwCgYDVR0VBAMKAQUw -IwIEWcXw4hcNMjAwODI4MTMyMDM3WjAMMAoGA1UdFQQDCgEFMCMCBFnF8NsXDTIw -MDgyODA2MDkzNlowDDAKBgNVHRUEAwoBBTAjAgRZxfCkFw0yMDA4MjcxMzM5NDNa -MAwwCgYDVR0VBAMKAQUwIwIEWcXwoxcNMjAwODI3MTMzOTI5WjAMMAoGA1UdFQQD -CgEFMCMCBFnF8KEXDTIwMDgyNzExMTA0NFowDDAKBgNVHRUEAwoBBTAjAgRZxfCg -Fw0yMDA4MjcxMTEwNTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXwjRcNMjAwODI2MjI0 -MzM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF8GYXDTIwMDgyODA0MTk1MFowDDAKBgNV -HRUEAwoBBTAjAgRZxfBRFw0yMDA5MDIxMTMzNTJaMAwwCgYDVR0VBAMKAQUwIwIE -WcXwUBcNMjAwOTAyMTEzMzUwWjAMMAoGA1UdFQQDCgEFMCMCBFnF8EoXDTIwMDgy -NTE5NTUwNFowDDAKBgNVHRUEAwoBBTAjAgRZxfBJFw0yMDA4MjUxOTUzNDdaMAww -CgYDVR0VBAMKAQUwIwIEWcXwRxcNMjAwODI1MTk1MjU0WjAMMAoGA1UdFQQDCgEF -MCMCBFnF8EYXDTIwMDgyNTE5NTIyNFowDDAKBgNVHRUEAwoBBTAjAgRZxfBCFw0y -MDA4MjUxOTQzNTVaMAwwCgYDVR0VBAMKAQUwIwIEWcXwQRcNMjAwODI1MTk0MzI1 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF8D0XDTIxMDIyNTExMDczNVowDDAKBgNVHRUE -AwoBBTAjAgRZxfA8Fw0yMTAyMjUxMTA3MzNaMAwwCgYDVR0VBAMKAQUwIwIEWcXw -OBcNMjEwMjI1MTExNDA0WjAMMAoGA1UdFQQDCgEFMCMCBFnF8DcXDTIxMDIyNTEx -MTQwM1owDDAKBgNVHRUEAwoBBTAjAgRZxfAzFw0yMDA4MjUxOTE2NTJaMAwwCgYD -VR0VBAMKAQUwIwIEWcXwMhcNMjAwODI1MTkxNjIyWjAMMAoGA1UdFQQDCgEFMCMC -BFnF8DAXDTIwMDkyMTEzMzgwN1owDDAKBgNVHRUEAwoBBTAjAgRZxfAuFw0yMDA4 -MjUxOTA2NThaMAwwCgYDVR0VBAMKAQUwIwIEWcXwLRcNMjAwODI1MTkwNjI3WjAM -MAoGA1UdFQQDCgEFMCMCBFnF8CwXDTIxMDIyNTExMTAxN1owDDAKBgNVHRUEAwoB -BTAjAgRZxfArFw0yMDA4MjUxODUxMzZaMAwwCgYDVR0VBAMKAQUwIwIEWcXwKhcN -MjAwODI1MTg1MDI4WjAMMAoGA1UdFQQDCgEFMCMCBFnF8CgXDTIwMDgyNTE4NDk0 -MlowDDAKBgNVHRUEAwoBBTAjAgRZxfAnFw0yMDA4MjUxODQ5MTJaMAwwCgYDVR0V -BAMKAQUwIwIEWcXwIxcNMjEwMjI1MTExMjAxWjAMMAoGA1UdFQQDCgEFMCMCBFnF -8CIXDTIxMDIyNTExMTE1OFowDDAKBgNVHRUEAwoBBTAjAgRZxfAeFw0yMTAyMjUx -MTM4MTZaMAwwCgYDVR0VBAMKAQUwIwIEWcXwHRcNMjEwMjI1MTEzODE0WjAMMAoG -A1UdFQQDCgEFMCMCBFnF7/YXDTIwMDgyNTE2MDcwMlowDDAKBgNVHRUEAwoBBTAj -AgRZxe/xFw0yMDA4MjUxNTQwMjVaMAwwCgYDVR0VBAMKAQUwIwIEWcXv7xcNMjAw -ODI1MTUyMTExWjAMMAoGA1UdFQQDCgEFMCMCBFnF7+0XDTIwMDgyNTE0MzcwMVow -DDAKBgNVHRUEAwoBBTAjAgRZxe/sFw0yMDA4MjUxNDMzMzVaMAwwCgYDVR0VBAMK -AQUwIwIEWcXv6xcNMjAwODI1MTQyNDA2WjAMMAoGA1UdFQQDCgEFMCMCBFnF7+UX -DTIwMDgyNTEzMDgzOVowDDAKBgNVHRUEAwoBBTAjAgRZxe+mFw0yMDA4MjcxNjUy -MDZaMAwwCgYDVR0VBAMKAQUwIwIEWcXvpRcNMjAwODI3MTY1MzQ4WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF7qwXDTIwMDgxOTEzNTQxMFowDDAKBgNVHRUEAwoBBTAjAgRZ -xe6rFw0yMDA4MTkxMzUxMzhaMAwwCgYDVR0VBAMKAQUwIwIEWcXuqhcNMjAwODE5 -MTMzODE3WjAMMAoGA1UdFQQDCgEFMCMCBFnF7qgXDTIwMDgxOTEzMTAwMlowDDAK -BgNVHRUEAwoBBTAjAgRZxe3tFw0yMDA4MTcxNDE5MjZaMAwwCgYDVR0VBAMKAQUw -IwIEWcXt5BcNMjAwODE3MTM0ODE5WjAMMAoGA1UdFQQDCgEFMCMCBFnF7d8XDTIw -MDgxNzEyNDk1OFowDDAKBgNVHRUEAwoBBTAjAgRZxe3eFw0yMDA4MTcxMjQ3NTFa -MAwwCgYDVR0VBAMKAQUwIwIEWcXt0xcNMjAwODE3MTIxMTM5WjAMMAoGA1UdFQQD -CgEFMBUCBFnF7QkXDTIwMDgyNDExMjIwM1owFQIEWcXtCBcNMjAwODI0MTEyMjAz -WjAVAgRZxe0HFw0yMDA4MjQxMTIyMDNaMCMCBFnF7QYXDTIwMDgxNzA4MjEyM1ow -DDAKBgNVHRUEAwoBBTAjAgRZxe0AFw0yMDA4MTkxMzI0MTVaMAwwCgYDVR0VBAMK -AQUwIwIEWcXs1xcNMjAwODE3MDgyMTM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF7M8X -DTIwMDgxMzE0MTkzNlowDDAKBgNVHRUEAwoBBTAjAgRZxeycFw0yMDA4MTIxMTMz -NDBaMAwwCgYDVR0VBAMKAQUwIwIEWcXsmxcNMjAwODEyMDcyNzMyWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF7JoXDTIwMDgxMjA2NTI1OVowDDAKBgNVHRUEAwoBBTAjAgRZ -xeyZFw0yMDA4MTIwNjQwNDRaMAwwCgYDVR0VBAMKAQUwIwIEWcXsmBcNMjAwODEy -MDYzMDM1WjAMMAoGA1UdFQQDCgEFMCMCBFnF7JcXDTIwMDgxMjA2MjkyN1owDDAK -BgNVHRUEAwoBBTAjAgRZxeyWFw0yMDA4MTIwNjE3MDRaMAwwCgYDVR0VBAMKAQUw -IwIEWcXslRcNMjAwODEyMDYxNTQ5WjAMMAoGA1UdFQQDCgEFMCMCBFnF7GwXDTIw -MDgxMTE1NTM1N1owDDAKBgNVHRUEAwoBBTAjAgRZxexmFw0yMDA4MTMxNjA2NDZa -MAwwCgYDVR0VBAMKAQUwIwIEWcXsYxcNMjAwODE3MDgyMTI5WjAMMAoGA1UdFQQD -CgEFMCMCBFnF7GIXDTIwMDgxMTEzMDUyMFowDDAKBgNVHRUEAwoBBTAjAgRZxexh -Fw0yMDA4MTExMjU1NTVaMAwwCgYDVR0VBAMKAQUwIwIEWcXsYBcNMjAwODExMTIy -NDIwWjAMMAoGA1UdFQQDCgEFMBUCBFnF7CEXDTIwMDgyNDExMjIwMlowIwIEWcXs -GxcNMjAwOTAyMTIwODIxWjAMMAoGA1UdFQQDCgEFMCMCBFnF7BcXDTIwMDkwMjEy -MDgxOVowDDAKBgNVHRUEAwoBBTAjAgRZxewWFw0yMDExMTYxODM0NTBaMAwwCgYD -VR0VBAMKAQUwIwIEWcXsFRcNMjAxMTE2MTgzNTAyWjAMMAoGA1UdFQQDCgEFMCMC -BFnF7AsXDTIwMDgxMDA4MTQxNlowDDAKBgNVHRUEAwoBBTAjAgRZxeuHFw0yMDA5 -MjQxNjI0MzRaMAwwCgYDVR0VBAMKAQUwIwIEWcXrhhcNMjAwOTI0MTYyNDMyWjAM -MAoGA1UdFQQDCgEFMCMCBFnF64AXDTIwMDgwNzEzNDA0MFowDDAKBgNVHRUEAwoB -BTAjAgRZxesWFw0yMDA4MDUxNzEwNDVaMAwwCgYDVR0VBAMKAQUwIwIEWcXrFRcN -MjAwODA1MTcxMDI4WjAMMAoGA1UdFQQDCgEFMCMCBFnF6tkXDTIwMDgwNDIwNTUy -M1owDDAKBgNVHRUEAwoBBTAjAgRZxerYFw0yMDA4MDQyMDU1MDlaMAwwCgYDVR0V -BAMKAQUwIwIEWcXq1BcNMjAxMDEyMTMyOTQ0WjAMMAoGA1UdFQQDCgEFMCMCBFnF -6tMXDTIwMTAxMjEzMjk1MVowDDAKBgNVHRUEAwoBBTAjAgRZxerRFw0yMTAyMjMx -NDI3MjFaMAwwCgYDVR0VBAMKAQUwIwIEWcXqzhcNMjEwMjIzMTQyNzE4WjAMMAoG -A1UdFQQDCgEFMCMCBFnF6sMXDTIwMDgwNDA5MjkxNlowDDAKBgNVHRUEAwoBBTAj -AgRZxeqRFw0yMTAzMDExMjAyMTBaMAwwCgYDVR0VBAMKAQUwIwIEWcXqkBcNMjEw -MzAxMTIwMjA3WjAMMAoGA1UdFQQDCgEFMCMCBFnF6akXDTIxMDMwMTEyMDI1Nlow -DDAKBgNVHRUEAwoBBTAjAgRZxemoFw0yMTAzMDExMjAyNTNaMAwwCgYDVR0VBAMK -AQUwIwIEWcXppRcNMjEwMzAxMTIwMjQzWjAMMAoGA1UdFQQDCgEFMCMCBFnF6aQX -DTIxMDMwMTEyMDI0MlowDDAKBgNVHRUEAwoBBTAjAgRZxemeFw0yMDA3MzAxNjMx -MTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXplxcNMjAwOTAyMTIwNTE2WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF6ZYXDTIwMDkwMjEyMDUxNFowDDAKBgNVHRUEAwoBBTAjAgRZ -xemUFw0yMDA5MDIxMjAxMTFaMAwwCgYDVR0VBAMKAQUwIwIEWcXpkxcNMjAwOTAy -MTIwMTA5WjAMMAoGA1UdFQQDCgEFMCMCBFnF6Y0XDTIwMDcyOTE4NDYzNVowDDAK -BgNVHRUEAwoBBTAjAgRZxemMFw0yMDA3MjkxODQ2MzhaMAwwCgYDVR0VBAMKAQUw -IwIEWcXpZRcNMjAwNzI5MTY1NDA4WjAMMAoGA1UdFQQDCgEFMCMCBFnF6UUXDTIw -MDcyODE5MzgwOVowDDAKBgNVHRUEAwoBBTAjAgRZxelEFw0yMDA3MjgxOTM3MDVa -MAwwCgYDVR0VBAMKAQUwIwIEWcXpQhcNMjAwNzI4MTkzNjIwWjAMMAoGA1UdFQQD -CgEFMCMCBFnF6UEXDTIwMDcyODE5MzU1MVowDDAKBgNVHRUEAwoBBTAjAgRZxelA -Fw0yMDA3MjgxOTExMzFaMAwwCgYDVR0VBAMKAQUwIwIEWcXpPxcNMjAwNzI4MTkx -MDI3WjAMMAoGA1UdFQQDCgEFMCMCBFnF6T0XDTIwMDcyODE5MDk0MVowDDAKBgNV -HRUEAwoBBTAjAgRZxek8Fw0yMDA3MjgxOTA5MTJaMAwwCgYDVR0VBAMKAQUwIwIE -WcXovhcNMjAwODI0MTAxMDM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF6L0XDTIwMDgy -NDEwMTAzMlowDDAKBgNVHRUEAwoBBTAjAgRZxei8Fw0yMDA3MjcxNDIxNDNaMAww -CgYDVR0VBAMKAQUwIwIEWcXoChcNMjAwOTAyMTIwNTA0WjAMMAoGA1UdFQQDCgEF -MCMCBFnF6AkXDTIwMDkwMjEyMDUwMlowDDAKBgNVHRUEAwoBBTAjAgRZxefgFw0y -MDA5MDIxMjA0NDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXn3hcNMjAwOTAyMTIwNDM4 -WjAMMAoGA1UdFQQDCgEFMBUCBFnF59gXDTIwMDgyNDExMjIwMlowFQIEWcXn1xcN -MjAwODI0MTEyMjAyWjAVAgRZxefWFw0yMDA4MjQxMTIyMDJaMCMCBFnF58sXDTIx -MDIwNDE1MzU1MlowDDAKBgNVHRUEAwoBBTAjAgRZxefDFw0yMDA5MDIxMjAzNTla -MAwwCgYDVR0VBAMKAQUwIwIEWcXnwhcNMjAwOTAyMTIwMzU3WjAMMAoGA1UdFQQD -CgEFMCMCBFnF58EXDTIwMDcyMzA4MzgwM1owDDAKBgNVHRUEAwoBBTAjAgRZxeeb -Fw0yMDA3MjIxNjUyMDRaMAwwCgYDVR0VBAMKAQUwIwIEWcXnkRcNMjAwNzIyMTMz -MjI4WjAMMAoGA1UdFQQDCgEFMCMCBFnF52AXDTIwMDcyMjEzNDY0OVowDDAKBgNV -HRUEAwoBBTAjAgRZxedZFw0yMDA3MjYyMDUyNDdaMAwwCgYDVR0VBAMKAQUwIwIE -WcXnWBcNMjAwNzI2MjA1MjM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF51cXDTIwMDgw -NDIxMDYxMlowDDAKBgNVHRUEAwoBBTAjAgRZxecfFw0yMDA3MjAxNTU2MThaMAww -CgYDVR0VBAMKAQUwIwIEWcXnEBcNMjAwNzIwMTQxMjQ2WjAMMAoGA1UdFQQDCgEF -MCMCBFnF5w8XDTIwMDcyMDE0MTE1NlowDDAKBgNVHRUEAwoBBTAjAgRZxebZFw0y -MDA3MTkxNTI2MzJaMAwwCgYDVR0VBAMKAQUwIwIEWcXmgBcNMjAwNzE3MTE1MDM5 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF5hEXDTIwMDgwNDIwNTYwNVowDDAKBgNVHRUE -AwoBBTAVAgRZxeYQFw0yMDA4MjQxMTIxNDhaMBUCBFnF5g8XDTIwMDgyNDExMjE0 -OFowIwIEWcXl4hcNMjAwNzE0MTE1OTE2WjAMMAoGA1UdFQQDCgEFMCMCBFnF5REX -DTIwMDcyNDEwNTQyM1owDDAKBgNVHRUEAwoBBTAjAgRZxeUQFw0yMDA3MjQxMDU0 -MjJaMAwwCgYDVR0VBAMKAQUwIwIEWcXkqhcNMjAwNzA3MTg0ODIzWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF5KkXDTIwMDcwNzE4NDgyMVowDDAKBgNVHRUEAwoBBTAjAgRZ -xeSeFw0yMDA3MDcxMTE2NTNaMAwwCgYDVR0VBAMKAQUwIwIEWcXkkhcNMjAwNzA3 -MDgzMDMwWjAMMAoGA1UdFQQDCgEFMCMCBFnF5JEXDTIwMDcwNzA4MzAyOFowDDAK -BgNVHRUEAwoBBTAjAgRZxeSPFw0yMDA3MDcwODI1MzVaMAwwCgYDVR0VBAMKAQUw -IwIEWcXkYBcNMjAwNzA2MTcyOTM4WjAMMAoGA1UdFQQDCgEFMCMCBFnF5F8XDTIw -MDcwNjE3Mjc0NlowDDAKBgNVHRUEAwoBBTAjAgRZxeRYFw0yMDA5MTUxMzQ1MTla -MAwwCgYDVR0VBAMKAQUwIwIEWcXjiRcNMjAwNzI0MDg0NDUyWjAMMAoGA1UdFQQD -CgEFMCMCBFnF4z8XDTIwMDcwMTExMDM0OFowDDAKBgNVHRUEAwoBBTAjAgRZxeM7 -Fw0yMDA3MDEwODQ3MDlaMAwwCgYDVR0VBAMKAQUwIwIEWcXjBhcNMjAwNzAyMTY1 -NDAyWjAMMAoGA1UdFQQDCgEFMCMCBFnF4s8XDTIwMDgwNDIwNTYwM1owDDAKBgNV -HRUEAwoBBTAjAgRZxeKrFw0yMDA2MjkxMDMwMDhaMAwwCgYDVR0VBAMKAQUwIwIE -WcXiqRcNMjAwNjI5MTQwMTI5WjAMMAoGA1UdFQQDCgEFMCMCBFnF4m4XDTIwMDYy -ODIwMTQxMFowDDAKBgNVHRUEAwoBBTAjAgRZxeJtFw0yMDA2MjgyMDE0MDNaMAww -CgYDVR0VBAMKAQUwIwIEWcXiZxcNMjAwNjI4MTIxNDI4WjAMMAoGA1UdFQQDCgEF -MBUCBFnF4a8XDTIwMDgyNDExMjIwMlowFQIEWcXhiBcNMjAwODI0MTEyMjAwWjAj -AgRZxeGHFw0yMDA2MjQxOTIyMjJaMAwwCgYDVR0VBAMKAQUwIwIEWcXhhhcNMjAw -NjI0MTQ0ODU0WjAMMAoGA1UdFQQDCgEFMCMCBFnF4XwXDTIwMDYyMzIxNDI0N1ow -DDAKBgNVHRUEAwoBBTAjAgRZxeF7Fw0yMDA2MjMyMTQxNTdaMAwwCgYDVR0VBAMK -AQUwIwIEWcXheRcNMjAwNjIzMjE0MDU1WjAMMAoGA1UdFQQDCgEFMCMCBFnF4XgX -DTIwMDYyMzIxNDAyNVowDDAKBgNVHRUEAwoBBTAjAgRZxeF3Fw0yMDA2MjMyMTI5 -MjVaMAwwCgYDVR0VBAMKAQUwIwIEWcXhdhcNMjAwNjIzMjEyODI5WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF4XQXDTIwMDYyMzIxMjczMlowDDAKBgNVHRUEAwoBBTAjAgRZ -xeFzFw0yMDA2MjMyMTI3MDJaMAwwCgYDVR0VBAMKAQUwIwIEWcXhOBcNMjAwNjI5 -MTAyOTUxWjAMMAoGA1UdFQQDCgEFMCMCBFnF4TcXDTIwMDYyMzE0MzUwMVowDDAK -BgNVHRUEAwoBBTAjAgRZxeE0Fw0yMDA2MjMxMzM4MTNaMAwwCgYDVR0VBAMKAQUw -IwIEWcXhMRcNMjAwNjIzMTIyOTI5WjAMMAoGA1UdFQQDCgEFMCMCBFnF4ScXDTIw -MDYyNDE0MzAxOFowDDAKBgNVHRUEAwoBBTAjAgRZxeEiFw0yMDA2MjMwODUzMjda -MAwwCgYDVR0VBAMKAQUwIwIEWcXg3hcNMjAwNjIzMTIwMzQ3WjAMMAoGA1UdFQQD -CgEFMBUCBFnF4NgXDTIwMDgyNDExMjIwMVowFQIEWcXg1xcNMjAwODI0MTEyMjAx -WjAVAgRZxeDWFw0yMDA4MjQxMTIyMDFaMBUCBFnF4NUXDTIwMDgyNDExMjIwMVow -IwIEWcXg1BcNMjAwNjIzMTE0MDQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnF4NMXDTIw -MDYyMzExMTM0NFowDDAKBgNVHRUEAwoBBTAjAgRZxeCpFw0yMDA2MjExNDU5MzZa -MAwwCgYDVR0VBAMKAQUwIwIEWcXgBhcNMjAwNjE5MTIwMjA3WjAMMAoGA1UdFQQD -CgEFMCMCBFnF4AQXDTIwMDYxODExMjY0NFowDDAKBgNVHRUEAwoBBTAjAgRZxeAD -Fw0yMDA2MTgxMTMxNDZaMAwwCgYDVR0VBAMKAQUwFQIEWcXf3RcNMjAwODI0MTEy -MTQzWjAVAgRZxd/ZFw0yMDA4MjQxMTIxNDNaMCMCBFnF38cXDTIwMDYxNzA1MDEz -M1owDDAKBgNVHRUEAwoBBTAjAgRZxd/FFw0yMDA2MTcwNTAwNTZaMAwwCgYDVR0V -BAMKAQUwIwIEWcXfxBcNMjAwNjE3MDMyNzUzWjAMMAoGA1UdFQQDCgEFMCMCBFnF -35QXDTIxMDMwNDE5NDYxN1owDDAKBgNVHRUEAwoBBTAjAgRZxd+SFw0yMDA2MTYx -NjE4MzRaMAwwCgYDVR0VBAMKAQUwIwIEWcXfjhcNMjAwNjE2MTc0MzQyWjAMMAoG -A1UdFQQDCgEFMCMCBFnF32UXDTIwMDgzMTEzNTUzMVowDDAKBgNVHRUEAwoBBTAj -AgRZxd9eFw0yMDA2MTYwOTA1NDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXfXRcNMjAw -NjE4MTUyNzQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnF3poXDTIxMDIwNDE1MzU0OFow -DDAKBgNVHRUEAwoBBTAjAgRZxd6ZFw0yMDA2MTYwOTA2MDBaMAwwCgYDVR0VBAMK -AQUwIwIEWcXemBcNMjEwMjA0MTUzNTQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnF3pQX -DTIwMDYxMjEwMDIzMVowDDAKBgNVHRUEAwoBBTAjAgRZxd6SFw0yMDA2MTIxMTU0 -MDZaMAwwCgYDVR0VBAMKAQUwIwIEWcXejxcNMjAwNjExMTA0NzA5WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF3o0XDTIwMDYxMTEwMjYxNVowDDAKBgNVHRUEAwoBBTAjAgRZ -xd6LFw0yMTAyMjUxMTExMzFaMAwwCgYDVR0VBAMKAQUwIwIEWcXeWRcNMjAwNjEy -MTAwMjIyWjAMMAoGA1UdFQQDCgEFMCMCBFnF3k8XDTIwMDYxMDExMzMzNlowDDAK -BgNVHRUEAwoBBTAjAgRZxd5OFw0yMDA2MTAxMTMzMTBaMAwwCgYDVR0VBAMKAQUw -IwIEWcXeTRcNMjEwMjI1MTExMzEzWjAMMAoGA1UdFQQDCgEFMCMCBFnF3g4XDTIw -MTExNjE4MzUyMFowDDAKBgNVHRUEAwoBBTAjAgRZxd4NFw0yMDExMTYxODM1NDBa -MAwwCgYDVR0VBAMKAQUwIwIEWcXd2xcNMjAwNjA4MTQ0OTQ4WjAMMAoGA1UdFQQD -CgEFMCMCBFnF3doXDTIwMTAxNDA4MjgzN1owDDAKBgNVHRUEAwoBBTAjAgRZxd3S -Fw0yMDA2MDgwODM0MzJaMAwwCgYDVR0VBAMKAQUwIwIEWcXdBxcNMjAxMDE0MDgz -MDI0WjAMMAoGA1UdFQQDCgEFMCMCBFnF3QYXDTIwMTAxNDA4MzAyMlowDDAKBgNV -HRUEAwoBBTAjAgRZxdzGFw0yMDA2MDMyMDM2NTNaMAwwCgYDVR0VBAMKAQUwIwIE -WcXckRcNMjEwMjI1MTEyNDAxWjAMMAoGA1UdFQQDCgEFMCMCBFnF3JAXDTIxMDIy -NTExMTM1OFowDDAKBgNVHRUEAwoBBTAjAgRZxdyMFw0yMTAyMjUxMTEyMjJaMAww -CgYDVR0VBAMKAQUwIwIEWcXcixcNMjEwMjI1MTExMjE5WjAMMAoGA1UdFQQDCgEF -MCMCBFnF3IoXDTIxMDIyNTExMTEwM1owDDAKBgNVHRUEAwoBBTAjAgRZxdyGFw0y -MTAyMjUxMTA4MThaMAwwCgYDVR0VBAMKAQUwIwIEWcXchRcNMjEwMjI1MTEwODE2 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF3IMXDTIxMDIyNTExMTAxNFowDDAKBgNVHRUE -AwoBBTAjAgRZxdyCFw0yMTAyMjUxMTEwMTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXc -gRcNMjAwNjAzMDg0OTI2WjAMMAoGA1UdFQQDCgEFMCMCBFnF3H4XDTIxMDIyNTEx -MTIzNlowDDAKBgNVHRUEAwoBBTAjAgRZxdx9Fw0yMTAyMjUxMTEyMzVaMAwwCgYD -VR0VBAMKAQUwIwIEWcXcexcNMjAwNjAzMDg0OTEzWjAMMAoGA1UdFQQDCgEFMCMC -BFnF3HkXDTIxMDIyNTExMDk1NVowDDAKBgNVHRUEAwoBBTAjAgRZxdx4Fw0yMTAy -MjUxMTA5NTNaMAwwCgYDVR0VBAMKAQUwIwIEWcXcdxcNMjEwMjA0MTUzNTQyWjAM -MAoGA1UdFQQDCgEFMCMCBFnF3HMXDTIwMDYwMzA4MTk0MVowDDAKBgNVHRUEAwoB -BTAjAgRZxdxyFw0yMDA2MDMwODE5MTBaMAwwCgYDVR0VBAMKAQUwIwIEWcXcbhcN -MjEwMjI1MTEwNzU4WjAMMAoGA1UdFQQDCgEFMCMCBFnF3G0XDTIxMDIyNTExMDc1 -N1owDDAKBgNVHRUEAwoBBTAjAgRZxdxpFw0yMTAyMjUxMTA2NDJaMAwwCgYDVR0V -BAMKAQUwIwIEWcXcaBcNMjEwMjI1MTEwNjM5WjAMMAoGA1UdFQQDCgEFMCMCBFnF -3GQXDTIxMDIyNTExMDgwN1owDDAKBgNVHRUEAwoBBTAjAgRZxdxjFw0yMTAyMjUx -MTA4MDRaMAwwCgYDVR0VBAMKAQUwIwIEWcXcYRcNMjAwNjAzMDcxNTEwWjAMMAoG -A1UdFQQDCgEFMCMCBFnF3GAXDTIwMDYwMzA3MTUyMFowDDAKBgNVHRUEAwoBBTAj -AgRZxdxeFw0yMDA2MDMwNzAwNDNaMAwwCgYDVR0VBAMKAQUwIwIEWcXcXRcNMjAw -NjAzMDcwMDM2WjAMMAoGA1UdFQQDCgEFMCMCBFnF3FwXDTIwMDYwMzAwNTU0MFow -DDAKBgNVHRUEAwoBBTAjAgRZxdxbFw0yMDA2MDMwMDU0MzRaMAwwCgYDVR0VBAMK -AQUwIwIEWcXcWRcNMjAwNjAzMDA1MzQ3WjAMMAoGA1UdFQQDCgEFMCMCBFnF3FgX -DTIwMDYwMzAwNTMxOFowDDAKBgNVHRUEAwoBBTAjAgRZxdxUFw0yMTAyMjUxMTA3 -NDJaMAwwCgYDVR0VBAMKAQUwIwIEWcXcUxcNMjEwMjI1MTEwNzM4WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF3E8XDTIxMDIyNTExMzgzMFowDDAKBgNVHRUEAwoBBTAjAgRZ -xdxOFw0yMTAyMjUxMTM4MjhaMAwwCgYDVR0VBAMKAQUwIwIEWcXcTRcNMjAwNjAz -MDAyNDU2WjAMMAoGA1UdFQQDCgEFMCMCBFnF3EwXDTIwMDYwMzAwMjM0OFowDDAK -BgNVHRUEAwoBBTAjAgRZxdxKFw0yMDA2MDMwMDIzMDJaMAwwCgYDVR0VBAMKAQUw -IwIEWcXcSRcNMjAwNjAzMDAyMjM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF3EUXDTIx -MDIyNTExMjY0NVowDDAKBgNVHRUEAwoBBTAjAgRZxdxEFw0yMTAyMjUxMTA2Mzda -MAwwCgYDVR0VBAMKAQUwIwIEWcXcQhcNMjAwNjAyMjM1OTQxWjAMMAoGA1UdFQQD -CgEFMCMCBFnF3EAXDTIwMDYwMjIzNTg1NFowDDAKBgNVHRUEAwoBBTAjAgRZxdw/ -Fw0yMDA2MDIyMzU4MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcXcPhcNMjEwMjI1MTEw -OTU4WjAMMAoGA1UdFQQDCgEFMCMCBFnF3D0XDTIxMDIyNTExMDkyMFowDDAKBgNV -HRUEAwoBBTAjAgRZxdwTFw0yMDA3MTUxMDMxMTRaMAwwCgYDVR0VBAMKAQUwIwIE -WcXcEhcNMjAwNzE1MTAzMTA3WjAMMAoGA1UdFQQDCgEFMCMCBFnF3A8XDTIwMDcx -NTEwMzA1OVowDDAKBgNVHRUEAwoBBTAjAgRZxdwLFw0yMDA3MTUxMDMwNDhaMAww -CgYDVR0VBAMKAQUwIwIEWcXcCRcNMjAwOTIyMTE0MDU2WjAMMAoGA1UdFQQDCgEF -MCMCBFnF2/QXDTIxMDIwNDE1NTA0NVowDDAKBgNVHRUEAwoBBTAjAgRZxdvzFw0y -MDA2MDMxMDM1NTZaMAwwCgYDVR0VBAMKAQUwIwIEWcXb7xcNMjEwMjA0MTU1MDM0 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF2+0XDTIwMDYxMDA4NTUzM1owDDAKBgNVHRUE -AwoBBTAjAgRZxdvsFw0yMDA2MTAwODU1MzFaMAwwCgYDVR0VBAMKAQUwIwIEWcXb -6xcNMjAwNjAyMDkxMTE4WjAMMAoGA1UdFQQDCgEFMCMCBFnF2+oXDTIwMDYwMjA5 -MTAxMlowDDAKBgNVHRUEAwoBBTAjAgRZxdvoFw0yMDA2MDIwOTA5MzFaMAwwCgYD -VR0VBAMKAQUwIwIEWcXb5xcNMjAwNjAyMDkwOTA3WjAMMAoGA1UdFQQDCgEFMCMC -BFnF2+YXDTIxMDIyNTExMTMzMVowDDAKBgNVHRUEAwoBBTAjAgRZxdvlFw0yMTAy -MjUxMTEzMDhaMAwwCgYDVR0VBAMKAQUwIwIEWcXb5BcNMjEwMjI1MTExMTIxWjAM -MAoGA1UdFQQDCgEFMCMCBFnF2+MXDTIxMDIyNTExMTA0NVowDDAKBgNVHRUEAwoB -BTAjAgRZxdviFw0yMTAyMjUxMTA4NDdaMAwwCgYDVR0VBAMKAQUwIwIEWcXb4RcN -MjAwNjAyMDg0NzM5WjAMMAoGA1UdFQQDCgEFMCMCBFnF2+AXDTIwMDYwMjA4NDYz -OVowDDAKBgNVHRUEAwoBBTAjAgRZxdveFw0yMDA2MDIwODQ1NThaMAwwCgYDVR0V -BAMKAQUwIwIEWcXb3RcNMjAwNjAyMDg0NTMzWjAMMAoGA1UdFQQDCgEFMCMCBFnF -29wXDTIxMDIyNTExMTkxM1owDDAKBgNVHRUEAwoBBTAjAgRZxdtbFw0yMTAyMjUx -MTA4MDhaMAwwCgYDVR0VBAMKAQUwIwIEWcXbWhcNMjAwNTMwMTAwOTM5WjAMMAoG -A1UdFQQDCgEFMCMCBFnF21kXDTIwMDUzMDEwMDgzOVowDDAKBgNVHRUEAwoBBTAj -AgRZxdtXFw0yMDA1MzAxMDA4MDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXbVhcNMjAw -NTMwMTAwNzM1WjAMMAoGA1UdFQQDCgEFMCMCBFnF21UXDTIwMDUzMDA5NTExMlow -DDAKBgNVHRUEAwoBBTAjAgRZxdtUFw0yMDA1MzAwOTUwMTNaMAwwCgYDVR0VBAMK -AQUwIwIEWcXbUhcNMjAwNTMwMDk0OTM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF21EX -DTIwMDUzMDA5NDkxMVowDDAKBgNVHRUEAwoBBTAjAgRZxdsgFw0yMDEwMDcxMDU5 -NDdaMAwwCgYDVR0VBAMKAQUwIwIEWcXbHBcNMjAwNTI5MTEzOTExWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF2xsXDTIwMDUyOTExMzgwM1owDDAKBgNVHRUEAwoBBTAjAgRZ -xdsZFw0yMDA1MjkxMTM3MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcXbGBcNMjAwNTI5 -MTEzNzAwWjAMMAoGA1UdFQQDCgEFMCMCBFnF2xQXDTIwMDUyOTExMjk0NFowDDAK -BgNVHRUEAwoBBTAjAgRZxdsTFw0yMDA1MjkxMTI5MjBaMAwwCgYDVR0VBAMKAQUw -IwIEWcXbERcNMjEwMjI1MTExMTQzWjAMMAoGA1UdFQQDCgEFMCMCBFnF2w8XDTIx -MDIyNTExMDkyNVowDDAKBgNVHRUEAwoBBTAjAgRZxdsLFw0yMTAyMjUxMTA4Mjda -MAwwCgYDVR0VBAMKAQUwIwIEWcXbChcNMjEwMjI1MTEwODI1WjAMMAoGA1UdFQQD -CgEFMCMCBFnF2wkXDTIxMDIyNTExMzgxMFowDDAKBgNVHRUEAwoBBTAjAgRZxdsI -Fw0yMTAyMjUxMTA4MTNaMAwwCgYDVR0VBAMKAQUwIwIEWcXbBxcNMjEwMjI1MTEx -NjQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnF2wYXDTIwMDUyOTEwNTQ1M1owDDAKBgNV -HRUEAwoBBTAjAgRZxdsFFw0yMDA1MjkxMDUzNTRaMAwwCgYDVR0VBAMKAQUwIwIE -WcXbAxcNMjAwNTI5MTA1MzE2WjAMMAoGA1UdFQQDCgEFMCMCBFnF2wIXDTIwMDUy -OTEwNTI1MVowDDAKBgNVHRUEAwoBBTAjAgRZxdsBFw0yMDA1MjkxMDQ0MDVaMAww -CgYDVR0VBAMKAQUwIwIEWcXbABcNMjAwNTI5MTA0MzA0WjAMMAoGA1UdFQQDCgEF -MCMCBFnF2v4XDTIwMDUyOTEwNDIyM1owDDAKBgNVHRUEAwoBBTAjAgRZxdr9Fw0y -MDA1MjkxMDQyMDBaMAwwCgYDVR0VBAMKAQUwIwIEWcXa/BcNMjEwMjI1MTExNzUy -WjAMMAoGA1UdFQQDCgEFMCMCBFnF2vgXDTIwMDkwMjEyMDMzNlowDDAKBgNVHRUE -AwoBBTAjAgRZxdr3Fw0yMDA5MDIxMjEzMzVaMAwwCgYDVR0VBAMKAQUwIwIEWcXa -8hcNMjAwOTAyMTEzNjE5WjAMMAoGA1UdFQQDCgEFMCMCBFnF2vEXDTIwMDkwMjEx -MzYxNlowDDAKBgNVHRUEAwoBBTAjAgRZxdrwFw0yMDA5MDIxMTM2NTBaMAwwCgYD -VR0VBAMKAQUwIwIEWcXa7hcNMjAwOTAyMTEzNjQ4WjAMMAoGA1UdFQQDCgEFMCMC -BFnF2usXDTIwMDkwMjExMzYzNFowDDAKBgNVHRUEAwoBBTAjAgRZxdrqFw0yMDA5 -MDIxMTM2MzJaMAwwCgYDVR0VBAMKAQUwIwIEWcXa6BcNMjAwOTAyMTIwMzUwWjAM -MAoGA1UdFQQDCgEFMCMCBFnF2ucXDTIwMDkwMjEyMDM0NlowDDAKBgNVHRUEAwoB -BTAjAgRZxdrlFw0yMDA5MDIxMjAzMjNaMAwwCgYDVR0VBAMKAQUwIwIEWcXa5BcN -MjAwOTAyMTIwMzIxWjAMMAoGA1UdFQQDCgEFMCMCBFnF2oIXDTIwMDkwMjEyMTAw -N1owDDAKBgNVHRUEAwoBBTAjAgRZxdqBFw0yMDA5MDIxMjEwMDNaMAwwCgYDVR0V -BAMKAQUwIwIEWcXaURcNMjAwOTAyMTIwMzAwWjAMMAoGA1UdFQQDCgEFMCMCBFnF -2lAXDTIwMDkwMjEyMDI1OFowDDAKBgNVHRUEAwoBBTAjAgRZxdmjFw0yMDA1MjIx -NjI1NDhaMAwwCgYDVR0VBAMKAQUwIwIEWcXZoRcNMjAwNTIyMTYyNTU1WjAMMAoG -A1UdFQQDCgEFMCMCBFnF2Z0XDTIwMDUyMjE1MTAzNlowDDAKBgNVHRUEAwoBBTAj -AgRZxdmbFw0yMDEwMTQwODI4MzZaMAwwCgYDVR0VBAMKAQUwIwIEWcXZmhcNMjAx -MDE0MDgyODMzWjAMMAoGA1UdFQQDCgEFMCMCBFnF2ZkXDTIwMDUyMjE2MjYwN1ow -DDAKBgNVHRUEAwoBBTAVAgRZxdmYFw0yMDA4MjQxMTIyMDFaMBUCBFnF2ZcXDTIw -MDgyNDExMjIwMVowIwIEWcXZlhcNMjAwNTIyMTYyNjIzWjAMMAoGA1UdFQQDCgEF -MCMCBFnF2ZUXDTIwMDUyMjE2MjYzOFowDDAKBgNVHRUEAwoBBTAVAgRZxdmUFw0y -MDA4MjQxMTIyMDFaMCMCBFnF2YYXDTIwMDUyMTE4MTIzMlowDDAKBgNVHRUEAwoB -BTAjAgRZxdlUFw0yMDA2MDQxMTA4MjBaMAwwCgYDVR0VBAMKAQUwIwIEWcXZUxcN -MjAwNjA0MTEwODI3WjAMMAoGA1UdFQQDCgEFMCMCBFnF2U0XDTIwMDUyMTExMDA1 -OVowDDAKBgNVHRUEAwoBBTAjAgRZxdlMFw0yMDA1MjExMDU5NDJaMAwwCgYDVR0V -BAMKAQUwIwIEWcXZShcNMjAwNTIxMTA1ODU3WjAMMAoGA1UdFQQDCgEFMCMCBFnF -2UkXDTIwMDUyMTEwNTgzMlowDDAKBgNVHRUEAwoBBTAjAgRZxdlFFw0yMTAyMjUx -MTA5MDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXZRBcNMjEwMjI1MTEwODU5WjAMMAoG -A1UdFQQDCgEFMCMCBFnF2UEXDTIwMDUyMTEwMjYxNVowDDAKBgNVHRUEAwoBBTAj -AgRZxdk/Fw0yMDA1MjExMDI1MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcXZPRcNMjAw -NTIxMTAyNDIxWjAMMAoGA1UdFQQDCgEFMCMCBFnF2TwXDTIwMDUyMTEwMjM1N1ow -DDAKBgNVHRUEAwoBBTAjAgRZxdk5Fw0yMTAyMjUxMTA4MjFaMAwwCgYDVR0VBAMK -AQUwIwIEWcXZOBcNMjEwMjI1MTExMDI1WjAMMAoGA1UdFQQDCgEFMCMCBFnF2TYX -DTIwMDcwMTEyNTkxNFowDDAKBgNVHRUEAwoBBTAjAgRZxdk1Fw0yMDA3MDExMjU5 -MDZaMAwwCgYDVR0VBAMKAQUwIwIEWcXZBxcNMjAwNzAxMTQxMTQzWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF2QYXDTIwMDcwMTE0MTEzM1owDDAKBgNVHRUEAwoBBTAjAgRZ -xdiHFw0yMTAyMjUxNjE1MjdaMAwwCgYDVR0VBAMKAQUwIwIEWcXYhhcNMjEwMjI1 -MTYxNTI1WjAMMAoGA1UdFQQDCgEFMCMCBFnF2IQXDTIxMDIyNTE2MTUzM1owDDAK -BgNVHRUEAwoBBTAjAgRZxdiCFw0yMTAyMjUxNjE1MzFaMAwwCgYDVR0VBAMKAQUw -IwIEWcXYgBcNMjEwMjI1MTYxNDExWjAMMAoGA1UdFQQDCgEFMCMCBFnF2H8XDTIx -MDIyNTE2MTQwOVowDDAKBgNVHRUEAwoBBTAjAgRZxdh9Fw0yMTAyMjUxNjE1MTda -MAwwCgYDVR0VBAMKAQUwIwIEWcXYfBcNMjEwMjI1MTYxNTE2WjAMMAoGA1UdFQQD -CgEFMCMCBFnF2HsXDTIxMDIyNTE2MTQyNVowDDAKBgNVHRUEAwoBBTAjAgRZxdh5 -Fw0yMTAyMjUxNjEzNDhaMAwwCgYDVR0VBAMKAQUwIwIEWcXYeBcNMjEwMjI1MTYx -MzQ2WjAMMAoGA1UdFQQDCgEFMCMCBFnF2G4XDTIxMDIyNTE2MTUwNVowDDAKBgNV -HRUEAwoBBTAjAgRZxdhtFw0yMTAyMjUxNjE1MDRaMAwwCgYDVR0VBAMKAQUwIwIE -WcXYaxcNMjEwMjI1MTYxNTAwWjAMMAoGA1UdFQQDCgEFMCMCBFnF2GoXDTIxMDIy -NTE2MTQ1OVowDDAKBgNVHRUEAwoBBTAjAgRZxdg/Fw0yMTAyMjUxNjE0MDBaMAww -CgYDVR0VBAMKAQUwIwIEWcXYPhcNMjEwMjI1MTYxMzU5WjAMMAoGA1UdFQQDCgEF -MCMCBFnF2DwXDTIxMDIyNTE2MTUyM1owDDAKBgNVHRUEAwoBBTAjAgRZxdg7Fw0y -MTAyMjUxNjE1MjBaMAwwCgYDVR0VBAMKAQUwIwIEWcXYORcNMjEwMjI1MTYxNDA2 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF2DgXDTIxMDIyNTE2MTQwNFowDDAKBgNVHRUE -AwoBBTAjAgRZxdg3Fw0yMTAyMjUxNjE0MjBaMAwwCgYDVR0VBAMKAQUwIwIEWcXX -0BcNMjAxMTE2MTgyOTAxWjAMMAoGA1UdFQQDCgEFMCMCBFnF188XDTIwMTExNjE4 -Mjg0NlowDDAKBgNVHRUEAwoBBTAjAgRZxdfOFw0yMDA5MTcxNTI4MjNaMAwwCgYD -VR0VBAMKAQUwIwIEWcXXzBcNMjAwOTE3MTUyODE0WjAMMAoGA1UdFQQDCgEFMBUC -BFnF18oXDTIwMDgyNDExMjIwMFowFQIEWcXXyRcNMjAwODI0MTEyMjAwWjAVAgRZ -xdfIFw0yMDA4MjQxMTIyMDBaMCMCBFnF18YXDTIwMDkwMjEyMDI0OFowDDAKBgNV -HRUEAwoBBTAjAgRZxdfFFw0yMDA5MDIxMjAyNDZaMAwwCgYDVR0VBAMKAQUwIwIE -WcXXlxcNMjAwOTAyMTIwNDE0WjAMMAoGA1UdFQQDCgEFMCMCBFnF15YXDTIwMDkw -MjEyMDQxMVowDDAKBgNVHRUEAwoBBTAjAgRZxdePFw0yMDA5MDIxMjAzMTRaMAww -CgYDVR0VBAMKAQUwIwIEWcXXjhcNMjAwOTAyMTIwMzEwWjAMMAoGA1UdFQQDCgEF -MCMCBFnF12AXDTIwMDUxMzE2NTczMVowDDAKBgNVHRUEAwoBBTAjAgRZxddfFw0y -MDA5MjYxMTA5MDJaMAwwCgYDVR0VBAMKAQUwIwIEWcXXURcNMjAwNTEzMTQyOTE3 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF108XDTIwMDYwMjE1Mjc0N1owDDAKBgNVHRUE -AwoBBTAjAgRZxddOFw0yMDA2MDIxNTI3NDVaMAwwCgYDVR0VBAMKAQUwIwIEWcXX -SxcNMjAwNTEzMTIzMjAxWjAMMAoGA1UdFQQDCgEFMCMCBFnF1tYXDTIwMDUxMjA3 -MzUzOFowDDAKBgNVHRUEAwoBBTAjAgRZxdbRFw0yMDA2MjgxMDU3MjlaMAwwCgYD -VR0VBAMKAQUwIwIEWcXWdxcNMjAwOTAyMTE1OTAxWjAMMAoGA1UdFQQDCgEFMCMC -BFnF1nYXDTIwMDkwMjExNTg1OVowDDAKBgNVHRUEAwoBBTAjAgRZxdZ0Fw0yMDA5 -MDIxMjAyMTdaMAwwCgYDVR0VBAMKAQUwIwIEWcXWcxcNMjAwOTAyMTIwMjE0WjAM -MAoGA1UdFQQDCgEFMCMCBFnF1nIXDTIwMDkwMjEyMDIwNFowDDAKBgNVHRUEAwoB -BTAjAgRZxdZwFw0yMDA5MDIxMjAyMDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXWQRcN -MjAwNjI4MTA1NzQ2WjAMMAoGA1UdFQQDCgEFMCMCBFnF1hMXDTIwMDUxMTE2MjM1 -MFowDDAKBgNVHRUEAwoBBTAjAgRZxdYSFw0yMDA1MTExNjIzNDhaMAwwCgYDVR0V -BAMKAQUwIwIEWcXWDhcNMjAwNTA3MTUzODQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnF -1g0XDTIwMDUwNzE1MzgyMFowDDAKBgNVHRUEAwoBBTAjAgRZxdYMFw0yMDA3MDMx -MTUzMjNaMAwwCgYDVR0VBAMKAQUwIwIEWcXWCRcNMjAwNTExMTYyNDAzWjAMMAoG -A1UdFQQDCgEFMCMCBFnF1ggXDTIwMDUxMTE2MjQwMlowDDAKBgNVHRUEAwoBBTAj -AgRZxdYHFw0yMDA1MTExNjI0MjFaMAwwCgYDVR0VBAMKAQUwIwIEWcXWBRcNMjAw -NzAzMTE1MzE1WjAMMAoGA1UdFQQDCgEFMCMCBFnF1gIXDTIwMDUxMTE2MjUyM1ow -DDAKBgNVHRUEAwoBBTAjAgRZxdYBFw0yMDA1MTExNjI1MjJaMAwwCgYDVR0VBAMK -AQUwIwIEWcXWABcNMjAwNTExMTYyNTM4WjAMMAoGA1UdFQQDCgEFMCMCBFnF1f8X -DTIwMDUxMTE2MjU1MFowDDAKBgNVHRUEAwoBBTAjAgRZxdX7Fw0yMDA1MTExNjI2 -MzdaMAwwCgYDVR0VBAMKAQUwIwIEWcXV+hcNMjAwNTExMTYyNjM2WjAMMAoGA1Ud -FQQDCgEFMCMCBFnF1fYXDTIwMDUwNzE0MTI1MFowDDAKBgNVHRUEAwoBBTAjAgRZ -xdX1Fw0yMDA1MDcxNDEyMjRaMAwwCgYDVR0VBAMKAQUwIwIEWcXV9BcNMjAwNTEx -MTYyNjQ5WjAMMAoGA1UdFQQDCgEFMCMCBFnF1fAXDTIwMDUwNzEzNTUwNlowDDAK -BgNVHRUEAwoBBTAjAgRZxdXvFw0yMDA1MDcxMzU0NDJaMAwwCgYDVR0VBAMKAQUw -IwIEWcXV6hcNMjAwNTA3MTM0MTU1WjAMMAoGA1UdFQQDCgEFMCMCBFnF1ekXDTIw -MDUwNzEzNDEyOVowDDAKBgNVHRUEAwoBBTAjAgRZxdXnFw0yMDA2MTExMDI3MDFa -MAwwCgYDVR0VBAMKAQUwIwIEWcXV5RcNMjAwNTA3MTMxNzIwWjAMMAoGA1UdFQQD -CgEFMCMCBFnF1eQXDTIwMDUwNzEzMTY1NVowDDAKBgNVHRUEAwoBBTAjAgRZxdXi -Fw0yMDA2MTAxMTM0MjBaMAwwCgYDVR0VBAMKAQUwIwIEWcXV4BcNMjAwNTA3MTMw -OTI5WjAMMAoGA1UdFQQDCgEFMCMCBFnF1d8XDTIwMDUwNzEzMDkwN1owDDAKBgNV -HRUEAwoBBTAjAgRZxdXeFw0yMTAyMjUxMTM5MTlaMAwwCgYDVR0VBAMKAQUwIwIE -WcXV3RcNMjEwMjI1MTExMjQwWjAMMAoGA1UdFQQDCgEFMCMCBFnF1dsXDTIwMDUw -NzE1MzkyOVowDDAKBgNVHRUEAwoBBTAjAgRZxdXZFw0yMTAyMjUxMTA3MTRaMAww -CgYDVR0VBAMKAQUwIwIEWcXV2BcNMjEwMjI1MTEwNzEyWjAMMAoGA1UdFQQDCgEF -MCMCBFnF1dcXDTIxMDIyNTExMTA1NFowDDAKBgNVHRUEAwoBBTAjAgRZxdXWFw0y -MDA2MTExMDI4MTVaMAwwCgYDVR0VBAMKAQUwIwIEWcXV1RcNMjAwNTA3MTQxMzMx -WjAMMAoGA1UdFQQDCgEFMCMCBFnF1dMXDTIxMDIyNTExMDgzOVowDDAKBgNVHRUE -AwoBBTAjAgRZxdXSFw0yMTAyMjUxMTA4MzdaMAwwCgYDVR0VBAMKAQUwIwIEWcXV -0RcNMjAwNjEwMTEzNTMwWjAMMAoGA1UdFQQDCgEFMCMCBFnF1dAXDTIwMDUwNzEz -NTU0N1owDDAKBgNVHRUEAwoBBTAjAgRZxdXOFw0yMDA1MDcxMjA0MTBaMAwwCgYD -VR0VBAMKAQUwIwIEWcXVzRcNMjAwNTA3MTIwNDA5WjAMMAoGA1UdFQQDCgEFMCMC -BFnF1cwXDTIwMDUwNzEzNDUzOFowDDAKBgNVHRUEAwoBBTAjAgRZxdXLFw0yMDA1 -MDcxMzQyMzZaMAwwCgYDVR0VBAMKAQUwIwIEWcXVyRcNMjAwNTExMTYzMDE1WjAM -MAoGA1UdFQQDCgEFMCMCBFnF1cgXDTIwMDUxMTE2MzAxNFowDDAKBgNVHRUEAwoB -BTAjAgRZxdXHFw0yMTAyMjUxMTA3NTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXVxRcN -MjAwOTAyMTIwMTQ2WjAMMAoGA1UdFQQDCgEFMCMCBFnF1cQXDTIwMDkwMjEyMDE0 -NFowDDAKBgNVHRUEAwoBBTAjAgRZxdXCFw0yMDA5MDIxMjAyMjhaMAwwCgYDVR0V -BAMKAQUwIwIEWcXVwRcNMjAwOTAyMTIwMjI2WjAMMAoGA1UdFQQDCgEFMCMCBFnF -1b4XDTIwMDUwNzA1MDY1MVowDDAKBgNVHRUEAwoBBTAjAgRZxdWUFw0yMDA1MTIw -NzM1MzFaMAwwCgYDVR0VBAMKAQUwIwIEWcXVkhcNMjAwNTA4MTU0MjU2WjAMMAoG -A1UdFQQDCgEFMBUCBFnF1Y8XDTIwMDgyNDExMjE1OVowIwIEWcXVjhcNMjAwNTA2 -MTEwMjAyWjAMMAoGA1UdFQQDCgEFMCMCBFnF1YcXDTIwMDUxOTExNDQ0N1owDDAK -BgNVHRUEAwoBBTAjAgRZxdWGFw0yMDA1MDYwNjUwMDVaMAwwCgYDVR0VBAMKAQUw -IwIEWcXVWRcNMjAwNTA1MTUzNDM2WjAMMAoGA1UdFQQDCgEFMCMCBFnF1VgXDTIw -MDUwNTE1MzQwOVowDDAKBgNVHRUEAwoBBTAjAgRZxdVXFw0yMDA1MDcxMjU3MTVa -MAwwCgYDVR0VBAMKAQUwIwIEWcXVVhcNMjAwNTA3MTI1NzA4WjAMMAoGA1UdFQQD -CgEFMCMCBFnF1VQXDTIwMDUwNTE1MjY1MFowDDAKBgNVHRUEAwoBBTAjAgRZxdVT -Fw0yMDA1MDUxNTI2MjFaMAwwCgYDVR0VBAMKAQUwIwIEWcXVUhcNMjAwNTA3MTI1 -NzAxWjAMMAoGA1UdFQQDCgEFMCMCBFnF1VEXDTIwMDUwNzEyNDE0OVowDDAKBgNV -HRUEAwoBBTAjAgRZxdVPFw0yMDA1MDUxNTE0NDVaMAwwCgYDVR0VBAMKAQUwIwIE -WcXVThcNMjAwNTA1MTUxNDE4WjAMMAoGA1UdFQQDCgEFMCMCBFnF1U0XDTIwMDUw -NTE1MTI0OFowDDAKBgNVHRUEAwoBBTAjAgRZxdVMFw0yMDA1MDUxNTAxNDhaMAww -CgYDVR0VBAMKAQUwIwIEWcXVShcNMjAwNTA1MTQ1OTQ5WjAMMAoGA1UdFQQDCgEF -MCMCBFnF1UkXDTIwMDUwNTE0NTk0MVowDDAKBgNVHRUEAwoBBTAjAgRZxdVHFw0y -MDA1MTQxNjU2MzhaMAwwCgYDVR0VBAMKAQUwIwIEWcXVHBcNMjAwNTA1MTA1NTQw -WjAMMAoGA1UdFQQDCgEFMCMCBFnF1RcXDTIwMDUwNTE1MDE0MlowDDAKBgNVHRUE -AwoBBTAjAgRZxdUVFw0yMDEwMTIxMzMxMzdaMAwwCgYDVR0VBAMKAQUwIwIEWcXV -FBcNMjAxMDEyMTMzMTQ0WjAMMAoGA1UdFQQDCgEFMCMCBFnF1GcXDTIwMDQzMDE1 -NTAwM1owDDAKBgNVHRUEAwoBBTAjAgRZxdRmFw0yMDA0MzAxNTUwMjVaMAwwCgYD -VR0VBAMKAQUwIwIEWcXUIRcNMjAwNDI5MDg0NjA4WjAMMAoGA1UdFQQDCgEFMCMC -BFnF1CAXDTIwMDQyOTA4NDYwNFowDDAKBgNVHRUEAwoBBTAjAgRZxdQeFw0yMDA0 -MjkwODQ2MDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXUHRcNMjAwNDI5MDg0NTU2WjAM -MAoGA1UdFQQDCgEFMCMCBFnF1BwXDTIwMDQyODE4NTAyMVowDDAKBgNVHRUEAwoB -BTAjAgRZxdQbFw0yMDA0MjgxODUwMTVaMAwwCgYDVR0VBAMKAQUwIwIEWcXUGhcN -MjAwNDI4MTg0OTMzWjAMMAoGA1UdFQQDCgEFMCMCBFnF0+oXDTIwMDQyOTExMzM0 -NlowDDAKBgNVHRUEAwoBBTAjAgRZxdPoFw0yMDA0MjgwODQ5MjdaMAwwCgYDVR0V -BAMKAQUwIwIEWcXT5xcNMjAwNDI4MDg0NTMwWjAMMAoGA1UdFQQDCgEFMCMCBFnF -0xMXDTIwMDkwMjEyMDY0NFowDDAKBgNVHRUEAwoBBTAjAgRZxdMSFw0yMDA5MDIx -MjA2NDFaMAwwCgYDVR0VBAMKAQUwFQIEWcXS4RcNMjAwODI0MTEyMTU5WjAVAgRZ -xdLgFw0yMDA4MjQxMTIxNTlaMCMCBFnF0tUXDTIwMDQyMzExNDMyMVowDDAKBgNV -HRUEAwoBBTAjAgRZxdLTFw0yMDA0MjYxMjI5NTBaMAwwCgYDVR0VBAMKAQUwFQIE -WcXSphcNMjAwODI0MTEyMTU5WjAVAgRZxdKlFw0yMDA4MjQxMTIxNTlaMBUCBFnF -0qQXDTIwMDgyNDExMjE1OVowIwIEWcXSchcNMjAwNDIxMTUwODQyWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF0nAXDTIwMDQyMTE0NTcyOFowDDAKBgNVHRUEAwoBBTAjAgRZ -xdJDFw0yMDA0MjAxODEyNDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXSQhcNMjAwNDIw -MTgxMjE1WjAMMAoGA1UdFQQDCgEFMCMCBFnF0kEXDTIwMDUwNzEyNTY1NVowDDAK -BgNVHRUEAwoBBTAjAgRZxdJAFw0yMDA1MDcxMjU2NDdaMAwwCgYDVR0VBAMKAQUw -IwIEWcXSPhcNMjAwNDIwMTgwNTM0WjAMMAoGA1UdFQQDCgEFMCMCBFnF0j0XDTIw -MDQyMDE4MDUwNVowDDAKBgNVHRUEAwoBBTAjAgRZxdI8Fw0yMDA1MDcxMjU2NDFa -MAwwCgYDVR0VBAMKAQUwIwIEWcXSOxcNMjAwNTA3MTI0MjQ0WjAMMAoGA1UdFQQD -CgEFMCMCBFnF0jkXDTIwMDQyMDE3NTE0NVowDDAKBgNVHRUEAwoBBTAjAgRZxdI4 -Fw0yMDA0MjAxNzUxMTdaMAwwCgYDVR0VBAMKAQUwIwIEWcXSNBcNMjAwNDIwMTc0 -MjE0WjAMMAoGA1UdFQQDCgEFMCMCBFnF0jMXDTIwMDQyMDE3NDE0OFowDDAKBgNV -HRUEAwoBBTAjAgRZxdH1Fw0yMDA0MTkxNzE5MTBaMAwwCgYDVR0VBAMKAQUwIwIE -WcXR9BcNMjAwNDE5MTcxOTAzWjAMMAoGA1UdFQQDCgEFMCMCBFnF0fMXDTIwMDQx -OTE2MzA0N1owDDAKBgNVHRUEAwoBBTAjAgRZxdHyFw0yMDA0MTkxNjA1MTZaMAww -CgYDVR0VBAMKAQUwIwIEWcXRoRcNMjAwOTA5MTA1MTMwWjAMMAoGA1UdFQQDCgEF -MCMCBFnF0Z8XDTIwMDkwOTEwNTEyOFowDDAKBgNVHRUEAwoBBTAjAgRZxdGZFw0y -MDA5MDIxMjA2MTdaMAwwCgYDVR0VBAMKAQUwIwIEWcXRmBcNMjAwOTAyMTIwNjE1 -WjAMMAoGA1UdFQQDCgEFMCMCBFnF0ZYXDTIwMDkwMjEyMDEzMlowDDAKBgNVHRUE -AwoBBTAjAgRZxdGVFw0yMDA5MDIxMjAxMjlaMAwwCgYDVR0VBAMKAQUwIwIEWcXR -YRcNMjAwNDIwMTIxMDU3WjAMMAoGA1UdFQQDCgEFMCMCBFnF0WAXDTIwMDQyMDEy -MTA1MFowDDAKBgNVHRUEAwoBBTAjAgRZxdFfFw0yMDA5MDkxMDUxMjdaMAwwCgYD -VR0VBAMKAQUwIwIEWcXRLxcNMjAwNDE1MTUwMzIxWjAMMAoGA1UdFQQDCgEFMBUC -BFnF0MYXDTIwMDgyNDExMjE1OFowIwIEWcXQxRcNMjAwNDEzMTQyMjM5WjAMMAoG -A1UdFQQDCgEFMCMCBFnF0HAXDTIwMDkwMjEyMDQyNFowDDAKBgNVHRUEAwoBBTAj -AgRZxdBvFw0yMDA5MDIxMjA0MjNaMAwwCgYDVR0VBAMKAQUwIwIEWcXQbRcNMjAw -OTAyMTIwMjEyWjAMMAoGA1UdFQQDCgEFMCMCBFnF0GwXDTIwMDkwMjEyMDIxMFow -DDAKBgNVHRUEAwoBBTAjAgRZxdAWFw0yMDA1MDcxNTQ0MDlaMAwwCgYDVR0VBAMK -AQUwIwIEWcXQFRcNMjAwNTA3MTMxODAwWjAMMAoGA1UdFQQDCgEFMCMCBFnF0BEX -DTIwMDQwOTEwMDY1MFowDDAKBgNVHRUEAwoBBTAjAgRZxdAQFw0yMDA0MDkxMDA2 -MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcXQDxcNMjAwNTA3MTI1NDUyWjAMMAoGA1Ud -FQQDCgEFMCMCBFnF0A4XDTIwMDUwNzEyNDQ0NVowDDAKBgNVHRUEAwoBBTAjAgRZ -xdAMFw0yMDA0MDkxMDAwMjNaMAwwCgYDVR0VBAMKAQUwIwIEWcXQCxcNMjAwNDA5 -MDk1OTU3WjAMMAoGA1UdFQQDCgEFMCMCBFnFz2QXDTIwMDUwNzEyNDQ0MFowDDAK -BgNVHRUEAwoBBTAjAgRZxc9jFw0yMDA1MDcxMjQ0MzNaMAwwCgYDVR0VBAMKAQUw -IwIEWcXPYRcNMjAwNDA2MTczMDA4WjAMMAoGA1UdFQQDCgEFMCMCBFnFz2AXDTIw -MDQwNjE3Mjk0MlowDDAKBgNVHRUEAwoBBTAjAgRZxc9eFw0yMDA1MDcxMjQzNTZa -MAwwCgYDVR0VBAMKAQUwIwIEWcXPXRcNMjAwNTA3MTI0MjE4WjAMMAoGA1UdFQQD -CgEFMCMCBFnFz1sXDTIwMDQwNjE3MDY1NVowDDAKBgNVHRUEAwoBBTAjAgRZxc9a -Fw0yMDA0MDYxNzA1NTlaMAwwCgYDVR0VBAMKAQUwIwIEWcXPWRcNMjAwNTA3MTI0 -NDI4WjAMMAoGA1UdFQQDCgEFMCMCBFnFz1gXDTIwMDUwNzEyNDM0MlowDDAKBgNV -HRUEAwoBBTAjAgRZxc9WFw0yMDA0MDYxNjU3MDFaMAwwCgYDVR0VBAMKAQUwIwIE -WcXPVRcNMjAwNDA2MTY1NjM0WjAMMAoGA1UdFQQDCgEFMCMCBFnFz1QXDTIwMDUw -NzEyNDQwNVowDDAKBgNVHRUEAwoBBTAjAgRZxc9TFw0yMDA1MDcxMjQzNTRaMAww -CgYDVR0VBAMKAQUwIwIEWcXPURcNMjAwNDA2MTY0OTI5WjAMMAoGA1UdFQQDCgEF -MCMCBFnFz1AXDTIwMDQwNjE2NDkwMVowDDAKBgNVHRUEAwoBBTAjAgRZxc9OFw0y -MDA0MDYxNjQ5MDdaMAwwCgYDVR0VBAMKAQUwIwIEWcXPTRcNMjAwNDA2MTY0ODU0 -WjAMMAoGA1UdFQQDCgEFMCMCBFnFz0sXDTIxMDIyNTExMzc1MVowDDAKBgNVHRUE -AwoBBTAjAgRZxc9KFw0yMTAyMjUxMTM3NDlaMAwwCgYDVR0VBAMKAQUwIwIEWcXP -SBcNMjAwOTAyMTIwNDE1WjAMMAoGA1UdFQQDCgEFMCMCBFnFz0cXDTIwMDkwMjEy -MDQxM1owDDAKBgNVHRUEAwoBBTAjAgRZxc9FFw0yMDA5MDIxMTQ5MjRaMAwwCgYD -VR0VBAMKAQUwIwIEWcXPRBcNMjAwOTAyMTE0OTIzWjAMMAoGA1UdFQQDCgEFMCMC -BFnFzzoXDTIwMDUwNzEyNDMyOVowDDAKBgNVHRUEAwoBBTAjAgRZxc85Fw0yMDA1 -MDcxMjQzNDRaMAwwCgYDVR0VBAMKAQUwIwIEWcXPNxcNMjAwNDA2MTExMDE5WjAM -MAoGA1UdFQQDCgEFMCMCBFnFzzYXDTIwMDQwNjExMDk1MlowDDAKBgNVHRUEAwoB -BTAjAgRZxc81Fw0yMDA1MDcxMjQzMzdaMAwwCgYDVR0VBAMKAQUwIwIEWcXPNBcN -MjAwNTA3MTI0MzMxWjAMMAoGA1UdFQQDCgEFMCMCBFnFzzIXDTIwMDQwNjExMDM0 -NlowDDAKBgNVHRUEAwoBBTAjAgRZxc8xFw0yMDA0MDYxMTAzMjBaMAwwCgYDVR0V -BAMKAQUwIwIEWcXPMBcNMjAwNTA3MTI0MzI2WjAMMAoGA1UdFQQDCgEFMCMCBFnF -zy8XDTIwMDUwNzEyNDI0NlowDDAKBgNVHRUEAwoBBTAjAgRZxc8tFw0yMDA0MDYx -MDU2NDBaMAwwCgYDVR0VBAMKAQUwIwIEWcXPLBcNMjAwNDA2MTA1NjEzWjAMMAoG -A1UdFQQDCgEFMCMCBFnFzykXDTIxMDIxNTA4MzkyOVowDDAKBgNVHRUEAwoBBTAj -AgRZxc8oFw0yMTAyMTUwODM5MjJaMAwwCgYDVR0VBAMKAQUwIwIEWcXOTxcNMjAw -OTAyMTIwNDA5WjAMMAoGA1UdFQQDCgEFMCMCBFnFzk4XDTIwMDkwMjEyMDQwNVow -DDAKBgNVHRUEAwoBBTAjAgRZxc5MFw0yMDA5MDIxMjAzNDJaMAwwCgYDVR0VBAMK -AQUwIwIEWcXOSxcNMjAwOTAyMTIwMzQxWjAMMAoGA1UdFQQDCgEFMCMCBFnFzkoX -DTIwMDQwMjA5MzYyMVowDDAKBgNVHRUEAwoBBTAjAgRZxc3lFw0yMDA2MDQxNTQ1 -NTVaMAwwCgYDVR0VBAMKAQUwIwIEWcXN5BcNMjAwNjA0MTU0NTM1WjAMMAoGA1Ud -FQQDCgEFMCMCBFnFzboXDTIwMDQwOTE3NTM0OFowDDAKBgNVHRUEAwoBBTAjAgRZ -xc25Fw0yMDA0MDkxNzUzMzhaMAwwCgYDVR0VBAMKAQUwIwIEWcXNshcNMjAwMzMw -MTUzNzQ4WjAMMAoGA1UdFQQDCgEFMCMCBFnFzbEXDTIwMDMzMDE1MzczOVowDDAK -BgNVHRUEAwoBBTAjAgRZxc2sFw0yMDAzMzEwNzU4MTBaMAwwCgYDVR0VBAMKAQUw -IwIEWcXNqhcNMjAxMTE2MTgzMzIyWjAMMAoGA1UdFQQDCgEFMCMCBFnFzakXDTIw -MTExNjE4MzMyMVowDDAKBgNVHRUEAwoBBTAjAgRZxc0nFw0yMDA0MDkxNzU0MDJa -MAwwCgYDVR0VBAMKAQUwIwIEWcXNJhcNMjAwNDA5MTc1NDE1WjAMMAoGA1UdFQQD -CgEFMCMCBFnFzSQXDTIwMDMzMDExMTIxNlowDDAKBgNVHRUEAwoBBTAjAgRZxc0c -Fw0yMDA5MDIxMTU5NTNaMAwwCgYDVR0VBAMKAQUwIwIEWcXNGxcNMjAwOTAyMTE1 -OTUyWjAMMAoGA1UdFQQDCgEFMCMCBFnFzPUXDTIwMTExNjE4Mjk0MlowDDAKBgNV -HRUEAwoBBTAjAgRZxcz0Fw0yMDExMTYxODI5MzJaMAwwCgYDVR0VBAMKAQUwIwIE -WcXMvBcNMjAwNjE1MDczNDU0WjAMMAoGA1UdFQQDCgEFMCMCBFnFzLsXDTIwMDYx -NTA3MzQ1M1owDDAKBgNVHRUEAwoBBTAjAgRZxcy5Fw0yMDAzMjUxNjM3MTNaMAww -CgYDVR0VBAMKAQUwIwIEWcXMtBcNMjAwOTIzMTEzMzI5WjAMMAoGA1UdFQQDCgEF -MCMCBFnFzLMXDTIwMDkyMzExMzMxOFowDDAKBgNVHRUEAwoBBTAjAgRZxcytFw0y -MDA1MDcxMjQyMzRaMAwwCgYDVR0VBAMKAQUwIwIEWcXMrBcNMjAwNTA3MTI0MjI2 -WjAMMAoGA1UdFQQDCgEFMCMCBFnFzKoXDTIwMDMyNDIwNTExMFowDDAKBgNVHRUE -AwoBBTAjAgRZxcypFw0yMDAzMjQyMDUwNDRaMAwwCgYDVR0VBAMKAQUwIwIEWcXM -qBcNMjEwMjI1MTExMDU4WjAMMAoGA1UdFQQDCgEFMCMCBFnFzHgXDTIwMDMyNDEy -NTQzOFowDDAKBgNVHRUEAwoBBTAjAgRZxcx2Fw0yMDA3MTAwOTE3MjdaMAwwCgYD -VR0VBAMKAQUwIwIEWcXMdRcNMjAwNzEwMDkxNzI1WjAMMAoGA1UdFQQDCgEFMCMC -BFnFzHEXDTIwMDQxMzE1MjUzN1owDDAKBgNVHRUEAwoBBTAjAgRZxcxwFw0yMDA0 -MTMxNTE1MzNaMAwwCgYDVR0VBAMKAQUwIwIEWcXMbxcNMjEwMzExMjA1ODQ2WjAM -MAoGA1UdFQQDCgEFMCMCBFnFzG4XDTIxMDMxMTIwNTgxM1owDDAKBgNVHRUEAwoB -BTAjAgRZxcxBFw0yMDA2MDIxNTE0MThaMAwwCgYDVR0VBAMKAQUwIwIEWcXMPxcN -MjAwNjAyMTUxNDExWjAMMAoGA1UdFQQDCgEFMCMCBFnFzDwXDTIwMDMyMzE0NTc1 -NVowDDAKBgNVHRUEAwoBBTAjAgRZxcw6Fw0yMDA3MjQxNjQ4MzNaMAwwCgYDVR0V -BAMKAQUwIwIEWcXMORcNMjAwNzI0MTY0ODI3WjAMMAoGA1UdFQQDCgEFMCMCBFnF -zDcXDTIwMDcyMjEzMzIxM1owDDAKBgNVHRUEAwoBBTAjAgRZxcw2Fw0yMDA3MjIx -MzMxNTdaMAwwCgYDVR0VBAMKAQUwIwIEWcXLsRcNMjAwNzEwMTAzNTA0WjAMMAoG -A1UdFQQDCgEFMCMCBFnFy7AXDTIwMDcxMDEwMzUwM1owDDAKBgNVHRUEAwoBBTAj -AgRZxcuvFw0yMDAzMjMxNDA4MDRaMAwwCgYDVR0VBAMKAQUwFQIEWcXLghcNMjAw -ODI0MTEyMTU4WjAVAgRZxcuBFw0yMDA4MjQxMTIxNThaMBUCBFnFy4AXDTIwMDgy -NDExMjE1OFowIwIEWcXLeBcNMjAwNDA2MTIzOTU0WjAMMAoGA1UdFQQDCgEFMCMC -BFnFy3cXDTIwMDQwNjEyMzk0N1owDDAKBgNVHRUEAwoBBTAjAgRZxct2Fw0yMDA1 -MTkxMzE1NTVaMAwwCgYDVR0VBAMKAQUwIwIEWcXLdBcNMjAwNTE5MTMxNTU0WjAM -MAoGA1UdFQQDCgEFMCMCBFnFy3MXDTIwMDMxOTE0MDkyN1owDDAKBgNVHRUEAwoB -BTAjAgRZxctuFw0yMDA5MDIxMjAzMzRaMAwwCgYDVR0VBAMKAQUwIwIEWcXLbRcN -MjAwOTAyMTIwMzMxWjAMMAoGA1UdFQQDCgEFMCMCBFnFy2sXDTIwMDkwMjEyMDEz -OVowDDAKBgNVHRUEAwoBBTAjAgRZxctqFw0yMDA5MDIxMjAxMzdaMAwwCgYDVR0V -BAMKAQUwIwIEWcXLORcNMjAwNDA2MDc1MzMzWjAMMAoGA1UdFQQDCgEFMCMCBFnF -yvMXDTIxMDMwNDE5MzcyMFowDDAKBgNVHRUEAwoBBTAjAgRZxcryFw0yMTAzMDQx -OTM3MTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXK7hcNMjEwMzA0MTkzMTUxWjAMMAoG -A1UdFQQDCgEFMCMCBFnFyu0XDTIxMDMwNDE5MzE0MVowDDAKBgNVHRUEAwoBBTAj -AgRZxcq7Fw0yMDEwMTQwODI4MzBaMAwwCgYDVR0VBAMKAQUwIwIEWcXKuhcNMjAx -MDE0MDgyODI4WjAMMAoGA1UdFQQDCgEFMCMCBFnFyrIXDTIwMTExNzE0MjE1Nlow -DDAKBgNVHRUEAwoBBTAjAgRZxcozFw0yMTAzMDQxMTIwMDJaMAwwCgYDVR0VBAMK -AQUwIwIEWcXKMRcNMjEwMzA0MTEwNjQ5WjAMMAoGA1UdFQQDCgEFMCMCBFnFyi8X -DTIwMDYxMjEwMDIxNFowDDAKBgNVHRUEAwoBBTAjAgRZxcosFw0yMTAzMDQxMTI3 -MDFaMAwwCgYDVR0VBAMKAQUwIwIEWcXKJBcNMjAwMzEyMjEwNjExWjAMMAoGA1Ud -FQQDCgEFMCMCBFnFyiMXDTIwMDMxMjIxMDYxMFowDDAKBgNVHRUEAwoBBTAjAgRZ -xcn6Fw0yMDAzMTIxNjM3MTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXJ+RcNMjAwMzEy -MTYzNjQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnFyfgXDTIwMDUwNzEyNDAwM1owDDAK -BgNVHRUEAwoBBTAjAgRZxcn3Fw0yMDA1MDcxMjM5NDFaMAwwCgYDVR0VBAMKAQUw -IwIEWcXJ9RcNMjAwMzEyMTYzMDM4WjAMMAoGA1UdFQQDCgEFMCMCBFnFyfQXDTIw -MDMxMjE2MzAxMVowDDAKBgNVHRUEAwoBBTAjAgRZxcnzFw0yMDAzMTIxNjI2NTVa -MAwwCgYDVR0VBAMKAQUwIwIEWcXJ8hcNMjEwMjI1MTExMzM2WjAMMAoGA1UdFQQD -CgEFMCMCBFnFye8XDTIwMDMxMjE1NTkzMVowDDAKBgNVHRUEAwoBBTAjAgRZxcnu -Fw0yMDAzMTIxNTU5MjVaMAwwCgYDVR0VBAMKAQUwIwIEWcXJ7BcNMjAwMzEyMTU0 -NjU0WjAMMAoGA1UdFQQDCgEFMCMCBFnFyesXDTIwMDMxMjE1NDY0OFowDDAKBgNV -HRUEAwoBBTAjAgRZxcneFw0yMDAzMTIwMTEyMzRaMAwwCgYDVR0VBAMKAQUwIwIE -WcXJ3RcNMjAwMzEyMDExMjI3WjAMMAoGA1UdFQQDCgEFMCMCBFnFybEXDTIwMDMx -NDE2MDgwMlowDDAKBgNVHRUEAwoBBTAjAgRZxcmwFw0yMDEwMTQwODMxMjdaMAww -CgYDVR0VBAMKAQUwIwIEWcXJrxcNMjAxMDE0MDgzMTE4WjAMMAoGA1UdFQQDCgEF -MCMCBFnFya0XDTIwMDcwMTEzMTYzMlowDDAKBgNVHRUEAwoBBTAjAgRZxcmsFw0y -MDA3MDExMzE2MjRaMAwwCgYDVR0VBAMKAQUwIwIEWcXJqhcNMjAwNzAxMTMxNzUx -WjAMMAoGA1UdFQQDCgEFMCMCBFnFyakXDTIwMDcwMTEzMTc0MlowDDAKBgNVHRUE -AwoBBTAVAgRZxcksFw0yMDA4MjQxMTIxNDBaMBUCBFnFySsXDTIwMDgyNDExMjE0 -MFowIwIEWcXJKBcNMjAwMzEzMjA1NTAyWjAMMAoGA1UdFQQDCgEFMCMCBFnFyScX -DTIwMDMxMzIwNTUwMFowDDAKBgNVHRUEAwoBBTAjAgRZxcklFw0yMDEyMTAwOTU1 -MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcXIoBcNMjAwNjEwMDg1NjIzWjAMMAoGA1Ud -FQQDCgEFMCMCBFnFyJ8XDTIwMDYxMDA4NTYyMFowDDAKBgNVHRUEAwoBBTAjAgRZ -xcieFw0yMDAzMDYxNTM2MjFaMAwwCgYDVR0VBAMKAQUwIwIEWcXInRcNMjAwMzA2 -MTUwMzAzWjAMMAoGA1UdFQQDCgEFMCMCBFnFyJoXDTIwMDMwNjEyMjg0MVowDDAK -BgNVHRUEAwoBBTAjAgRZxciZFw0yMDAzMDYxMjI4MzRaMAwwCgYDVR0VBAMKAQUw -IwIEWcXIlhcNMjAwNDI3MTU0ODIxWjAMMAoGA1UdFQQDCgEFMCMCBFnFyJUXDTIw -MDQyNzE1NDgxMFowDDAKBgNVHRUEAwoBBTAVAgRZxciOFw0yMDA4MjQxMTIxNTBa -MBUCBFnFyI0XDTIwMDgyNDExMjE1MFowIwIEWcXIZhcNMjAwMzEwMTcxMTQzWjAM -MAoGA1UdFQQDCgEFMCMCBFnFyGUXDTIwMDMxMDE3MTEzNlowDDAKBgNVHRUEAwoB -BTAjAgRZxchhFw0yMDAzMDUxNTU2MDNaMAwwCgYDVR0VBAMKAQUwIwIEWcXIYBcN -MjAwMzA1MTU1NTU3WjAMMAoGA1UdFQQDCgEFMCMCBFnFyFsXDTIwMDMwNTE1NDUw -OFowDDAKBgNVHRUEAwoBBTAjAgRZxchaFw0yMDAzMDUxNTQ1MDJaMAwwCgYDVR0V -BAMKAQUwIwIEWcXIWBcNMjAwMzA1MTUwNjU1WjAMMAoGA1UdFQQDCgEFMCMCBFnF -yFcXDTIwMDMwNTE1MDY1NFowDDAKBgNVHRUEAwoBBTAjAgRZxchTFw0yMDAzMTEw -OTUxMzFaMAwwCgYDVR0VBAMKAQUwIwIEWcXIUhcNMjAwMzExMDk1MTA2WjAMMAoG -A1UdFQQDCgEFMCMCBFnFyFEXDTIwMDMxMTA5NTA1M1owDDAKBgNVHRUEAwoBBTAj -AgRZxchQFw0yMDAzMTEwOTUwNDZaMAwwCgYDVR0VBAMKAQUwIwIEWcXITxcNMjAw -MzExMDk1MDMyWjAMMAoGA1UdFQQDCgEFMCMCBFnFyE4XDTIwMDMxMTA5NTAyNlow -DDAKBgNVHRUEAwoBBTAjAgRZxchNFw0yMDAzMTEwOTUwMTlaMAwwCgYDVR0VBAMK -AQUwIwIEWcXITBcNMjAwMzExMDk0OTA4WjAMMAoGA1UdFQQDCgEFMCMCBFnFyEsX -DTIwMDMxMTA5NDg1OVowDDAKBgNVHRUEAwoBBTAjAgRZxchKFw0yMDAzMTEwOTQ4 -NTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXISRcNMjAwMzExMDk0ODM2WjAMMAoGA1Ud -FQQDCgEFMCMCBFnFyEgXDTIwMDMxMTA5NDgyNlowDDAKBgNVHRUEAwoBBTAjAgRZ -xchGFw0yMTAyMjUxMTU4NDhaMAwwCgYDVR0VBAMKAQUwIwIEWcXIRRcNMjEwMjI1 -MTE1ODQyWjAMMAoGA1UdFQQDCgEFMCMCBFnFyD4XDTIwMDYwMTA4Mzg0N1owDDAK -BgNVHRUEAwoBBTAjAgRZxcg9Fw0yMDA2MDEwODM4MzhaMAwwCgYDVR0VBAMKAQUw -IwIEWcXH0BcNMjEwMzAxMTAyNzAyWjAMMAoGA1UdFQQDCgEFMCMCBFnFx88XDTIx -MDMwMTEwMjY0NlowDDAKBgNVHRUEAwoBBTAjAgRZxcfOFw0yMTAyMTkxNDI3MDVa -MAwwCgYDVR0VBAMKAQUwIwIEWcXHzRcNMjEwMjE5MTQyNjU4WjAMMAoGA1UdFQQD -CgEFMCMCBFnFx8wXDTIxMDIxOTE0MjYwMFowDDAKBgNVHRUEAwoBBTAjAgRZxcfL -Fw0yMTAyMTkxNDI1NTJaMAwwCgYDVR0VBAMKAQUwIwIEWcXHyBcNMjAwMzAzMTIy -MjU0WjAMMAoGA1UdFQQDCgEFMCMCBFnFx8YXDTIwMDMwMzEyMjIyMlowDDAKBgNV -HRUEAwoBBTAjAgRZxceOFw0yMDA0MDIxMzI1MTVaMAwwCgYDVR0VBAMKAQUwIwIE -WcXHjRcNMjAwNDAyMTMxNTExWjAMMAoGA1UdFQQDCgEFMCMCBFnFx4gXDTIwMDMw -MjEwMDMxOVowDDAKBgNVHRUEAwoBBTAjAgRZxccJFw0yMDA3MTUxMDM5MTFaMAww -CgYDVR0VBAMKAQUwIwIEWcXHARcNMjAwOTAyMTE0OTM4WjAMMAoGA1UdFQQDCgEF -MCMCBFnFxwAXDTIwMDkwMjExNDkzNlowDDAKBgNVHRUEAwoBBTAjAgRZxcb+Fw0y -MDA5MDIxMTUyMjJaMAwwCgYDVR0VBAMKAQUwIwIEWcXG/RcNMjAwOTAyMTE1MjIx -WjAMMAoGA1UdFQQDCgEFMCMCBFnFxsoXDTIwMDMxMDEwMDcwN1owDDAKBgNVHRUE -AwoBBTAjAgRZxcbJFw0yMDAzMTAxMDA3MDVaMAwwCgYDVR0VBAMKAQUwIwIEWcXG -xhcNMjAwMzExMDkxNDA0WjAMMAoGA1UdFQQDCgEFMCMCBFnFxsUXDTIwMDMxMDEy -NDk1NVowDDAKBgNVHRUEAwoBBTAjAgRZxcaYFw0yMDAyMjYxNzI0NDBaMAwwCgYD -VR0VBAMKAQUwIwIEWcXGlhcNMjAxMTIwMTMxNjAzWjAMMAoGA1UdFQQDCgEFMCMC -BFnFxpUXDTIwMTEyMDEzMTYwMFowDDAKBgNVHRUEAwoBBTAjAgRZxcaQFw0yMDA0 -MTUwNzMyMjVaMAwwCgYDVR0VBAMKAQUwIwIEWcXGjxcNMjAwNDE1MDczMjIzWjAM -MAoGA1UdFQQDCgEFMCMCBFnFxnoXDTIwMTExNzE0MjE1M1owDDAKBgNVHRUEAwoB -BTAjAgRZxcZyFw0yMDAyMjYwOTIxNThaMAwwCgYDVR0VBAMKAQUwIwIEWcXGcRcN -MjAwMjI2MDk0MzM1WjAMMAoGA1UdFQQDCgEFMBUCBFnFxm8XDTIwMDgyNDExMjE1 -NlowFQIEWcXGbhcNMjAwODI0MTEyMTU2WjAVAgRZxcZtFw0yMDA4MjQxMTIxNTZa -MCMCBFnFxmQXDTIwMDIyNTIxMTQzNlowDDAKBgNVHRUEAwoBBTAjAgRZxcZjFw0y -MDAyMjUyMTE0MDlaMAwwCgYDVR0VBAMKAQUwIwIEWcXGYRcNMjAwMjI1MjA1MzE0 -WjAMMAoGA1UdFQQDCgEFMCMCBFnFxmAXDTIwMDIyNTIwNTMyNVowDDAKBgNVHRUE -AwoBBTAjAgRZxcYrFw0yMDEyMDYxMjAzMzFaMAwwCgYDVR0VBAMKAQUwIwIEWcXG -KhcNMjAxMjA2MTIwMzE5WjAMMAoGA1UdFQQDCgEFMCMCBFnFxf4XDTIxMDIwNDE1 -NTkxMFowDDAKBgNVHRUEAwoBBTAjAgRZxcX9Fw0yMTAyMDQxNTU4NTBaMAwwCgYD -VR0VBAMKAQUwIwIEWcXF/BcNMjAwMjI0MTM0OTQ3WjAMMAoGA1UdFQQDCgEFMCMC -BFnFxfYXDTIwMDIyNzE2NDcxNFowDDAKBgNVHRUEAwoBBTAjAgRZxcXxFw0yMDA1 -MDcxMzEwMTBaMAwwCgYDVR0VBAMKAQUwIwIEWcXF8BcNMjAwNTA3MTUzNjAwWjAM -MAoGA1UdFQQDCgEFMCMCBFnFxe4XDTIwMDYwMjE1MjUwNlowDDAKBgNVHRUEAwoB -BTAjAgRZxcXtFw0yMDA2MDIxNTI1MDRaMAwwCgYDVR0VBAMKAQUwIwIEWcXF7BcN -MjAwNTA3MTU0MDQ1WjAMMAoGA1UdFQQDCgEFMCMCBFnFxeoXDTIwMDYwMjE1MjQ0 -OFowDDAKBgNVHRUEAwoBBTAjAgRZxcXoFw0yMDA2MDIxNTI2MTRaMAwwCgYDVR0V -BAMKAQUwIwIEWcXF5xcNMjAwNjAyMTUyNDQ2WjAMMAoGA1UdFQQDCgEFMCMCBFnF -xeYXDTIwMDYwMjE1MjYxMlowDDAKBgNVHRUEAwoBBTAjAgRZxcXlFw0yMDA1MDcx -MjM5MzRaMAwwCgYDVR0VBAMKAQUwIwIEWcXF5BcNMjAwNTA3MTQxNDQ1WjAMMAoG -A1UdFQQDCgEFMCMCBFnFxeMXDTIwMDUwNzEzNTY1N1owDDAKBgNVHRUEAwoBBTAj -AgRZxcXiFw0yMDAyMjQxMTM3MzJaMAwwCgYDVR0VBAMKAQUwIwIEWcXF4RcNMjAw -NTA3MTIzOTI3WjAMMAoGA1UdFQQDCgEFMCMCBFnFxeAXDTIwMDUwNzEyMzkyMFow -DDAKBgNVHRUEAwoBBTAjAgRZxcXeFw0yMDA1MDcxNTM2NDNaMAwwCgYDVR0VBAMK -AQUwIwIEWcXF3RcNMjAwNTA3MTUzNjM5WjAMMAoGA1UdFQQDCgEFMCMCBFnFxdwX -DTIwMDIyNDEwMTcwNFowDDAKBgNVHRUEAwoBBTAjAgRZxcVXFw0yMDA1MTMxMjI4 -MDhaMAwwCgYDVR0VBAMKAQUwIwIEWcXFURcNMjAwMjIxMTEwMDA2WjAMMAoGA1Ud -FQQDCgEFMCMCBFnFxRkXDTIwMDUxMzEyMjc1OFowDDAKBgNVHRUEAwoBBTAjAgRZ -xcUXFw0yMDA2MjkwODI5NTNaMAwwCgYDVR0VBAMKAQUwIwIEWcXFFhcNMjAwNjI5 -MDgyOTQxWjAMMAoGA1UdFQQDCgEFMCMCBFnFxRUXDTIwMDIyNDEwMzU0MlowDDAK -BgNVHRUEAwoBBTAjAgRZxcTmFw0yMDAyMjAxMDI5MTlaMAwwCgYDVR0VBAMKAQUw -IwIEWcXE4RcNMjAwMjIwMTAyOTI1WjAMMAoGA1UdFQQDCgEFMCMCBFnFxN8XDTIw -MDUwNzEyMzkwN1owDDAKBgNVHRUEAwoBBTAVAgRZxcTPFw0yMDA4MjQxMTIxNTBa -MBUCBFnFxM4XDTIwMDgyNDExMjE1MFowIwIEWcXEzRcNMjEwMzAxMTA0NzU4WjAM -MAoGA1UdFQQDCgEFMCMCBFnFxMwXDTIxMDMwMTEwNDc0N1owDDAKBgNVHRUEAwoB -BTAVAgRZxcTLFw0yMDA4MjQxMTIxNTRaMCMCBFnFxMgXDTIxMDMxMDEyMDkzMlow -DDAKBgNVHRUEAwoBBTAjAgRZxcTEFw0yMDAyMTkxMTMxMDNaMAwwCgYDVR0VBAMK -AQUwIwIEWcXEwxcNMjAwMjE5MTEzMDU4WjAMMAoGA1UdFQQDCgEFMCMCBFnFxMEX -DTIwMDIxOTEzMTcyN1owDDAKBgNVHRUEAwoBBTAjAgRZxcSDFw0yMDAyMTkxMjQ1 -NDZaMAwwCgYDVR0VBAMKAQUwIwIEWcXEfxcNMjAwMjE5MTI1NjEzWjAMMAoGA1Ud -FQQDCgEFMCMCBFnFxHYXDTIxMDIxNTA4MzAyM1owDDAKBgNVHRUEAwoBBTAjAgRZ -xcR1Fw0yMTAyMTUwODMwMjBaMAwwCgYDVR0VBAMKAQUwIwIEWcXEaRcNMjEwMTIx -MTQxNDQzWjAMMAoGA1UdFQQDCgEFMCMCBFnFxGUXDTIwMDMxMzIwNTQ0OFowDDAK -BgNVHRUEAwoBBTAjAgRZxcRjFw0yMDAzMTMyMDU0NDVaMAwwCgYDVR0VBAMKAQUw -IwIEWcXENhcNMjAwMjE5MTI0MTU5WjAMMAoGA1UdFQQDCgEFMBUCBFnFxDIXDTIw -MDgyNDExMjE1MVowIwIEWcXEMBcNMjAwMjE5MTI0MTUyWjAMMAoGA1UdFQQDCgEF -MBUCBFnFxC8XDTIwMDgyNDExMjE1MVowFQIEWcXELhcNMjAwODI0MTEyMTUxWjAV -AgRZxcQtFw0yMDA4MjQxMTIxNTFaMCMCBFnFxCwXDTIwMDIxOTEzMTY1NVowDDAK -BgNVHRUEAwoBBTAjAgRZxcQqFw0yMDAyMTcxNzMxMjNaMAwwCgYDVR0VBAMKAQUw -FQIEWcXEIxcNMjAwODI0MTEyMTQ5WjAVAgRZxcQiFw0yMDA4MjQxMTIxNDlaMBUC -BFnFw5IXDTIwMDgyNDExMjE0OVowFQIEWcW4LBcNMjAwODI0MTEyMTQ3WjAVAgRZ -xbD2Fw0yMDA4MjQxMTIxNDVaMBUCBFnFn9oXDTIwMDgyNDExMjE0NFowFQIEWcWc -PhcNMjAwODI0MTEyMTQyWjAVAgRZxZs/Fw0yMDA4MjQxMTIxNDBaMBUCBFnFmlAX -DTIwMDgyNDExMjE0MVowFQIEWcWTSxcNMjAwODI0MTEyMTM5WjAVAgRZxZClFw0y -MDA4MjQxMTIxMzhaMBUCBFnFh+oXDTIwMDgyNDExMjEzOFowFQIEWcWAVBcNMjAw -ODI0MTEyMTI0WjAVAgRZxX5yFw0yMDA4MjQxMTIxMzVaMBUCBFnFfeQXDTIwMDgy -NDExMjEzNFowFQIEWcVyzRcNMjAwODI0MTEyMTEzWjAVAgRZxXB6Fw0yMDA4MjQx -MTIxMjZaMBUCBFnFbf4XDTIwMDgyNDExMjEyNVowFQIEWcVs6RcNMjAwODI0MTEy -MTIzWjAVAgRZxWzNFw0yMDA4MjQxMTIxMjJaMBUCBFnFbHkXDTIwMDgyNDExMjEy -MVowFQIEWcVscxcNMjAwODI0MTEyMTIxWjAVAgRZxWuVFw0yMDA4MjQxMTIxMTla -MBUCBFnFa4gXDTIwMDgyNDExMjExOFowFQIEWcVrBxcNMjAwODI0MTEyMTE1WjAV -AgRZxWsAFw0yMDA4MjQxMTIxMTRaMBUCBFnFavAXDTIwMDgyNDExMjExMVowFQIE -WcVqwhcNMjAwODI0MTEyMTEwWjAVAgRZxWqIFw0yMDA4MjQxMTIxMDlaMBUCBFnF -ankXDTIwMDgyNDExMjEwOFowFQIEWcVp+hcNMjAwODI0MTEyMTA0WjAVAgRZxWmb -Fw0yMDA4MjQxMTIxMDVaMBUCBFnFaQIXDTIwMDgyNDExMjEwNVowFQIEWcVouhcN -MjAwODI0MTEyMTAyWjAVAgRZxWgfFw0yMDA4MjQxMTIxMDFaMBUCBFnFaBkXDTIw -MDgyNDExMjEwMFowFQIEWcVoAxcNMjAwODI0MTEyMDU5WqAwMC4wCwYDVR0UBAQC -AlgmMB8GA1UdIwQYMBaAFFBzkcYhctN39P4AEgaBXHl5bj9QMA0GCSqGSIb3DQEB -CwUAA4IBAQBky3WxpSe5SWo3IdBgbA3pGUzlN+D4BZ6qlFeTkhoHFQ4m1IRqmDi4 -PNJugtb7C9MqDtu4EuViSUmB7I5gcZTqkF4wDZjJPPaL+Rz1baQUtYYJHG3Iz/4k -v3qsXagxWPo835kjLJ4IAnrutEX3cETp4tNlWmQjqVVDT7SPvHKtdXqlfVSa5O3U -1ofOWFLijLywOdV/1+NiNvhgL2nAgAQ9JixHlwHM1Wsq5LQZR2ExHoDdBEKaloc+ -gijtkYcBEkTQYBONxTfcXCpBr80LnKaa078SqCqeQqkJRgZYElVdmIasAnh7YrSu -IQkOUlYPYnTFIzwNzTljmNFs2bNOD+WY ------END X509 CRL----- diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/testng.xml deleted file mode 100644 index 49169106..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/testng.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/wso2carbon.jks b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/wso2carbon.jks deleted file mode 100644 index c8775783..00000000 Binary files a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.gateway/src/test/resources/wso2carbon.jks and /dev/null differ diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/pom.xml deleted file mode 100644 index 7e0acde5..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/pom.xml +++ /dev/null @@ -1,377 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.identity - bundle - WSO2 Open Banking - Identity Extensions - - - org.wso2.eclipse.osgi - org.eclipse.osgi.services - - - org.eclipse.osgi - org.eclipse.osgi - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - javax.validation - validation-api - provided - - - org.apache.tomcat - tomcat-catalina - - - org.wso2.carbon - org.wso2.carbon.logging - - - javax.ws.rs - javax.ws.rs-api - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.common - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.mgt - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.core - - - org.wso2.carbon.extension.identity.oauth.addons - org.wso2.carbon.identity.oauth2.token.handler.clientauth.mutualtls - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.ciba - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.authentication.framework - - - org.wso2.carbon.identity.application.auth.basic - org.wso2.carbon.identity.application.authenticator.basicauth - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.impl - - - org.wso2.orbit.org.apache.oltu.oauth2 - oltu - - - org.mockito - mockito-all - - - org.powermock - powermock-module-testng - - - org.powermock - powermock-api-mockito - - - org.springframework - spring-test - - - org.springframework - spring-core - - - org.hibernate - hibernate-validator - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - org.testng - testng - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.data.publisher.common - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.service - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.dao - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.throttler.dao - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.throttler.service - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push.device.handler - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push.common - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.jacoco - jacoco-maven-plugin - - - - **/*Constants.class - **/*Component.class - **/*Enum.class - **/*Exception.class - **/*DataHolder.class - **/*ServiceComponent.class - **/*IdentityCommonUtil.class - **/*DefaultTokenFilter.class - **/object/validator/** - **/com.wso2.openbanking.accelerator.identity.dcr/validation/annotation/* - - **/validator/annotations/**/* - **/*Constants.class - **/*RegistrationValidator.class - **/*SignatureValidator.class - **/*RegistrationError.class - **/*RegistrationRequest.class - **/*RegistrationResponse.class - **/*SoftwareStatementBody.class - **/*Wrapper.class - **/*ClaimProvider.class - **/*KeyIDProvider.class - **/*IntrospectionDataProvider.class - **/*GrantHandler.class - **/*Cache* - **/*IdentityCache.class - **/*IdentityCacheKey.class - **/*OBDefaultResponseTypeHandlerImpl.class - **/*PushAuthErrorResponse.class - **/*DefaultSPMetadataFilter.class - **/*IdentityServiceExporter.class - **/*DeviceVerificationToken.class - **/wrapper/* - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.8 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - false - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.identity.internal - - - javax.servlet;version="${imp.pkg.version.javax.servlet}", - javax.servlet.descriptor; version="${imp.pkg.version.javax.servlet}", - javax.servlet.http; version="${imp.pkg.version.javax.servlet}", - javax.validation.*;version="0", - - com.nimbusds.jwt.*;version="${nimbusds.osgi.version.range}", - com.nimbusds.jose.*;version="${nimbusds.osgi.version.range}", - net.minidev.json.*;version="${json-smart}", - com.google.gson.*;version="${gson.version}", - org.json.*;version="${org.json.version}", - org.wso2.carbon.core.*;version="${carbon.kernel.version}", - org.wso2.carbon.user.core.service.*;version="${carbon.kernel.version}", - - org.wso2.carbon.identity.application.authentication.framework.*; - version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.application.common.*;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.application.mgt.*;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.core.*;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.oauth2.keyidprovider;version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2.token.handler.clientauth.mutualtls.*;version="${carbon.identity.clientauth.mutualtls.version}", - org.wso2.carbon.identity.openidconnect.*;version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2.*;version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth2.model.*;version="${identity.inbound.auth.oauth.version.range}", - org.wso2.carbon.identity.oauth.*;version="${identity.inbound.auth.oauth.version.range}", - - com.wso2.openbanking.accelerator.common.*;version="${project.version}", - com.wso2.openbanking.accelerator.data.publisher.common.*;version="${project.version}", - com.wso2.openbanking.accelerator.consent.mgt.service.impl.*;version="${project.version}", - com.wso2.openbanking.accelerator.consent.mgt.dao.models.*, - com.wso2.openbanking.accelerator.throttler.service.*;version="${project.version}", - - org.apache.commons.lang3;version="${commons-lang.version}", - org.apache.commons.beanutils.*;version="0", - org.apache.commons.logging.*;version="${commons.logging.version}", - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}" - - - !com.wso2.openbanking.accelerator.identity.internal, - com.wso2.openbanking.accelerator.identity.*;version="${project.version}", - com.wso2.openbanking.accelerator.identity.authenticator.*;version="${project.version}", - com.wso2.openbanking.accelerator.identity.authenticator.OBIdentifierAuthenticator;version="${project.version}", - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticator.java deleted file mode 100644 index beb348c7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticator.java +++ /dev/null @@ -1,248 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app; - -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.app2app.exception.JWTValidationException; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.utils.App2AppAuthUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.authentication.framework.AbstractApplicationAuthenticator; -import org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.DeviceHandler; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerClientException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerServerException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.impl.DeviceHandlerImpl; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; - -import java.text.ParseException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * App2App authenticator for authenticating users from native auth attempt. - */ -public class App2AppAuthenticator extends AbstractApplicationAuthenticator - implements FederatedApplicationAuthenticator { - - private static final Log log = LogFactory.getLog(App2AppAuthenticator.class); - private static final long serialVersionUID = -5439464372188473141L; - private static DeviceHandler deviceHandler; - - /** - * Constructor for the App2AppAuthenticator. - */ - public App2AppAuthenticator() { - - if (deviceHandler == null) { - deviceHandler = new DeviceHandlerImpl(); - } - } - - /** - * This method is used to get authenticator name. - * - * @return String Authenticator name. - */ - @Override - public String getName() { - - return App2AppAuthenticatorConstants.AUTHENTICATOR_NAME; - } - - /** - * This method is used to get the friendly name of the authenticator. - * - * @return String Friendly name of the authenticator - */ - @Override - public String getFriendlyName() { - - return App2AppAuthenticatorConstants.AUTHENTICATOR_FRIENDLY_NAME; - } - - /** - * This method processes the authentication response received from the client. - * It verifies the authenticity of the received JWT token, extracts necessary information, - * and performs validations before authenticating the user. - * - * @param httpServletRequest The HTTP servlet request object containing the authentication response. - * @param httpServletResponse The HTTP servlet response object for sending responses. - * @param authenticationContext The authentication context containing information related to the authentication - * process. - * @throws AuthenticationFailedException If authentication fails due to various reasons such as missing parameters, - * parsing errors, JWT validation errors, or exceptions during authentication process. - */ - @Override - protected void processAuthenticationResponse(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, - AuthenticationContext authenticationContext) - throws AuthenticationFailedException { - - authenticationContext.setCurrentAuthenticator(App2AppAuthenticatorConstants.AUTHENTICATOR_NAME); - String jwtString = - httpServletRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER); - String request = - httpServletRequest.getParameter(App2AppAuthenticatorConstants.REQUEST); - - try { - SignedJWT signedJWT = JWTUtils.getSignedJWT(jwtString); - DeviceVerificationToken deviceVerificationToken = new DeviceVerificationToken(signedJWT); - //Extracting deviceId and loginHint is necessary to retrieve the public key - String loginHint = deviceVerificationToken.getLoginHint(); - String deviceID = deviceVerificationToken.getDeviceId(); - - //Checking whether deviceId and loginHint present in passed jwt - if (StringUtils.isBlank(loginHint) || StringUtils.isBlank(deviceID)) { - if (log.isDebugEnabled()) { - log.debug(App2AppAuthenticatorConstants.REQUIRED_PARAMS_MISSING_MESSAGE); - } - throw new AuthenticationFailedException(App2AppAuthenticatorConstants.REQUIRED_PARAMS_MISSING_MESSAGE); - } - - AuthenticatedUser userToBeAuthenticated = - App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(loginHint); - String publicKey = getPublicKeyByDeviceID(deviceID, userToBeAuthenticated); - deviceVerificationToken.setPublicKey(publicKey); - deviceVerificationToken.setRequestObject(request); - // setting the user is mandatory for data publishing purposes - //If exception is thrown before setting a user data publishing will encounter exceptions - authenticationContext.setSubject(userToBeAuthenticated); - /* - if validations are failed it will throw a JWTValidationException and flow will be interrupted. - Hence, user Authentication will fail. - */ - App2AppAuthUtils.validateToken(deviceVerificationToken); - //If the flow is not interrupted user will be authenticated. - if (log.isDebugEnabled()) { - log.debug(String.format(App2AppAuthenticatorConstants.USER_AUTHENTICATED_MSG, - userToBeAuthenticated.getUserName())); - } - } catch (ParseException e) { - log.error(e.getMessage()); - throw new AuthenticationFailedException(App2AppAuthenticatorConstants.PARSE_EXCEPTION_MESSAGE, e); - } catch (JWTValidationException e) { - log.error(e.getMessage()); - throw new AuthenticationFailedException - (App2AppAuthenticatorConstants.APP_AUTH_IDENTIFIER_VALIDATION_EXCEPTION_MESSAGE, e); - } catch (OpenBankingException e) { - log.error(e.getMessage()); - throw new AuthenticationFailedException(App2AppAuthenticatorConstants.OPEN_BANKING_EXCEPTION_MESSAGE, e); - } catch (PushDeviceHandlerServerException e) { - log.error(e.getMessage()); - throw new AuthenticationFailedException - (App2AppAuthenticatorConstants.PUSH_DEVICE_HANDLER_SERVER_EXCEPTION_MESSAGE, e); - } catch (UserStoreException e) { - log.error(e.getMessage()); - throw new AuthenticationFailedException(App2AppAuthenticatorConstants.USER_STORE_EXCEPTION_MESSAGE, e); - } catch (PushDeviceHandlerClientException e) { - log.error(e.getMessage()); - throw new AuthenticationFailedException - (App2AppAuthenticatorConstants.PUSH_DEVICE_HANDLER_CLIENT_EXCEPTION_MESSAGE, e); - } catch (IllegalArgumentException e) { - log.error(e.getMessage()); - throw new - AuthenticationFailedException(App2AppAuthenticatorConstants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE, e); - } - } - - /** - * Determines whether this authenticator can handle the incoming HTTP servlet request. - * This method checks if the request contains the necessary parameter for App2App authentication, - * which is the device verification token identifier. - * - * @param httpServletRequest The HTTP servlet request object to be checked for handling. - * @return True if this authenticator can handle the request, false otherwise. - */ - @Override - public boolean canHandle(HttpServletRequest httpServletRequest) { - - /* - App2App authenticates the user in one step depending on the app_auth_key, - Hence it's mandatory to have the required parameter app_auth_key. - */ - return StringUtils.isNotBlank(httpServletRequest.getParameter( - App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)); - } - - /** - * Retrieves the context identifier(sessionDataKey in this case) from the HTTP servlet request. - * - * @param request The HTTP servlet request object from which to retrieve the context identifier. - * @return The context identifier extracted from the request, typically representing session data key. - */ - @Override - public String getContextIdentifier(HttpServletRequest request) { - - return request.getParameter(App2AppAuthenticatorConstants.SESSION_DATA_KEY); - } - - /** - * Initiates the authentication request, but App2App authenticator does not support this operation. - * Therefore, this method terminates the authentication process and throws an AuthenticationFailedException. - * - * @param request The HTTP servlet request object. - * @param response The HTTP servlet response object. - * @param context The authentication context. - * @throws AuthenticationFailedException if this method is called - */ - @Override - protected void initiateAuthenticationRequest(HttpServletRequest request, - HttpServletResponse response, - AuthenticationContext context) - throws AuthenticationFailedException { - - /* - App2App authenticator does not support initiating authentication request, - Hence authentication process will be terminated. - */ - log.error(App2AppAuthenticatorConstants.INITIALIZATION_ERROR_MESSAGE); - throw new AuthenticationFailedException( - App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_MISSING_ERROR_MESSAGE); - } - - /** - * Retrieves the public key associated with a device and user. - * - * @param deviceID The identifier of the device for which the public key is requested. - * @param authenticatedUser the authenticated user for this request - * @return The public key associated with the specified device and user. - * @throws UserStoreException If an error occurs while accessing user store. - * @throws PushDeviceHandlerServerException If an error occurs on the server side of the push device handler. - * @throws PushDeviceHandlerClientException If an error occurs on the client side of the push device handler. - */ - private String getPublicKeyByDeviceID(String deviceID, AuthenticatedUser authenticatedUser) - throws UserStoreException, PushDeviceHandlerServerException, PushDeviceHandlerClientException, - OpenBankingException { - - UserRealm userRealm = App2AppAuthUtils.getUserRealm(authenticatedUser); - String userID = App2AppAuthUtils.getUserIdFromUsername(authenticatedUser.getUserName(), userRealm); - return App2AppAuthUtils.getPublicKey(deviceID, userID, deviceHandler); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticatorConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticatorConstants.java deleted file mode 100644 index b00f9c5a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticatorConstants.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app; - -/** - * Constants related with App2App Authenticator process. - */ -public class App2AppAuthenticatorConstants { - - public static final String AUTHENTICATOR_NAME = "app2app"; - public static final String AUTHENTICATOR_FRIENDLY_NAME = "App2App Authenticator"; - public static final String REQUEST = "request"; - public static final String DEVICE_VERIFICATION_TOKEN_IDENTIFIER = "deviceVerificationToken"; - public static final String SESSION_DATA_KEY = "sessionDataKey"; - public static final String APP_AUTH_IDENTIFIER_VALIDATION_EXCEPTION_MESSAGE - = "Error while validating device verification token."; - public static final String ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE - = "Error while creating user for provided login_hint."; - public static final String PARSE_EXCEPTION_MESSAGE = "Error while parsing the provided JWT."; - public static final String PUSH_DEVICE_HANDLER_SERVER_EXCEPTION_MESSAGE - = "Error occurred in push device handler service."; - public static final String USER_STORE_EXCEPTION_MESSAGE = "Error while creating authenticated user."; - public static final String PUSH_DEVICE_HANDLER_CLIENT_EXCEPTION_MESSAGE - = "Error occurred in Push Device handler client."; - public static final String INITIALIZATION_ERROR_MESSAGE = "Initializing App2App authenticator is not supported."; - public static final String DEVICE_VERIFICATION_TOKEN_MISSING_ERROR_MESSAGE - = "Device verification token null or empty in request."; - public static final String USER_AUTHENTICATED_MSG - = "User {%s} authenticated by app2app authenticator successfully."; - public static final String OPEN_BANKING_EXCEPTION_MESSAGE - = "Error while retrieving user."; - public static final String REQUIRED_PARAMS_MISSING_MESSAGE - = "Required Parameters did or loginHint null or empty."; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/cache/JTICache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/cache/JTICache.java deleted file mode 100644 index b32a8796..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/cache/JTICache.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.cache; - -import com.wso2.openbanking.accelerator.identity.cache.IdentityCache; -import com.wso2.openbanking.accelerator.identity.cache.IdentityCacheKey; - -/** - * Class for maintaining JTI cache. - */ -public class JTICache { - - private static volatile IdentityCache jtiCacheInstance; - - /** - * Get JTI cache instance. - * - * @return IdentityCache instance as JTICache - */ - public static IdentityCache getInstance() { - - //Outer null check avoids entering synchronized block when jtiCache is not null. - if (jtiCacheInstance == null) { - // Synchronize access to ensure thread safety - synchronized (JTICache.class) { - // Avoids race condition within threads - if (jtiCacheInstance == null) { - jtiCacheInstance = new IdentityCache(); - } - } - } - - return jtiCacheInstance; - } - - /** - * Adds the provided JTI (JSON Web Token ID) to the cache for efficient retrieval and management. - * - * @param jti The JTI (JSON Web Token ID) to be added to the cache. - */ - public static void addJtiDataToCache(String jti) { - - JTICache.getInstance().addToCache(IdentityCacheKey.of(jti), jti); - } - - /** - * Retrieves the data associated with the provided JTI (JSON Web Token ID) from the cache. - * - * @param jti The JTI (JSON Web Token ID) for which data is to be retrieved from the cache. - * @return The data associated with the provided JTI if found in the cache, otherwise null. - */ - public static Object getJtiDataFromCache(String jti) { - - return JTICache.getInstance().getFromCache(IdentityCacheKey.of(jti)); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/exception/JWTValidationException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/exception/JWTValidationException.java deleted file mode 100644 index e11dea70..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/exception/JWTValidationException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * DeviceVerificationToken Object Validation Exception. - */ -public class JWTValidationException extends OpenBankingException { - - private static final long serialVersionUID = -2572459527308720228L; - - public JWTValidationException(String message) { - super(message); - } - - public JWTValidationException(String message, Throwable e) { - super(message, e); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/model/DeviceVerificationToken.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/model/DeviceVerificationToken.java deleted file mode 100644 index f977d161..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/model/DeviceVerificationToken.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.model; - -import com.google.gson.annotations.SerializedName; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateDigest; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateExpiry; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateJTI; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateNBF; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateSignature; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.MandatoryChecks; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.SignatureCheck; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.ValidityChecks; - -import java.text.ParseException; -import java.util.Date; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; - -/** - * Model class for App2App Auth DeviceVerificationToken. - */ -@ValidateJTI(groups = ValidityChecks.class) -@ValidateSignature(groups = SignatureCheck.class) -@ValidateExpiry(groups = ValidityChecks.class) -@ValidateNBF(groups = ValidityChecks.class) -@ValidateDigest(groups = ValidityChecks.class) -public class DeviceVerificationToken { - - @SerializedName(DeviceVerificationTokenConstants.DEVICE_IDENTIFIER) - private String deviceId; - @SerializedName(DeviceVerificationTokenConstants.LOGIN_HINT) - private String loginHint; - @SerializedName(DeviceVerificationTokenConstants.EXPIRY_TIME) - private Date expirationTime; - @SerializedName(DeviceVerificationTokenConstants.NOT_VALID_BEFORE) - private Date notValidBefore; - @SerializedName(DeviceVerificationTokenConstants.JWT_ID) - private String jti; - @SerializedName(DeviceVerificationTokenConstants.ISSUED_TIME) - private Date issuedTime; - @SerializedName(DeviceVerificationTokenConstants.DIGEST) - private String digest; - private SignedJWT signedJWT; - private String publicKey; - private String requestObject; - - public DeviceVerificationToken(SignedJWT signedJWT) - throws ParseException { - - this.signedJWT = signedJWT; - JWTClaimsSet jwtClaimsSet = signedJWT.getJWTClaimsSet(); - this.expirationTime = jwtClaimsSet.getExpirationTime(); - this.notValidBefore = jwtClaimsSet.getNotBeforeTime(); - this.issuedTime = jwtClaimsSet.getIssueTime(); - this.jti = jwtClaimsSet.getJWTID(); - this.deviceId = getClaim(jwtClaimsSet, DeviceVerificationTokenConstants.DEVICE_IDENTIFIER); - this.loginHint = getClaim(jwtClaimsSet, DeviceVerificationTokenConstants.LOGIN_HINT); - this.digest = getClaim(jwtClaimsSet, DeviceVerificationTokenConstants.DIGEST); - } - - @NotBlank(message = "Required parameter did cannot be null or empty.", groups = MandatoryChecks.class) - public String getDeviceId() { - - return deviceId; - } - - @NotBlank(message = "Required parameter loginHint cannot be null or empty.", groups = MandatoryChecks.class) - public String getLoginHint() { - - return loginHint; - } - - @NotNull(message = "Required parameter exp cannot be null.", groups = MandatoryChecks.class) - public Date getExpirationTime() { - - return expirationTime; - } - - @NotNull(message = "Required parameter nbf cannot be null.", groups = MandatoryChecks.class) - public Date getNotValidBefore() { - - return notValidBefore; - } - - @NotBlank(message = "Required parameter jti cannot be null or empty.", groups = MandatoryChecks.class) - public String getJti() { - - return jti; - } - - @NotNull(message = "Required parameter iat cannot be null.", groups = MandatoryChecks.class) - public Date getIssuedTime() { - - return issuedTime; - } - - @NotNull(message = "Required parameter signedJWT cannot be null.", groups = MandatoryChecks.class) - public SignedJWT getSignedJWT() { - - return signedJWT; - } - - public void setSignedJWT(SignedJWT signedJWT) { - - this.signedJWT = signedJWT; - } - - @NotBlank(message = "Required parameter public key cannot be null or empty.", groups = MandatoryChecks.class) - public String getPublicKey() { - - return publicKey; - } - - public void setPublicKey(String publicKey) { - - this.publicKey = publicKey; - } - - public String getDigest() { - - return this.digest; - } - - /** - * Retrieves the value of the specified claim from the provided JWTClaimsSet. - * - * @param jwtClaimsSet the JWTClaimsSet from which to retrieve the claim value - * @param claim the name of the claim to retrieve - * @return the value of the specified claim, or null if the claim is not present - */ - private String getClaim(JWTClaimsSet jwtClaimsSet , String claim) { - - Object claimObj = jwtClaimsSet.getClaim(claim); - return (String) claimObj; - } - - public String getRequestObject() { - return requestObject; - } - - public void setRequestObject(String requestObject) { - this.requestObject = requestObject; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/model/DeviceVerificationTokenConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/model/DeviceVerificationTokenConstants.java deleted file mode 100644 index c5c81664..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/model/DeviceVerificationTokenConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.model; - -/** - * Constants for DeviceVerificationToken. - */ -public class DeviceVerificationTokenConstants { - - public static final String EXPIRY_TIME = "exp"; - public static final String NOT_VALID_BEFORE = "nbf"; - public static final String LOGIN_HINT = "login_hint"; - public static final String ISSUED_TIME = "ist"; - public static final String DEVICE_IDENTIFIER = "did"; - public static final String JWT_ID = "jti"; - public static final String DIGEST = "digest"; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/utils/App2AppAuthUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/utils/App2AppAuthUtils.java deleted file mode 100644 index ec1efd4f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/utils/App2AppAuthUtils.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.utils; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.validator.OpenBankingValidator; -import com.wso2.openbanking.accelerator.identity.app2app.exception.JWTValidationException; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.validations.validationorder.App2AppValidationOrder; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.DeviceHandler; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerClientException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerServerException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.model.Device; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; - -import java.util.List; - -/** - * Utils class for Authentication related logic implementations. - */ -public class App2AppAuthUtils { - - /** - * Retrieves an authenticated user object based on the provided subject identifier. - * - * @param subjectIdentifier the subject identifier used to retrieve the authenticated user - * @return an AuthenticatedUser object representing the authenticated user - */ - public static AuthenticatedUser getAuthenticatedUserFromSubjectIdentifier(String subjectIdentifier) { - - return AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(subjectIdentifier); - } - - /** - * Retrieves the user realm associated with the provided authenticated user. - * - * @param authenticatedUser the authenticated user for whom to retrieve the user realm - * @return the user realm associated with the authenticated user, or null if the user is not authenticated - * @throws UserStoreException if an error occurs while retrieving the user realm - */ - public static UserRealm getUserRealm(AuthenticatedUser authenticatedUser) throws UserStoreException { - - UserRealm userRealm = null; - - if (authenticatedUser != null) { - String tenantDomain = authenticatedUser.getTenantDomain(); - int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); - RealmService realmService = IdentityExtensionsDataHolder.getInstance().getRealmService(); - userRealm = realmService.getTenantUserRealm(tenantId); - } - - return userRealm; - } - - /** - * Retrieves the user ID associated with the provided username from the specified user realm. - * - * @param username the username for which to retrieve the user ID - * @param userRealm the user realm from which to retrieve the user ID - * @return the user ID associated with the username - * @throws UserStoreException if an error occurs while retrieving the user ID - */ - public static String getUserIdFromUsername(String username, UserRealm userRealm) throws UserStoreException, - OpenBankingException { - - if (userRealm != null) { - AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) userRealm.getUserStoreManager(); - return userStoreManager.getUserIDFromUserName(username); - } else { - throw new OpenBankingException("UserRealm service can not be null."); - } - } - - /** - * Retrieve Public key of the device specified if it is registered under specified user. - * TODO: Optimise this code to retrieve device by did and validate userID. - * Github issue :{...} - * - * @param deviceId deviceId of the device where the public key is required - * @param userId userId of the user - * @return the public key of the intended device. - * @throws PushDeviceHandlerServerException if an error occurs on the server side while handling the device - * @throws IllegalArgumentException if the provided device identifier does not exist - * @throws PushDeviceHandlerClientException if an error occurs on the client side while handling the device - */ - public static String getPublicKey(String deviceId, String userId, DeviceHandler deviceHandler) - throws PushDeviceHandlerServerException, IllegalArgumentException, PushDeviceHandlerClientException, - OpenBankingException { - - /* - It is important to verify the device is registered under the given user - as public key is associated with device not the user. - */ - List deviceList = deviceHandler.listDevices(userId); - //If none of the devices registered under the given user matches the specified deviceId then throw a exception - deviceList.stream() - .filter(registredDevice -> StringUtils.equals(registredDevice.getDeviceId(), deviceId)) - .findFirst() - .orElseThrow(() -> - new OpenBankingException("Provided Device ID doesn't match any device registered under user.")); - //If a device is found retrieve and return the public key - return deviceHandler.getPublicKey(deviceId); - } - - /** - * Validator util to validate DeviceVerificationToken model for given validationOrder. - * - * @param deviceVerificationToken DeviceVerificationToken object that needs to be validated - * @throws JWTValidationException if validation failed - */ - public static void validateToken(DeviceVerificationToken deviceVerificationToken) throws JWTValidationException { - /* - App2AppValidationOrder validation order - 1.Required Params validation - 2.Validity Validations - Signature, JTI, Timeliness, Digest will be validated. - */ - String error = OpenBankingValidator.getInstance() - .getFirstViolation(deviceVerificationToken, App2AppValidationOrder.class); - - //if there is a validation violation convert it to JWTValidationException - if (error != null) { - throw new JWTValidationException(error); - } - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/DigestValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/DigestValidator.java deleted file mode 100644 index 6b9c0e4c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/DigestValidator.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations; - -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateDigest; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for validating digest of a device verification token. - * Digest here is expected to be the hash of the request object if it is present. - */ -public class DigestValidator implements ConstraintValidator { - - private static final Log log = LogFactory.getLog(DigestValidator.class); - - /** - * Checks if the given device verification token is valid based on its digest. - * - * @param deviceVerificationToken The device verification token to be validated. - * @param constraintValidatorContext The context in which the validation is performed. - * @return true if the token is valid, false otherwise. - */ - @Override - public boolean isValid(DeviceVerificationToken deviceVerificationToken, - ConstraintValidatorContext constraintValidatorContext) { - - String requestObject = deviceVerificationToken.getRequestObject(); - String digest = deviceVerificationToken.getDigest(); - return isDigestValid(digest, requestObject); - } - - /** - * Validating the digest of the requestObject. - * Digest is expected to be the hash of requestObject if request Object is not null. - * - * @param digest digest sent in the device verification token - * @param requestObject JWT String of the request object - * @return return true if the digest validation is a success, false otherwise - */ - protected boolean isDigestValid(String digest, String requestObject) { - - if (StringUtils.isBlank(requestObject)) { - //If the request is null nothing to validate. - return true; - } else if (StringUtils.isBlank(digest)) { - //If request is not empty and digest us empty validation fails. - return false; - } - - try { - // Example : SHA-256=EkH8fPgZ2TY2XGns8c5Vvce8h3DB83V+w47zHiyYfiQ= - String[] digestAttribute = digest.split("=", 2); - - if (digestAttribute.length != 2) { - log.error("Invalid digest."); - return false; - } - // Example : SHA-256 - String digestAlgorithm = digestAttribute[0].trim(); - String digestValue = digestAttribute[1].trim(); - MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithm); - byte[] digestHash = messageDigest.digest(requestObject.getBytes(StandardCharsets.UTF_8)); - String generatedDigest = Base64.getEncoder() - .encodeToString(digestHash); - - if (generatedDigest.equals(digestValue)) { - return true; - } - - } catch (NoSuchAlgorithmException e) { - log.error("Invalid algorithm.", e); - return false; - } - - return false; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/ExpiryValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/ExpiryValidator.java deleted file mode 100644 index 078fb847..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/ExpiryValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations; - -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateExpiry; - -import java.util.Date; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for validating expiry of a device verification token. - */ -public class ExpiryValidator implements ConstraintValidator { - - private static final long DEFAULT_TIME_SKEW_IN_SECONDS = 300L; - - /** - * Checks if the given device verification token is valid based on its expiration time. - * - * @param deviceVerificationToken The device verification token to be validated. - * @param constraintValidatorContext The context in which the validation is performed. - * @return true if the token is valid, false otherwise. - */ - @Override - public boolean isValid(DeviceVerificationToken deviceVerificationToken, - ConstraintValidatorContext constraintValidatorContext) { - - Date expiryTime = deviceVerificationToken.getExpirationTime(); - return JWTUtils.isValidExpiryTime(expiryTime, DEFAULT_TIME_SKEW_IN_SECONDS); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/JTIValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/JTIValidator.java deleted file mode 100644 index 960d67fd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/JTIValidator.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations; - -import com.wso2.openbanking.accelerator.identity.app2app.cache.JTICache; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateJTI; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for validating the JWT ID of a device verification token. - */ -public class JTIValidator implements ConstraintValidator { - - /** - * Checks if the given device verification token is valid based on its JTI value. - * - * @param deviceVerificationToken The device verification token to be validated. - * @param constraintValidatorContext The context in which the validation is performed. - * @return true if the token is valid, false otherwise. - */ - @Override - public boolean isValid(DeviceVerificationToken deviceVerificationToken, - ConstraintValidatorContext constraintValidatorContext) { - - String jti = deviceVerificationToken.getJti(); - return validateJTI(jti); - } - - private boolean validateJTI(String jti) { - - if (getFromCache(jti) != null) { - return false; - } - - //adding to cache to prevent the value from being replayed again - addToCache(jti); - return true; - } - - private Object getFromCache(String jti) { - - return JTICache.getJtiDataFromCache(jti); - } - - private void addToCache(String jti) { - - JTICache.addJtiDataToCache(jti); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/NBFValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/NBFValidator.java deleted file mode 100644 index ff7b6528..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/NBFValidator.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations; - -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateNBF; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Date; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validation class for validating NBF of a device verification token. - */ -public class NBFValidator implements ConstraintValidator { - - private static final long DEFAULT_TIME_SKEW_IN_SECONDS = 300L; - private static final Log log = LogFactory.getLog(NBFValidator.class); - - /** - * Checks if the given device verification token is valid based on its nbf time. - * - * @param deviceVerificationToken The device verification token to be validated. - * @param constraintValidatorContext The context in which the validation is performed. - * @return true if the token is valid, false otherwise. - */ - @Override - public boolean isValid(DeviceVerificationToken deviceVerificationToken, - ConstraintValidatorContext constraintValidatorContext) { - - Date notValidBefore = deviceVerificationToken.getNotValidBefore(); - return JWTUtils.isValidNotValidBeforeTime(notValidBefore, DEFAULT_TIME_SKEW_IN_SECONDS); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/PublicKeySignatureValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/PublicKeySignatureValidator.java deleted file mode 100644 index 6ea59823..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/PublicKeySignatureValidator.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.validations.annotations.ValidateSignature; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for validating the signature of a device verification token. - */ -public class PublicKeySignatureValidator implements ConstraintValidator { - - private static final Log log = LogFactory.getLog(PublicKeySignatureValidator.class); - - /** - * Checks if the given device verification token is valid based on its signature. - * - * @param deviceVerificationToken The device verification token to be validated. - * @param constraintValidatorContext The context in which the validation is performed. - * @return true if the token is valid, false otherwise. - */ - @Override - public boolean isValid(DeviceVerificationToken deviceVerificationToken, - ConstraintValidatorContext constraintValidatorContext) { - - SignedJWT signedJWT = deviceVerificationToken.getSignedJWT(); - String publicKey = deviceVerificationToken.getPublicKey(); - - try { - if (!JWTUtils.isValidSignature(signedJWT, publicKey)) { - log.error("Signature can't be verified with registered public key."); - return false; - } - } catch (NoSuchAlgorithmException e) { - log.error("No such algorithm found.", e); - return false; - } catch (InvalidKeySpecException e) { - log.error("Invalid key spec.", e); - return false; - } catch (JOSEException e) { - log.error("JOSE exception.", e); - return false; - } catch (OpenBankingException e) { - log.error("Algorithm not supported yet.", e); - } - return true; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateDigest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateDigest.java deleted file mode 100644 index d50243c8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateDigest.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations.annotations; - -import com.wso2.openbanking.accelerator.identity.app2app.validations.DigestValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for validating digest. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {DigestValidator.class}) -public @interface ValidateDigest { - - String message() default "Digest validation failed."; - - Class[] groups() default {}; - - Class[] payload() default {}; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateExpiry.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateExpiry.java deleted file mode 100644 index 44134d4e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateExpiry.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations.annotations; - -import com.wso2.openbanking.accelerator.identity.app2app.validations.ExpiryValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for validating expiry of a device verification token. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {ExpiryValidator.class}) -public @interface ValidateExpiry { - - String message() default "JWT token is expired."; - - Class[] groups() default {}; - - Class[] payload() default {}; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateJTI.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateJTI.java deleted file mode 100644 index 24e33d67..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateJTI.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations.annotations; - -import com.wso2.openbanking.accelerator.identity.app2app.validations.JTIValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for validating JWT ID of a device verification token. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {JTIValidator.class}) -public @interface ValidateJTI { - - String message() default "JTI has been replayed"; - - Class[] groups() default {}; - - Class[] payload() default {}; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateNBF.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateNBF.java deleted file mode 100644 index c5c6ad02..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateNBF.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations.annotations; - -import com.wso2.openbanking.accelerator.identity.app2app.validations.NBFValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for validating NBF of a device verification token. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {NBFValidator.class}) -public @interface ValidateNBF { - - String message() default "JWT token is not active."; - - Class[] groups() default {}; - - Class[] payload() default {}; -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateSignature.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateSignature.java deleted file mode 100644 index beaeb7a8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/annotations/ValidateSignature.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.app2app.validations.annotations; - -import com.wso2.openbanking.accelerator.identity.app2app.validations.PublicKeySignatureValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for validating JWT Signature of a device verification token. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {PublicKeySignatureValidator.class}) -public @interface ValidateSignature { - - String message() default "Signature validation Failed."; - - Class[] groups() default {}; - - Class[] payload() default {}; - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/validationorder/App2AppValidationOrder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/validationorder/App2AppValidationOrder.java deleted file mode 100644 index 5619320b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/app2app/validations/validationorder/App2AppValidationOrder.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.validations.validationorder; - -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.MandatoryChecks; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.SignatureCheck; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.ValidityChecks; - -import javax.validation.GroupSequence; - -/** - * Class to define the order of execution for the hibernate validation groups. - */ -@GroupSequence({SignatureCheck.class , MandatoryChecks.class, ValidityChecks.class}) -public interface App2AppValidationOrder { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorker.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorker.java deleted file mode 100644 index ee7ce39b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorker.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function; - -import org.json.JSONObject; -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; - -import java.util.Map; - -/** - * Interface for Open Banking Authentication Worker. - */ -@FunctionalInterface -public interface OpenBankingAuthenticationWorker { - - JSONObject handleRequest(JsAuthenticationContext context, Map properties); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunction.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunction.java deleted file mode 100644 index c5559d39..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunction.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function; - - -import org.json.JSONObject; -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; - -import java.util.Map; - -/** - * Functional Interface for OpenBankingAuthWorker. - */ -@FunctionalInterface -public interface OpenBankingAuthenticationWorkerFunction { - - JSONObject handleRequest(JsAuthenticationContext context, Map properties, String workerName); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunctionImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunctionImpl.java deleted file mode 100644 index fa882adb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunctionImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function; - -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; - -import java.util.Map; - -/** - * Implementation of OpenBankingAuthenticationWorkerFunction. - */ -public class OpenBankingAuthenticationWorkerFunctionImpl implements OpenBankingAuthenticationWorkerFunction { - - private static final Log log = LogFactory.getLog(OpenBankingAuthenticationWorkerFunctionImpl.class); - - - @Override - public JSONObject handleRequest(JsAuthenticationContext context, - Map properties, String workerName) { - - Map workers = - IdentityExtensionsDataHolder.getInstance().getWorkers(); - if (workers.containsKey(workerName)) { - return workers.get(workerName).handleRequest(context, properties); - } else { - log.error("Failed to find a worker for the requested name : " + workerName); - } - return new JSONObject().put("Error", "Failed to find a worker for the requested name : " + workerName); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/authz/request/OBOAuthAuthzRequest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/authz/request/OBOAuthAuthzRequest.java deleted file mode 100644 index 9e5b6699..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/authz/request/OBOAuthAuthzRequest.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.authz.request; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest; -import org.apache.oltu.oauth2.common.OAuth; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; -import org.apache.oltu.oauth2.common.utils.OAuthUtils; -import org.apache.oltu.oauth2.common.validators.OAuthValidator; -import org.json.JSONObject; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; - -import static com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants.OAUTH2_INVALID_REQUEST_MESSAGE; -import static com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants.REQUEST; -import static com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants.REQUEST_URI; - -/** - * OB OAuth 2 authorization request for request_uri support. - */ -public class OBOAuthAuthzRequest extends OAuthAuthzRequest { - - private static final Log log = LogFactory.getLog(OBOAuthAuthzRequest.class); - - public OBOAuthAuthzRequest(HttpServletRequest request) throws OAuthSystemException, OAuthProblemException { - - super(request); - } - - @Override - protected OAuthValidator initValidator() throws OAuthProblemException, OAuthSystemException { - - String responseTypeValue = getParam(OAuth.OAUTH_RESPONSE_TYPE); - - // Check if request object reference is present. - if (OAuthUtils.isEmpty(responseTypeValue) && request.getParameterMap().containsKey(REQUEST_URI)) { - responseTypeValue = IdentityCommonUtil.decodeRequestObjectAndGetKey(request, OAuth.OAUTH_RESPONSE_TYPE); - } - if (OAuthUtils.isEmpty(responseTypeValue)) { - throw IdentityCommonUtil.handleOAuthProblemException(OAUTH2_INVALID_REQUEST_MESSAGE, - "Missing response_type parameter value", getState()); - } - - Class> oauthValidatorClass = OAuthServerConfiguration.getInstance() - .getSupportedResponseTypeValidators().get(responseTypeValue); - - if (oauthValidatorClass == null) { - if (log.isDebugEnabled()) { - - //Do not change this log format as these logs use by external applications - log.debug("Unsupported Response Type : " + responseTypeValue + - " for client id : " + getClientId()); - } - throw IdentityCommonUtil.handleOAuthProblemException(OAUTH2_INVALID_REQUEST_MESSAGE, - "Invalid response_type parameter value", getState()); - } - - return OAuthUtils.instantiateClass(oauthValidatorClass); - } - - @Override - public Set getScopes() { - - if (request.getParameterMap().containsKey(REQUEST_URI) && request.getParameter(REQUEST_URI) != null) { - try { - return OAuthUtils.decodeScopes(IdentityCommonUtil - .decodeRequestObjectAndGetKey(request, OAuth.OAUTH_SCOPE)); - } catch (OAuthProblemException e) { - log.error("Invalid request URI", e); - return null; - } - } else { - return super.getScopes(); - } - } - - @Override - public String getResponseType() { - - if (request.getParameterMap().containsKey(REQUEST_URI) && request.getParameter(REQUEST_URI) != null) { - try { - return IdentityCommonUtil.decodeRequestObjectAndGetKey(request, OAuth.OAUTH_RESPONSE_TYPE); - } catch (OAuthProblemException e) { - log.error("Invalid request URI", e); - return null; - } - } else { - return super.getResponseType(); - } - - } - - @Override - public String getState() { - - if (request.getParameterMap().containsKey(REQUEST_URI) && request.getParameter(REQUEST_URI) != null) { - try { - return IdentityCommonUtil.decodeRequestObjectAndGetKey(request, OAuth.OAUTH_STATE); - } catch (OAuthProblemException e) { - log.error("Invalid request URI", e); - return null; - } - } else { - - //retrieve state value if present inside request body. - if (StringUtils.isNotBlank(getParam(REQUEST))) { - byte[] requestObject; - try { - requestObject = Base64.getDecoder().decode(getParam(REQUEST).split("\\.")[1]); - } catch (IllegalArgumentException e) { - - // Decode if the requestObject is base64-url encoded. - requestObject = Base64.getUrlDecoder().decode(getParam(REQUEST).split("\\.")[1]); - } - JSONObject requestObjectJson = new JSONObject(new String(requestObject, StandardCharsets.UTF_8)); - return requestObjectJson.has(OAuth.OAUTH_STATE) ? requestObjectJson.getString(OAuth.OAUTH_STATE) : null; - } - return null; - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/DefaultOBRequestObjectValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/DefaultOBRequestObjectValidator.java deleted file mode 100644 index 52e52edc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/DefaultOBRequestObjectValidator.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator; - -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.OBRequestObject; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.ValidationResponse; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.RequestObjectException; - -import java.util.Map; - -/** - * The extension class for enforcing OB Request Object Validations. For Tool kits to extend. - */ -public class DefaultOBRequestObjectValidator extends OBRequestObjectValidator { - - private static final String CLAIMS = "claims"; - private static final String[] CLAIM_FIELDS = new String[]{"id_token", "userinfo"}; - private static final String OPENBANKING_INTENT_ID = "openbanking_intent_id"; - private static final String VALUE = "value"; - private static final String CLIENT_ID = "client_id"; - private static final String SCOPE = "scope"; - - private static final Log log = LogFactory.getLog(DefaultOBRequestObjectValidator.class); - - public DefaultOBRequestObjectValidator() { - } - - /** - * Extension point for tool kits. Perform validation and return the error message if any, else null. - * - * @param obRequestObject request object - * @param dataMap provides scope related data needed for validation from service provider meta data - * @return the response object with error message. - */ - @Override - public ValidationResponse validateOBConstraints(OBRequestObject obRequestObject, Map dataMap) { - - ValidationResponse superValidationResponse = super.validateOBConstraints(obRequestObject, dataMap); - - if (superValidationResponse.isValid()) { - try { - if (isClientIdAndScopePresent(obRequestObject)) { - // consent id and client id is matching - return new ValidationResponse(true); - } - return new ValidationResponse(false, - "Consent Id in the request does not match with the client Id"); - } catch (RequestObjectException e) { - return new ValidationResponse(false, e.getMessage()); - } - } else { - return superValidationResponse; - } - } - - /** - * Extract clientId and scope from ob request object and check whether it's present. - * - * @param obRequestObject - * @return result received from validateConsentIdWithClientId method - * @throws RequestObjectException if error occurred while validating - */ - private boolean isClientIdAndScopePresent(OBRequestObject obRequestObject) throws RequestObjectException { - JSONObject jsonObject = obRequestObject.getSignedJWT().getPayload().toJSONObject(); - final String clientId = jsonObject.getAsString(CLIENT_ID); - String scope = jsonObject.getAsString(SCOPE); - if (StringUtils.isBlank(clientId) || StringUtils.isBlank(scope)) { - log.error("Client id or scope cannot be empty"); - throw new RequestObjectException("Client id or scope cannot be empty"); - } - return true; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/OBRequestObjectValidationExtension.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/OBRequestObjectValidationExtension.java deleted file mode 100644 index bd6b4d54..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/OBRequestObjectValidationExtension.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.OBRequestObject; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.ValidationResponse; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.openidconnect.RequestObjectValidatorImpl; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * The extension of RequestObjectValidatorImpl to enforce Open Banking specific validations of the - * request object. - */ -public class OBRequestObjectValidationExtension extends RequestObjectValidatorImpl { - - private static final Log log = LogFactory.getLog(OBRequestObjectValidationExtension.class); - // Get extension impl - static OBRequestObjectValidator obDefaultRequestObjectValidator = - IdentityExtensionsDataHolder.getInstance().getObRequestObjectValidator(); - - /** - * Validations related to clientId, response type, exp, redirect URL, mandatory params, - * issuer, audience are done. Called after signature validation. - * - * @param initialRequestObject request object - * @param oAuth2Parameters oAuth2Parameters - * @throws RequestObjectException - RequestObjectException - */ - @Override - public boolean validateRequestObject(RequestObject initialRequestObject, OAuth2Parameters oAuth2Parameters) - throws RequestObjectException { - - try { - if (isRegulatory(oAuth2Parameters)) { - - OBRequestObject obRequestObject = new OBRequestObject(initialRequestObject); - - Map dataMap = new HashMap<>(); - final String allowedScopes = getAllowedScopes(oAuth2Parameters); - if (StringUtils.isNotBlank(allowedScopes)) { - dataMap.put(IdentityCommonConstants.SCOPE, Arrays.asList(allowedScopes.split(" "))); - } - // perform OB customized validations - ValidationResponse validationResponse = obDefaultRequestObjectValidator - .validateOBConstraints(obRequestObject, dataMap); - - if (!validationResponse.isValid()) { - // Exception will be caught and converted to auth error by IS at endpoint. - throw new RequestObjectException(RequestObjectException.ERROR_CODE_INVALID_REQUEST, - validationResponse.getViolationMessage()); - } - } - return validateIAMConstraints(initialRequestObject, oAuth2Parameters); - - } catch (OpenBankingException e) { - log.error("Error while retrieving regulatory property from sp metadata", e); - throw new RequestObjectException(RequestObjectException.ERROR_CODE_INVALID_REQUEST, "Error while " + - "retrieving regulatory property from sp metadata"); - } - } - - /** - * Validate IAM related logic. - * @param requestObject - * @param oAuth2Parameters - * @return - * @throws RequestObjectException - */ - @Generated(message = "super methods cannot be mocked") - boolean validateIAMConstraints(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws RequestObjectException { - - return super.validateRequestObject(requestObject, oAuth2Parameters); - } - - - /** - * Called by validateRequestObject. - * - * @param requestObject - * @param oAuth2Parameters - * @return - */ - @Generated(message = "Empty method") - @Override - protected boolean isValidAudience(RequestObject requestObject, OAuth2Parameters oAuth2Parameters) { - - // converted to validation layer - return true; - } - - /** - * Called by validateRequestObject. - * - * @param oAuth2Parameters - * @return - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - protected String getAllowedScopes(OAuth2Parameters oAuth2Parameters) throws RequestObjectException { - - try { - return new IdentityCommonHelper() - .getAppPropertyFromSPMetaData(oAuth2Parameters.getClientId(), IdentityCommonConstants.SCOPE); - } catch (OpenBankingException e) { - throw new RequestObjectException(e.getMessage(), e); - } - } - - /** - * Get regulatory property from sp metadata. - * - * @param oAuth2Parameters oAuthParameters - * @return - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - protected boolean isRegulatory(OAuth2Parameters oAuth2Parameters) throws OpenBankingException { - - return IdentityCommonUtil.getRegulatoryFromSPMetaData(oAuth2Parameters.getClientId()); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/OBRequestObjectValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/OBRequestObjectValidator.java deleted file mode 100644 index 6576baf4..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/OBRequestObjectValidator.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator; - -import com.wso2.openbanking.accelerator.common.validator.OpenBankingValidator; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.OBRequestObject; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.ValidationResponse; -import org.apache.commons.lang.StringUtils; - -import java.util.Map; - -/** - * The extension class for enforcing OB Request Object Validations. For Tool kits to extend. - */ -public class OBRequestObjectValidator { - - /** - * Extension point for tool kits. Perform validation and return the error message if any, else null. - * - * @param obRequestObject request object - * @param dataMap provides scope related data needed for validation from service provider meta data - * @return the response object with error message. - */ - public ValidationResponse validateOBConstraints(OBRequestObject obRequestObject, Map dataMap) { - - String violation = OpenBankingValidator.getInstance().getFirstViolation(obRequestObject); - - if (StringUtils.isEmpty(violation)) { - return new ValidationResponse(true); - } else { - return new ValidationResponse(false, violation); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/annotations/SigningAlgorithmValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/annotations/SigningAlgorithmValidator.java deleted file mode 100644 index 50ebb847..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/annotations/SigningAlgorithmValidator.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.annotations; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.beanutils.NestedNullException; -import org.apache.commons.beanutils.PropertyUtilsBean; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - - -/** - * To validate if the signing algorithm used to sign request object - * is the same as the algorithm given during registration. - */ -public class SigningAlgorithmValidator implements ConstraintValidator { - - private String algorithmXpath; - private String clientIdXPath; - private static Log log = LogFactory.getLog(SigningAlgorithmValidator.class); - - @Override - public void initialize(ValidSigningAlgorithm constraintAnnotation) { - - this.algorithmXpath = constraintAnnotation.algorithm(); - this.clientIdXPath = constraintAnnotation.clientId(); - } - - @Override - public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { - - try { - final String algorithm = new PropertyUtilsBean().getProperty(object, algorithmXpath).toString(); - final String clientId = BeanUtils.getProperty(object, clientIdXPath); - - return algorithmValidate(algorithm, clientId); - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | NestedNullException e) { - log.error("Error while resolving validation fields", e); - return false; - } - } - - boolean algorithmValidate(String requestedAlgo, String clientId) { - - try { - if (!(StringUtils.isNotEmpty(new IdentityCommonHelper().getCertificateContent(clientId)) - && IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId))) { - String registeredAlgo = new IdentityCommonHelper().getAppPropertyFromSPMetaData( - clientId, IdentityCommonConstants.REQUEST_OBJECT_SIGNING_ALG); - - return requestedAlgo.equals(registeredAlgo); - } else { - return true; - } - } catch (OpenBankingException e) { - log.error("Error while getting signing SP metadata", e); - } - - return false; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/annotations/ValidSigningAlgorithm.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/annotations/ValidSigningAlgorithm.java deleted file mode 100644 index 0410400b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/annotations/ValidSigningAlgorithm.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * An annotation to execute signing algorithm validation. - */ -@Target(ElementType.TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {SigningAlgorithmValidator.class}) -public @interface ValidSigningAlgorithm { - - String message() default "Invalid signing algorithm used"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String algorithm() default "alg"; - - String clientId() default "clientId"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/models/OBRequestObject.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/models/OBRequestObject.java deleted file mode 100644 index 2bd05183..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/models/OBRequestObject.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models; - -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.PlainJWT; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.validator.annotation.RequiredParameter; -import com.wso2.openbanking.accelerator.common.validator.annotation.RequiredParameters; -import com.wso2.openbanking.accelerator.common.validator.annotation.ValidAudience; -import com.wso2.openbanking.accelerator.common.validator.annotation.ValidScopeFormat; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.annotations.ValidSigningAlgorithm; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; -import org.wso2.carbon.identity.openidconnect.model.RequestedClaim; - -import java.util.List; -import java.util.Map; - -/** - * A decorator class of RequestObject to enforce validations. Can add delegate methods as required. - * - * @param Any child of this class. - */ -@RequiredParameters({ - @RequiredParameter(param = "signedJWT", - message = "Only Signed JWS is accepted for request object"), - @RequiredParameter(param = "claimsSet.claims.aud", - message = "aud parameter is missing in the request object") -}) -@ValidScopeFormat(scope = "claimsSet.claims.scope") -@ValidAudience(audience = "claimsSet.claims.aud", clientId = "claimsSet.claims.client_id") -@ValidSigningAlgorithm(algorithm = "signedJWT.header.algorithm.name", clientId = "claimsSet.claims.client_id") -public class OBRequestObject extends RequestObject { - - // decorator object - private RequestObject requestObject; - private static final long serialVersionUID = -568639546792395972L; - - public OBRequestObject(RequestObject requestObject) throws RequestObjectException { - if (requestObject == null) { - throw new RequestObjectException(RequestObjectException.ERROR_CODE_INVALID_REQUEST, - "Null request object passed"); - } - this.requestObject = requestObject; - } - - - // for tool kits to use - - /** - * Any child object of this class can create object of this class using this constructor. - * - * @param childObject Any class extending this class. - */ - public OBRequestObject(T childObject) { - this.requestObject = childObject; - } - - - // delegations - @Override - public SignedJWT getSignedJWT() { - return requestObject.getSignedJWT(); - } - - @Override - public JWTClaimsSet getClaimsSet() { - return requestObject.getClaimsSet(); - } - - @Override - public boolean isSignatureValid() { - return requestObject.isSignatureValid(); - } - - @Override - public void setIsSignatureValid(boolean isSignatureValid) { - requestObject.setIsSignatureValid(isSignatureValid); - } - - @Override - public boolean isSigned() { - return requestObject.isSigned(); - } - - @Override - public PlainJWT getPlainJWT() { - return requestObject.getPlainJWT(); - } - - @Override - public void setPlainJWT(PlainJWT plainJWT) throws RequestObjectException { - requestObject.setPlainJWT(plainJWT); - } - - @Override - public Map> getRequestedClaims() { - return requestObject.getRequestedClaims(); - } - - @Override - public void setRequestedClaims(Map> claimsforRequestParameter) { - requestObject.setRequestedClaims(claimsforRequestParameter); - } - - @Override - public void setSignedJWT(SignedJWT signedJWT) throws RequestObjectException { - requestObject.setSignedJWT(signedJWT); - } - - @Override - public void setClaimSet(JWTClaimsSet claimSet) { - requestObject.setClaimSet(claimSet); - } - - @Override - public String getClaimValue(String claimName) { - return requestObject.getClaimValue(claimName); - } - - @Override - public Object getClaim(String claimName) { - return requestObject.getClaim(claimName); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/models/ValidationResponse.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/models/ValidationResponse.java deleted file mode 100644 index 88e9b676..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/models/ValidationResponse.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models; - -/** - * Holder of response in request object validation. - */ -public class ValidationResponse { - private boolean valid; - private String violationMessage; - - public ValidationResponse(boolean valid) { - this.valid = valid; - } - - public ValidationResponse(boolean valid, String violationMessage) { - this.valid = valid; - this.violationMessage = violationMessage; - } - - public boolean isValid() { - return valid; - } - - public void setValid(boolean valid) { - this.valid = valid; - } - - public String getViolationMessage() { - return violationMessage; - } - - public void setViolationMessage(String violationMessage) { - this.violationMessage = violationMessage; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBCodeResponseTypeHandlerExtension.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBCodeResponseTypeHandlerExtension.java deleted file mode 100644 index 5d3ddf6f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBCodeResponseTypeHandlerExtension.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.authz.handlers.CodeResponseTypeHandler; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; - -/** - * Extension to append scope with OB_ prefix at the end of auth flow, before offering auth code. - */ -public class OBCodeResponseTypeHandlerExtension extends CodeResponseTypeHandler { - - static OBResponseTypeHandler obResponseTypeHandler = - IdentityExtensionsDataHolder.getInstance().getObResponseTypeHandler(); - - /** - * Extension point to get updated scope and refresh token validity period. - * - * @param oauthAuthzMsgCtx - * @return - * @throws IdentityOAuth2Exception - */ - @Override - public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception { - - try { - if (!isRegulatory(oauthAuthzMsgCtx.getAuthorizationReqDTO().getConsumerKey())) { - return issueCode(oauthAuthzMsgCtx); - } - } catch (OpenBankingException e) { - throw new IdentityOAuth2Exception("Error while reading regulatory property"); - } - - // make oauthAuthzMsgCtx immutable - oauthAuthzMsgCtx.setRefreshTokenvalidityPeriod( - obResponseTypeHandler.updateRefreshTokenValidityPeriod(oauthAuthzMsgCtx)); - if (obResponseTypeHandler.updateApprovedScopes(oauthAuthzMsgCtx) != null) { - oauthAuthzMsgCtx.setApprovedScope(obResponseTypeHandler.updateApprovedScopes(oauthAuthzMsgCtx)); - } else { - throw new IdentityOAuth2Exception("Error while updating scopes"); - } - - return issueCode(oauthAuthzMsgCtx); - } - - /** - * Separated method to call parent issue. - * - * @param oAuthAuthzReqMessageContext - * @return - * @throws IdentityOAuth2Exception - */ - @Generated(message = "Cannot test super calls") - OAuth2AuthorizeRespDTO issueCode( - OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) throws IdentityOAuth2Exception { - - return super.issue(oAuthAuthzReqMessageContext); - } - - @Generated(message = "Ignoring because it requires a service call") - boolean isRegulatory(String clientId) throws OpenBankingException { - - return IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBHybridResponseTypeHandlerExtension.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBHybridResponseTypeHandlerExtension.java deleted file mode 100644 index 5fc608ad..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBHybridResponseTypeHandlerExtension.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.authz.handlers.HybridResponseTypeHandler; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; - -/** - * Extension to append scope with OB_ prefix at the end of auth flow, before offering auth code. - */ -public class OBHybridResponseTypeHandlerExtension extends HybridResponseTypeHandler { - - static OBResponseTypeHandler obResponseTypeHandler = - IdentityExtensionsDataHolder.getInstance().getObResponseTypeHandler(); - - /** - * Extension point to get updated scope and refresh token validity period. - * - * @param oauthAuthzMsgCtx - * @return - * @throws IdentityOAuth2Exception - */ - @Override - public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception { - - try { - if (!isRegulatory(oauthAuthzMsgCtx.getAuthorizationReqDTO().getConsumerKey())) { - return issueCode(oauthAuthzMsgCtx); - } - } catch (OpenBankingException e) { - throw new IdentityOAuth2Exception("Error while reading regulatory property"); - } - - oauthAuthzMsgCtx.setRefreshTokenvalidityPeriod( - obResponseTypeHandler.updateRefreshTokenValidityPeriod(oauthAuthzMsgCtx)); - if (obResponseTypeHandler.updateApprovedScopes(oauthAuthzMsgCtx) != null) { - oauthAuthzMsgCtx.setApprovedScope(obResponseTypeHandler.updateApprovedScopes(oauthAuthzMsgCtx)); - } else { - throw new IdentityOAuth2Exception("Error while updating scopes"); - } - return issueCode(oauthAuthzMsgCtx); - } - - /** - * Separated method to call parent issue. - * - * @param oAuthAuthzReqMessageContext - * @return - * @throws IdentityOAuth2Exception - */ - @Generated(message = "cant unit test super calls") - OAuth2AuthorizeRespDTO issueCode( - OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) throws IdentityOAuth2Exception { - - return super.issue(oAuthAuthzReqMessageContext); - } - - @Generated(message = "Ignoring because it requires a service call") - boolean isRegulatory(String clientId) throws OpenBankingException { - - return IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBResponseTypeHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBResponseTypeHandler.java deleted file mode 100644 index dd305d7f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/OBResponseTypeHandler.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler; - -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; - -/** - * Extension interface for setting values in response type handling. Toolkits have to implement this. - */ -public interface OBResponseTypeHandler { - - /** - * return the new refresh validity period. - * - * @param oAuthAuthzReqMessageContext - * @return - */ - public long updateRefreshTokenValidityPeriod(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext); - - /** - * return the new approved scope. - * - * @param oAuthAuthzReqMessageContext - * @return - */ - public String[] updateApprovedScopes(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext); - - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/impl/OBDefaultResponseTypeHandlerImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/impl/OBDefaultResponseTypeHandlerImpl.java deleted file mode 100644 index 15d4de52..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/impl/OBDefaultResponseTypeHandlerImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler.impl; - -import com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler.OBResponseTypeHandler; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.openidconnect.RequestObjectService; -import org.wso2.carbon.identity.openidconnect.model.RequestedClaim; - -import java.util.Arrays; -import java.util.List; - -/** - * Default extension implementation. Used to do the accelerator testing. Mimics a UK flow. - */ -public class OBDefaultResponseTypeHandlerImpl implements OBResponseTypeHandler { - - private static final String OPENBANKING_INTENT_ID = "openbanking_intent_id"; - private static final Log log = LogFactory.getLog(OBDefaultResponseTypeHandlerImpl.class); - - /** - * return the new refresh validity period. - * - * @param oAuthAuthzReqMessageContext - * @return - */ - public long updateRefreshTokenValidityPeriod(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) { - - return oAuthAuthzReqMessageContext.getRefreshTokenvalidityPeriod(); - } - - /** - * return the new approved scope. - * - * @param oAuthAuthzReqMessageContext - * @return - */ - public String[] updateApprovedScopes(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) { - - if (oAuthAuthzReqMessageContext != null && oAuthAuthzReqMessageContext.getAuthorizationReqDTO() != null) { - - String[] scopes = oAuthAuthzReqMessageContext.getApprovedScope(); - if (scopes != null && !Arrays.asList(scopes).contains("api_store")) { - - String sessionDataKey = oAuthAuthzReqMessageContext.getAuthorizationReqDTO().getSessionDataKey(); - String consentID = getConsentIDFromSessionData(sessionDataKey); - if (consentID.isEmpty()) { - log.error("Consent-ID retrieved from request object claims is empty"); - return scopes; - } - - String consentIdClaim = IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .get(IdentityCommonConstants.CONSENT_ID_CLAIM_NAME).toString(); - String consentScope = consentIdClaim + consentID; - if (!Arrays.asList(scopes).contains(consentScope)) { - String[] updatedScopes = (String[]) ArrayUtils.addAll(scopes, new String[]{consentScope}); - if (log.isDebugEnabled()) { - log.debug("Updated scopes: " + Arrays.toString(updatedScopes)); - } - return updatedScopes; - } - } - - } else { - return new String[0]; - } - - return oAuthAuthzReqMessageContext.getApprovedScope(); - } - - /** - * Call sessionDataAPI and retrieve request object, decode it and return consentID. - * - * @param sessionDataKey sessionDataKeyConsent parameter from authorize request - * @return consentID - */ - String getConsentIDFromSessionData(String sessionDataKey) { - - String consentID = StringUtils.EMPTY; - if (sessionDataKey != null && !sessionDataKey.isEmpty()) { - RequestObjectService requestObjectService = IdentityExtensionsDataHolder.getInstance() - .getRequestObjectService(); - if (requestObjectService != null) { - consentID = retrieveConsentIDFromReqObjService(requestObjectService, sessionDataKey); - if (consentID.isEmpty()) { - log.error("Failed to retrieve ConsentID from query parameters"); - } - } else { - log.error("Failed to retrieve Request Object Service"); - } - } else { - log.error("Invalid Session Data Key"); - } - return consentID; - } - - /** - * Call Request Object Service and retrieve consent id. - * - * @param service request object service - * @param sessionDataKey session data key - * @return consentID - */ - String retrieveConsentIDFromReqObjService(RequestObjectService service, String sessionDataKey) { - - String consentID = StringUtils.EMPTY; - try { - List requestedClaims = service.getRequestedClaimsForSessionDataKey(sessionDataKey, - false); - consentID = iterateClaims(requestedClaims); - if (consentID.isEmpty()) { - requestedClaims = service.getRequestedClaimsForSessionDataKey(sessionDataKey, true); - consentID = iterateClaims(requestedClaims); - } - - } catch (RequestObjectException ex) { - log.error("Exception occurred", ex); - } - return consentID; - } - - /** - * Iterate the claims list to identify the consent-ID. - * - * @param requestedClaims list of claims - * @return consent id - */ - String iterateClaims(List requestedClaims) { - - String consentID = StringUtils.EMPTY; - for (RequestedClaim claim : requestedClaims) { - if (log.isDebugEnabled()) { - log.debug("Claim: " + claim.getName() + ", value: " + claim.getValue()); - } - - if (OPENBANKING_INTENT_ID.equals(claim.getName())) { - consentID = claim.getValue(); - if (log.isDebugEnabled()) { - log.debug("Consent-ID retrieved: " + consentID); - } - break; - } - } - return consentID; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBCodeResponseTypeValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBCodeResponseTypeValidator.java deleted file mode 100644 index 7ba4aebc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBCodeResponseTypeValidator.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.validator; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.validators.AbstractValidator; - -import javax.servlet.http.HttpServletRequest; - -/** - * Validator to validate whether the response type in the request object is allowed. - * Validate whether the correct response type is sent for regulatory applications. By default, code response type - * is not allowed for regulatory apps. - */ -public class OBCodeResponseTypeValidator extends AbstractValidator { - - private static Log log = LogFactory.getLog(OBCodeResponseTypeValidator.class); - private static final String CODE = "code"; - - @Override - public void validateMethod(HttpServletRequest request) throws OAuthProblemException { - - } - - @Override - public void validateContentType(HttpServletRequest request) throws OAuthProblemException { - - } - - @Override - public void validateRequiredParameters(HttpServletRequest request) throws OAuthProblemException { - String responseType = request.getParameter("response_type"); - String clientId = request.getParameter("client_id"); - if (!isValidResponseType(clientId, responseType)) { - log.error("Unsupported Response Type"); - throw OAuthProblemException.error("Unsupported Response Type"); - } - } - - /** - * Validate whether the correct response type is sent for regulatory applications. By default code response type - * is not allowed for regulatory apps. - * - * @param clientId Client Id received from Request Object - * @param responseType Response Type received from Request Object - * @return - */ - private boolean isValidResponseType(String clientId, String responseType) { - - try { - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId) && CODE.equals(responseType)) { - return false; - } - } catch (OpenBankingException e) { - log.error("Error while retrieving service provider metadata", e); - return false; - } - return true; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBHybridResponseTypeValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBHybridResponseTypeValidator.java deleted file mode 100644 index 0b8cb1e5..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBHybridResponseTypeValidator.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.validator; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.oltu.oauth2.as.validator.TokenValidator; -import org.apache.oltu.oauth2.common.OAuth; -import org.apache.oltu.oauth2.common.error.OAuthError; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.wso2.carbon.identity.oauth.common.OAuthConstants; - -import java.util.ArrayList; -import java.util.Arrays; - -import javax.servlet.http.HttpServletRequest; - -/** - Validator for hybrid flow code token requests. - */ -public class OBHybridResponseTypeValidator extends TokenValidator { - - private static final Log log = LogFactory.getLog(OBHybridResponseTypeValidator.class); - - private static boolean isContainOIDCScope(String scope) { - - String[] scopeArray = scope.split("\\s+"); - for (String anyScope : scopeArray) { - if (anyScope.equals(OAuthConstants.Scope.OPENID)) { - return true; - } - } - return false; - } - - @Override - public void validateRequiredParameters(HttpServletRequest request) throws OAuthProblemException { - - String openIdScope; - if (StringUtils.isNotBlank(request.getParameter(IdentityCommonConstants.REQUEST_URI))) { - - this.requiredParams = new ArrayList(Arrays.asList(OAuth.OAUTH_CLIENT_ID, - IdentityCommonConstants.REQUEST_URI)); - this.notAllowedParams.add(IdentityCommonConstants.REQUEST); - openIdScope = IdentityCommonUtil.decodeRequestObjectAndGetKey(request, OAuth.OAUTH_SCOPE); - } else { - openIdScope = request.getParameter(OAuth.OAUTH_SCOPE); - } - - super.validateRequiredParameters(request); - - if (StringUtils.isBlank(openIdScope) || !isContainOIDCScope(openIdScope)) { - String clientID = request.getParameter(OAuth.OAUTH_CLIENT_ID); - throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) - .description("Request with \'client_id\' = \'" + clientID + - "\' has \'response_type\' for \'hybrid flow\'; but \'openid\' scope not found."); - } - - } - - @Override - public void validateMethod(HttpServletRequest request) throws OAuthProblemException { - - String method = request.getMethod(); - if (!OAuth.HttpMethod.GET.equals(method) && !OAuth.HttpMethod.POST.equals(method)) { - throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) - .description("Method not correct."); - } - } - - @Override - public void validateContentType(HttpServletRequest request) throws OAuthProblemException { - - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/OBIdentifierAuthenticator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/OBIdentifierAuthenticator.java deleted file mode 100644 index 4eb4682d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/OBIdentifierAuthenticator.java +++ /dev/null @@ -1,608 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.authenticator; - -import com.wso2.openbanking.accelerator.common.exception.OBThrottlerException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.authenticator.constants.IdentifierHandlerConstants; -import com.wso2.openbanking.accelerator.identity.authenticator.util.OBIdentifierAuthUtil; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.throttler.service.OBThrottleService; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.json.JSONObject; -import org.wso2.carbon.identity.application.authentication.framework.AbstractApplicationAuthenticator; -import org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus; -import org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator; -import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade; -import org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException; -import org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException; -import org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; -import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; -import org.wso2.carbon.identity.application.authenticator.basicauth.BasicAuthenticator; -import org.wso2.carbon.identity.application.authenticator.basicauth.BasicAuthenticatorConstants; -import org.wso2.carbon.identity.application.common.model.User; -import org.wso2.carbon.identity.base.IdentityRuntimeException; -import org.wso2.carbon.identity.core.model.IdentityErrorMsgContext; -import org.wso2.carbon.identity.core.util.IdentityCoreConstants; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.core.UserCoreConstants; -import org.wso2.carbon.user.core.UserStoreException; -import org.wso2.carbon.user.core.UserStoreManager; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.RequestParams.IDENTIFIER_CONSENT; - -/** - * OB Identifier based authenticator. - */ -public class OBIdentifierAuthenticator extends AbstractApplicationAuthenticator - implements LocalApplicationAuthenticator { - - private static final long serialVersionUID = 1819664539416029785L; - private static final Log log = LogFactory.getLog(OBIdentifierAuthenticator.class); - private static final String PROMPT_CONFIRMATION_WINDOW = "promptConfirmationWindow"; - private static final String CONTINUE = "continue"; - private static final String RESET = "reset"; - private static final String RE_CAPTCHA_USER_DOMAIN = "user-domain-recaptcha"; - private static final String USER_TENANT_DOMAIN_MISMATCH = "UserTenantDomainMismatch"; - private static final String OB_IDENTIFIER_AUTHENTICATOR = "OBIdentifierAuthenticator"; - private static final String REDIRECT_URI = "redirect_uri"; - private static final String REQUEST_URI = "request_uri"; - - @Override - public boolean canHandle(HttpServletRequest request) { - - String userName = request.getParameter(IdentifierHandlerConstants.USER_NAME); - String identifierConsent = request.getParameter(IDENTIFIER_CONSENT); - return userName != null || identifierConsent != null; - } - - @Override - public AuthenticatorFlowStatus process(HttpServletRequest request, - HttpServletResponse response, AuthenticationContext context) - throws AuthenticationFailedException, LogoutFailedException { - - if (context.isLogoutRequest()) { - return AuthenticatorFlowStatus.SUCCESS_COMPLETED; - } else { - if (context.getPreviousAuthenticatedIdPs().get(BasicAuthenticatorConstants.LOCAL) != null) { - AuthenticatedIdPData local = - context.getPreviousAuthenticatedIdPs().get(BasicAuthenticatorConstants.LOCAL); - if (local.getAuthenticators().size() > 0) { - for (AuthenticatorConfig authenticatorConfig : local.getAuthenticators()) { - if (authenticatorConfig.getApplicationAuthenticator() instanceof BasicAuthenticator) { - boolean isPrompt = Boolean.parseBoolean(context.getAuthenticatorParams(this - .getName()).get(PROMPT_CONFIRMATION_WINDOW)); - - if (isPrompt) { - String identifierConsent = request.getParameter(IDENTIFIER_CONSENT); - if (identifierConsent != null && CONTINUE.equals(identifierConsent)) { - context.setSubject(local.getUser()); - return AuthenticatorFlowStatus.SUCCESS_COMPLETED; - } else if (identifierConsent != null && RESET.equals(identifierConsent)) { - initiateAuthenticationRequest(request, response, context); - return AuthenticatorFlowStatus.INCOMPLETE; - } else if (request.getParameter(IdentifierHandlerConstants.USER_NAME) != null) { - processAuthenticationResponse(request, response, context); - return AuthenticatorFlowStatus.SUCCESS_COMPLETED; - } else { - String identifierFirstConfirmationURL = - ConfigurationFacade.getInstance().getIdentifierFirstConfirmationURL(); - String queryParams = context.getContextIdIncludedQueryParams(); - try { - queryParams = queryParams + "&username=" + local.getUser() - .toFullQualifiedUsername(); - response.sendRedirect(identifierFirstConfirmationURL + - ("?" + queryParams)); - return AuthenticatorFlowStatus.INCOMPLETE; - } catch (IOException e) { - throw new AuthenticationFailedException(e.getMessage(), e); - } - } - } else { - context.setSubject(local.getUser()); - return AuthenticatorFlowStatus.SUCCESS_COMPLETED; - } - } - } - } - } else if (request.getParameter(IDENTIFIER_CONSENT) != null) { - //submit from the confirmation page. - initiateAuthenticationRequest(request, response, context); - return AuthenticatorFlowStatus.INCOMPLETE; - } - return super.process(request, response, context); - } - } - - @Override - protected void initiateAuthenticationRequest(HttpServletRequest request, - HttpServletResponse response, AuthenticationContext context) - throws AuthenticationFailedException { - - int throttleLimit = 3; //default allowed attempts (use this if config is not defined) - int throttleTimePeriod = 180; //default blocked time period (3 minutes) - String showAuthFailureReason = ""; - String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL(); - String retryPage = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL(); - String queryParams = context.getContextIdIncludedQueryParams(); - OBThrottleService obThrottleService = IdentityExtensionsDataHolder.getInstance().getOBThrottleService(); - - //Read authenticator configs - Map parameterMap = getAuthenticatorConfig().getParameterMap(); - if (parameterMap != null) { - throttleLimit = Integer.parseInt(parameterMap.get("throttleLimit")); - throttleTimePeriod = Integer.parseInt(parameterMap.get("throttleTimePeriod")); - showAuthFailureReason = parameterMap.get("showAuthFailureReason"); - } - - try { - String retryParam = ""; - if (context.isRetrying()) { - // Update throttling data - String userIp = IdentityUtil.getClientIpAddress(request); - obThrottleService - .updateThrottleData(OB_IDENTIFIER_AUTHENTICATOR, userIp, throttleLimit, throttleTimePeriod); - // Check if the client-ip is throttled - if (obThrottleService.isThrottled(OB_IDENTIFIER_AUTHENTICATOR, userIp)) { - retryParam = "&authFailure=true&authFailureMsg=Too.many.attempts"; - } else { - if (context.getProperty(IdentifierHandlerConstants.CONTEXT_PROP_INVALID_EMAIL_USERNAME) != null && - (Boolean) context.getProperty(IdentifierHandlerConstants. - CONTEXT_PROP_INVALID_EMAIL_USERNAME)) { - retryParam = "&authFailure=true&authFailureMsg=Login.failed"; - context.setProperty(IdentifierHandlerConstants.CONTEXT_PROP_INVALID_EMAIL_USERNAME, false); - } else { - retryParam = "&authFailure=true&authFailureMsg=Login.failed"; - } - } - } - - if (context.getProperty(USER_TENANT_DOMAIN_MISMATCH) != null && - (Boolean) context.getProperty(USER_TENANT_DOMAIN_MISMATCH)) { - retryParam = "&authFailure=true&authFailureMsg=user.tenant.domain.mismatch.message"; - context.setProperty(USER_TENANT_DOMAIN_MISMATCH, false); - } - - IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg(); - IdentityUtil.clearIdentityErrorMsg(); - - if (errorContext != null && errorContext.getErrorCode() != null) { - log.debug("Identity error message context is not null"); - String errorCode = errorContext.getErrorCode(); - - if (errorCode.equals(IdentityCoreConstants.USER_ACCOUNT_NOT_CONFIRMED_ERROR_CODE)) { - retryParam = "&authFailure=true&authFailureMsg=account.confirmation.pending"; - String username = request.getParameter(IdentifierHandlerConstants.USER_NAME); - Object domain = IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN); - if (domain != null) { - username = IdentityUtil.addDomainToName(username, domain.toString()); - } - String redirectURL = loginPage + ("?" + queryParams) + IdentifierHandlerConstants.FAILED_USERNAME - + URLEncoder.encode(username, IdentifierHandlerConstants.UTF_8) + - IdentifierHandlerConstants.ERROR_CODE + errorCode + IdentifierHandlerConstants - .AUTHENTICATORS + getName() + ":" + IdentifierHandlerConstants.LOCAL + retryParam; - response.sendRedirect(redirectURL); - - } else if ("true".equals(showAuthFailureReason)) { - String reason = null; - if (errorCode.contains(":")) { - String[] errorCodeReason = errorCode.split(":"); - errorCode = errorCodeReason[0]; - if (errorCodeReason.length > 1) { - reason = errorCodeReason[1]; - } - } - int remainingAttempts = - errorContext.getMaximumLoginAttempts() - errorContext.getFailedLoginAttempts(); - - if (log.isDebugEnabled()) { - log.debug("errorCode : " + errorCode); - log.debug("username : " + request.getParameter(IdentifierHandlerConstants.USER_NAME)); - log.debug("remainingAttempts : " + remainingAttempts); - } - - if (errorCode.equals(UserCoreConstants.ErrorCode.INVALID_CREDENTIAL)) { - retryParam = retryParam + IdentifierHandlerConstants.ERROR_CODE + errorCode - + IdentifierHandlerConstants.FAILED_USERNAME + URLEncoder - .encode(request.getParameter(IdentifierHandlerConstants.USER_NAME), - IdentifierHandlerConstants.UTF_8) - + "&remainingAttempts=" + remainingAttempts; - response.sendRedirect(loginPage + ("?" + queryParams) - + IdentifierHandlerConstants.AUTHENTICATORS + getName() + ":" + - IdentifierHandlerConstants.LOCAL + retryParam); - } else if (errorCode.equals(UserCoreConstants.ErrorCode.USER_IS_LOCKED)) { - String redirectURL = retryPage; - if (remainingAttempts == 0) { - if (StringUtils.isBlank(reason)) { - redirectURL = URLEncoder.encode((redirectURL + ("?" + queryParams)), - IdentifierHandlerConstants.UTF_8) + IdentifierHandlerConstants.ERROR_CODE - + errorCode + IdentifierHandlerConstants.FAILED_USERNAME + - URLEncoder.encode(request.getParameter(IdentifierHandlerConstants.USER_NAME), - IdentifierHandlerConstants.UTF_8) + - "&remainingAttempts=0"; - } else { - redirectURL = URLEncoder.encode((redirectURL + ("?" + queryParams)), - IdentifierHandlerConstants.UTF_8) + IdentifierHandlerConstants.ERROR_CODE - + errorCode + "&lockedReason=" + reason + - IdentifierHandlerConstants.FAILED_USERNAME + - URLEncoder.encode(request.getParameter(IdentifierHandlerConstants.USER_NAME), - IdentifierHandlerConstants.UTF_8) + "&remainingAttempts=0"; - } - } else { - if (StringUtils.isBlank(reason)) { - redirectURL = URLEncoder.encode((redirectURL + ("?" + queryParams)), - IdentifierHandlerConstants.UTF_8) + IdentifierHandlerConstants.ERROR_CODE + - errorCode + IdentifierHandlerConstants.FAILED_USERNAME + - URLEncoder.encode(request.getParameter(IdentifierHandlerConstants.USER_NAME), - IdentifierHandlerConstants.UTF_8); - } else { - redirectURL = URLEncoder.encode((redirectURL + ("?" + queryParams)), - IdentifierHandlerConstants.UTF_8) + IdentifierHandlerConstants.ERROR_CODE + - errorCode + "&lockedReason=" + reason + - IdentifierHandlerConstants.FAILED_USERNAME + - URLEncoder.encode(request.getParameter(IdentifierHandlerConstants.USER_NAME), - IdentifierHandlerConstants.UTF_8); - } - } - response.sendRedirect(redirectURL); - } else { - retryParam = retryParam + IdentifierHandlerConstants.ERROR_CODE + errorCode - + IdentifierHandlerConstants.FAILED_USERNAME + URLEncoder - .encode(request.getParameter(IdentifierHandlerConstants.USER_NAME), - IdentifierHandlerConstants.UTF_8); - response.sendRedirect(loginPage + ("?" + queryParams) - + IdentifierHandlerConstants.AUTHENTICATORS + getName() + ":" - + IdentifierHandlerConstants.LOCAL + retryParam); - } - } else { - log.debug("Unknown identity error code."); - response.sendRedirect(loginPage + ("?" + queryParams) - + IdentifierHandlerConstants.AUTHENTICATORS + getName() + ":" + - IdentifierHandlerConstants.LOCAL + retryParam); - } - } else { - log.debug("Identity error message context is null"); - response.sendRedirect(loginPage + ("?" + queryParams) - + IdentifierHandlerConstants.AUTHENTICATORS + getName() + ":" + - IdentifierHandlerConstants.LOCAL + retryParam); - } - } catch (IOException e) { - throw new AuthenticationFailedException(e.getMessage(), User.getUserFromUserName(request.getParameter - (IdentifierHandlerConstants.USER_NAME)), e); - } catch (OBThrottlerException e) { - throw new AuthenticationFailedException("Error occurred while deleting throttle data.", e); - } - } - - @Override - protected void processAuthenticationResponse(HttpServletRequest request, - HttpServletResponse response, AuthenticationContext context) - throws AuthenticationFailedException { - - OBIdentifierAuthUtil.validateUsername(request.getParameter(BasicAuthenticatorConstants.USER_NAME), context); - OBThrottleService obThrottleService = IdentityExtensionsDataHolder.getInstance().getOBThrottleService(); - String username = OBIdentifierAuthUtil.preprocessUsername( - request.getParameter(IdentifierHandlerConstants.USER_NAME), context); - Map authProperties = context.getProperties(); - if (authProperties == null) { - authProperties = new HashMap<>(); - context.setProperties(authProperties); - } - - String userIp = IdentityUtil.getClientIpAddress(request); - try { - // Check if the client-ip is throttled. - if (obThrottleService.isThrottled(OB_IDENTIFIER_AUTHENTICATOR, userIp)) { - throw new AuthenticationFailedException("Too many attempts to log in.", - User.getUserFromUserName(username)); - } - } catch (OBThrottlerException e) { - throw new AuthenticationFailedException("Error occurred while deleting throttle data.", e); - } - - if (getAuthenticatorConfig().getParameterMap() != null) { - String validateUsername = getAuthenticatorConfig().getParameterMap().get("ValidateUsername"); - if (Boolean.valueOf(validateUsername)) { - boolean isUserExists; - UserStoreManager userStoreManager; - // Check if the username exists. - try { - int tenantId = IdentityTenantUtil.getTenantIdOfUser(username); - UserRealm userRealm = IdentityExtensionsDataHolder.getInstance().getRealmService() - .getTenantUserRealm(tenantId); - - if (userRealm != null) { - userStoreManager = (UserStoreManager) userRealm.getUserStoreManager(); - isUserExists = userStoreManager.isExistingUser(MultitenantUtils.getTenantAwareUsername - (username)); - } else { - throw new AuthenticationFailedException("Cannot find the user realm for the given tenant: " + - tenantId, User.getUserFromUserName(username)); - } - } catch (IdentityRuntimeException e) { - log.error("OBIdentifierAuthenticator failed while trying to get the tenant ID of " + - "the user " + username, e); - throw new AuthenticationFailedException(e.getMessage(), User.getUserFromUserName(username), e); - } catch (org.wso2.carbon.user.api.UserStoreException e) { - log.error("OBIdentifierAuthenticator failed while trying to authenticate", e); - throw new AuthenticationFailedException(e.getMessage(), User.getUserFromUserName(username), e); - } - if (!isUserExists) { - log.debug("User does not exist."); - if (IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN) != null) { - username = IdentityUtil.addDomainToName( - username, IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN) - .toString()); - } - IdentityUtil.threadLocalProperties.get().remove(RE_CAPTCHA_USER_DOMAIN); - throw new InvalidCredentialsException("User does not exist.", User.getUserFromUserName(username)); - } - String tenantDomain = MultitenantUtils.getTenantDomain(username); - authProperties.put("user-tenant-domain", tenantDomain); - } - } - - username = FrameworkUtils.prependUserStoreDomainToName(username); - authProperties.put("username", username); - Map identifierParams = new HashMap<>(); - identifierParams.put(FrameworkConstants.JSAttributes.JS_OPTIONS_USERNAME, username); - Map> contextParams = new HashMap<>(); - contextParams.put(FrameworkConstants.JSAttributes.JS_COMMON_OPTIONS, identifierParams); - //Identifier first is the first authenticator. - context.getPreviousAuthenticatedIdPs().clear(); - context.addAuthenticatorParams(contextParams); - context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(username)); - if (context.getParameters().containsKey("username")) { - try { - obThrottleService.deleteRecordOnSuccessAttempt(OB_IDENTIFIER_AUTHENTICATOR, userIp); - } catch (OBThrottlerException e) { - throw new AuthenticationFailedException("Error occurred while deleting throttle data.", e); - } - } - } - - @Override - protected boolean retryAuthenticationEnabled() { - return true; - } - - @Override - public String getContextIdentifier(HttpServletRequest request) { - return request.getParameter("sessionDataKey"); - } - - @Override - public String getFriendlyName() { - return IdentifierHandlerConstants.HANDLER_FRIENDLY_NAME; - } - - @Override - public String getName() { - return IdentifierHandlerConstants.HANDLER_NAME; - } - - /** - * To get session details from SessionDataKey. - * authRequestURL need be configured in the IAM deployment.toml file. - * @param sessionDataKey session data key - * @return session data - * @throws OpenBankingException openbanking exception - */ - public String getSessionData(String sessionDataKey) throws OpenBankingException { - - BufferedReader reader = null; - String authRequestURL = null; - RealmConfiguration realmConfig = null; - - //Read authenticator configs - Map parameterMap = getAuthenticatorConfig().getParameterMap(); - if (parameterMap != null) { - authRequestURL = parameterMap.get(IdentifierHandlerConstants.AUTH_REQ_URL); - } - try { - realmConfig = IdentityExtensionsDataHolder.getInstance().getRealmService() - .getBootstrapRealm().getUserStoreManager().getRealmConfiguration(); - } catch (UserStoreException e) { - throw new OpenBankingException("Error while retrieving session data", e); - } - String adminUsername = realmConfig.getAdminUserName(); - char[] adminPassword = realmConfig.getAdminPassword().toCharArray(); - - String credentials = adminUsername + ":" + String.valueOf(adminPassword); - credentials = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); - - try (CloseableHttpClient client = HTTPClientUtils.getHttpsClient()) { - HttpGet dataRequest = new HttpGet(authRequestURL + sessionDataKey); - dataRequest.addHeader(IdentifierHandlerConstants.ACCEPT_HEADER, - IdentifierHandlerConstants.ACCEPT_HEADER_VALUE); - dataRequest.addHeader(IdentifierHandlerConstants.AUTH_HEADER, "Basic " + credentials); - CloseableHttpResponse dataResponse = client.execute(dataRequest); - - reader = new BufferedReader(new InputStreamReader(dataResponse.getEntity() - .getContent(), "UTF-8")); - String inputLine; - StringBuffer buffer = new StringBuffer(); - while ((inputLine = reader.readLine()) != null) { - buffer.append(inputLine); - } - - if (dataResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { - return null; - } else { - JSONObject sessionData = new JSONObject(buffer.toString()); - appendRedirectUri(sessionData); - return sessionData.toString(); - } - } catch (IOException e) { - throw new OpenBankingException("Error while retrieving session data", e); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - log.error("Error while closing buffered reader", e); - } - } - } - } - - /** - * Append redirect_uri value to session data for par requests. - * - * @param sessionData - */ - private void appendRedirectUri(JSONObject sessionData) throws OpenBankingException { - - // Handle redirect uri for par request. - // In par requests, there's no redirect_uri in request object itself, so fetch redirect uri from cached request. - if (!sessionData.has(REDIRECT_URI) && sessionData.has(REQUEST_URI)) { - - JSONObject requestObjectVal = getParRequestObject(sessionData); - if (requestObjectVal.has(REDIRECT_URI)) { - sessionData.put(REDIRECT_URI, requestObjectVal.get(REDIRECT_URI)); - } else { - log.error("redirect_uri could not be found in the par request object."); - throw new OpenBankingException("redirect_uri could not be found in the par request object."); - } - } - } - - /** - * Get redirect_uri using request_uri. - * - * @param requestUri - request_uri - * @return redirect_uri - * @throws OpenBankingException - OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a valid cache entry") - public String getRedirectUri(String requestUri) throws OpenBankingException { - - JSONObject requestObjectVal = getParRequestObject(requestUri); - if (requestObjectVal.has(REDIRECT_URI)) { - return requestObjectVal.get(REDIRECT_URI).toString(); - } else { - log.error("redirect_uri could not be found in the par request object."); - throw new OpenBankingException("redirect_uri could not be found in the par request object."); - } - } - - /** - * Retrieve PAR request object from session data cache. - * - * @param sessionData session data - * @return Request object json. - * @throws OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a valid cache entry") - private JSONObject getParRequestObject(JSONObject sessionData) throws OpenBankingException { - - //get request ref Ex -> "IVL...." from "urn::IVL..." - String requestUri = sessionData.get(REQUEST_URI).toString(); - return getParRequestObject(requestUri); - } - - /** - * Retrieve PAR request object from request_uri. - * - * @param requestUri - request_uri - * @return Request object json. - * @throws OpenBankingException - OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a valid cache entry") - private JSONObject getParRequestObject(String requestUri) throws OpenBankingException { - - String[] requestUriArr = requestUri.split(":"); - String requestUriRef = requestUriArr[requestUriArr.length - 1]; - return getRequestObjectUsingUriReference(requestUriRef); - } - - /** - * Retrieve PAR request object using request_uri reference. - * - * @param requestUriReference - request_uri reference (i.e:last part of request_uri split by :) - * @return Request object json. - * @throws OpenBankingException - OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a valid cache entry") - private JSONObject getRequestObjectUsingUriReference(String requestUriReference) throws OpenBankingException { - - SessionDataCacheKey cacheKey = new SessionDataCacheKey(requestUriReference); - SessionDataCacheEntry cacheEntry = SessionDataCache.getInstance().getValueFromCache(cacheKey); - - if (cacheEntry != null) { - String essentialClaims = cacheEntry.getoAuth2Parameters().getEssentialClaims(); - byte[] requestObject; - try { - requestObject = Base64.getDecoder().decode(essentialClaims.split("\\.")[1]); - } catch (IllegalArgumentException e) { - // Decode if the requestObject is base64-url encoded. - requestObject = Base64.getUrlDecoder().decode(essentialClaims.split("\\.")[1]); - } - return new JSONObject(new String(requestObject, StandardCharsets.UTF_8)); - } else { - log.error("Unable to fetch par request object from session data cache."); - throw new OpenBankingException("Unable to fetch par request object from session data cache."); - } - } - - /** - * Get SSA client_name using clientId. - * - * @param clientId client id. - * @param property required property. - * @return service provider value. - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public String getSPProperty (String clientId, String property) throws OpenBankingException { - - return new IdentityCommonHelper().getAppPropertyFromSPMetaData(clientId, property); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/constants/IdentifierHandlerConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/constants/IdentifierHandlerConstants.java deleted file mode 100644 index edc3c1dd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/constants/IdentifierHandlerConstants.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.authenticator.constants; - -/** - * Constants used by the OBIdentifierAuthenticator. - */ -public class IdentifierHandlerConstants { - - public static final String CONTEXT_PROP_INVALID_EMAIL_USERNAME = "InvalidEmailUsername"; - public static final String HANDLER_NAME = "IdentifierExecutor"; - public static final String HANDLER_FRIENDLY_NAME = "ob-identifier-first"; - public static final String USER_NAME = "username"; - public static final String FAILED_USERNAME = "&failedUsername="; - public static final String ERROR_CODE = "&errorCode="; - public static final String AUTHENTICATORS = "&authenticators="; - public static final String LOCAL = "LOCAL"; - public static final String UTF_8 = "UTF-8"; - - //auth request params - public static final String AUTH_REQ_URL = "authRequestURL"; - public static final String ACCEPT_HEADER = "accept"; - public static final String ACCEPT_HEADER_VALUE = "application/json"; - public static final String AUTH_HEADER = "Authorization"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/util/OBIdentifierAuthUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/util/OBIdentifierAuthUtil.java deleted file mode 100644 index 0691788d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/authenticator/util/OBIdentifierAuthUtil.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.authenticator.util; - -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -/** - * Util methods for OBIdentifierFirstAuthenticator. - */ -public class OBIdentifierAuthUtil { - - /** - * Add tenant domain to the username. - * - * @param username - username - * @param context - authentication context - * @return - processed username - */ - public static String preprocessUsername(String username, AuthenticationContext context) { - if (context.getSequenceConfig().getApplicationConfig().isSaaSApp()) { - return username; - } else { - if (IdentityUtil.isEmailUsernameEnabled()) { - if (StringUtils.countMatches(username, "@") == 1) { - return username + "@" + context.getTenantDomain(); - } - } else if (!username.contains("@")) { - return username + "@" + context.getTenantDomain(); - } - return username; - } - } - - /** - * Check if the username exists. - * - * @param username - username - * @param context - authentication context - * @throws InvalidCredentialsException - */ - public static void validateUsername(String username, AuthenticationContext context) - throws InvalidCredentialsException { - if (IdentityUtil.isEmailUsernameEnabled()) { - String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username); - if (StringUtils.countMatches(tenantAwareUsername, "@") < 1) { - context.setProperty("InvalidEmailUsername", true); - throw new InvalidCredentialsException("Invalid username. Username has to be an email."); - } - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/builders/DefaultOBRequestUriRequestObjectBuilder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/builders/DefaultOBRequestUriRequestObjectBuilder.java deleted file mode 100644 index 047a55bd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/builders/DefaultOBRequestUriRequestObjectBuilder.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.builders; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JOSEObject; -import com.nimbusds.jose.JWEObject; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.crypto.RSADecrypter; -import com.nimbusds.jwt.EncryptedJWT; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.PlainJWT; -import com.nimbusds.jwt.SignedJWT; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; -import org.wso2.carbon.identity.openidconnect.RequestObjectBuilder; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import java.security.Key; -import java.security.interfaces.RSAPrivateKey; -import java.text.ParseException; -import java.time.Instant; - -import static org.wso2.carbon.identity.openidconnect.model.Constants.JWT_PART_DELIMITER; -import static org.wso2.carbon.identity.openidconnect.model.Constants.NUMBER_OF_PARTS_IN_JWE; -import static org.wso2.carbon.identity.openidconnect.model.Constants.NUMBER_OF_PARTS_IN_JWS; - -/** - * Build Request Object from request_uri for authorize call's request object. - * Object is stored as JWT string in Session DataStore Cache. - * - * Works in-coordination with Push Authorization endpoint. - * - * To differentiate 'request' and 'request_uri' auth calls, an internal claim is added to the request object. - */ -public class DefaultOBRequestUriRequestObjectBuilder implements RequestObjectBuilder { - - private static final Log log = LogFactory.getLog(DefaultOBRequestUriRequestObjectBuilder.class); - private static final String PAR_INITIATED_REQ_OBJ = "par_initiated_request_object"; - - @Override - public RequestObject buildRequestObject(String urn, OAuth2Parameters oAuth2Parameters) - throws RequestObjectException { - - String[] sessionKey = urn.split(":"); - - SessionDataCacheKey sessionDataCacheKey = new SessionDataCacheKey(sessionKey[(sessionKey.length - 1)]); - SessionDataCacheEntry sessionDataCacheEntry = SessionDataCache.getInstance() - .getValueFromCache(sessionDataCacheKey); - RequestObject requestObject = new RequestObject(); - - if (sessionDataCacheEntry == null) { - throw new RequestObjectException(OAuth2ErrorCodes.INVALID_REQUEST, "Invalid request URI"); - } - - // Making a copy of requestObjectParam to prevent editing initial reference - String requestObjectParamValue = sessionDataCacheEntry.getoAuth2Parameters().getEssentialClaims(); - - // validate expiry - String[] jwtWithExpiry = requestObjectParamValue.split(":"); - if (Instant.now().getEpochSecond() > Long.parseLong(jwtWithExpiry[1])) { - throw new RequestObjectException(OAuth2ErrorCodes.INVALID_REQUEST, "Expired request URI"); - } - - requestObjectParamValue = jwtWithExpiry[0]; - - if (isEncrypted(requestObjectParamValue)) { - requestObjectParamValue = decrypt(requestObjectParamValue, oAuth2Parameters); - if (StringUtils.isEmpty(requestObjectParamValue)) { - return requestObject; - } - } - - setRequestObjectValues(requestObjectParamValue, requestObject); - return requestObject; - - } - - @Override - public String decrypt(String requestObject, OAuth2Parameters oAuth2Parameters) throws RequestObjectException { - EncryptedJWT encryptedJWT; - try { - encryptedJWT = EncryptedJWT.parse(requestObject); - RSAPrivateKey rsaPrivateKey = getRSAPrivateKey(oAuth2Parameters); - RSADecrypter decrypter = new RSADecrypter(rsaPrivateKey); - encryptedJWT.decrypt(decrypter); - - JWEObject jweObject = JWEObject.parse(requestObject); - jweObject.decrypt(decrypter); - - if (jweObject.getPayload() != null && jweObject.getPayload().toString() - .split(JWT_PART_DELIMITER).length == NUMBER_OF_PARTS_IN_JWS) { - return jweObject.getPayload().toString(); - } else { - return new PlainJWT(encryptedJWT.getJWTClaimsSet()).serialize(); - } - - } catch (JOSEException | IdentityOAuth2Exception | ParseException e) { - String errorMessage = "Failed to decrypt Request Object"; - log.error(errorMessage + " from " + requestObject, e); - throw new RequestObjectException(RequestObjectException.ERROR_CODE_INVALID_REQUEST, errorMessage); - } - } - - /** - * Retrieve RSA private key. - * - * @param oAuth2Parameters oAuth2Parameters - * @return RSA private key - */ - private RSAPrivateKey getRSAPrivateKey(OAuth2Parameters oAuth2Parameters) throws IdentityOAuth2Exception { - - String tenantDomain = getTenantDomainForDecryption(oAuth2Parameters); - int tenantId = OAuth2Util.getTenantId(tenantDomain); - Key key = OAuth2Util.getPrivateKey(tenantDomain, tenantId); - return (RSAPrivateKey) key; - } - - /** - * Get tenant domain from oAuth2Parameters. - * - * @param oAuth2Parameters oAuth2Parameters - * @return Tenant domain - */ - private String getTenantDomainForDecryption(OAuth2Parameters oAuth2Parameters) { - - if (StringUtils.isNotEmpty(oAuth2Parameters.getTenantDomain())) { - return oAuth2Parameters.getTenantDomain(); - } - return MultitenantConstants.SUPER_TENANT_NAME; - } - - /** - * Check whether given request object is encrypted. - * - * @param requestObject request object string - * @return true if its encrypted - */ - private boolean isEncrypted(String requestObject) { - - return requestObject.split(JWT_PART_DELIMITER).length == NUMBER_OF_PARTS_IN_JWE; - } - - /** - * Set retrieved claims to the request object instance. - * - * @param requestObjectString request object string - * @param requestObjectInstance request object instance - * @return - */ - private void setRequestObjectValues(String requestObjectString, RequestObject requestObjectInstance) throws - RequestObjectException { - - try { - JOSEObject jwt = JOSEObject.parse(requestObjectString); - if (jwt.getHeader().getAlgorithm() == null || jwt.getHeader().getAlgorithm().equals(JWSAlgorithm.NONE)) { - requestObjectInstance.setPlainJWT(PlainJWT.parse(requestObjectString)); - } else { - requestObjectInstance.setSignedJWT(SignedJWT.parse(requestObjectString)); - } - JSONObject claimSet = requestObjectInstance.getClaimsSet().toJSONObject(); - claimSet.put(PAR_INITIATED_REQ_OBJ, "true"); - requestObjectInstance.setClaimSet(JWTClaimsSet.parse(claimSet)); - } catch (ParseException e) { - String errorMessage = "No Valid JWT is found for the Request Object."; - log.error(errorMessage, e); - throw new RequestObjectException(OAuth2ErrorCodes.INVALID_REQUEST, errorMessage); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/cache/IdentityCache.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/cache/IdentityCache.java deleted file mode 100644 index 7423ec2f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/cache/IdentityCache.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCache; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; - -/** - * Cache definition to store objects in open banking iam component implementations. - */ -public class IdentityCache extends OpenBankingBaseCache { - - private static final String cacheName = "OPEN_BANKING_IDENTITY_CACHE"; - - private Integer accessExpiryMinutes; - private Integer modifiedExpiryMinutes; - - /** - * Initialize with unique cache name. - */ - public IdentityCache() { - - super(cacheName); - this.accessExpiryMinutes = setAccessExpiryMinutes(); - this.modifiedExpiryMinutes = setModifiedExpiryMinutes(); - } - - @Override - public int getCacheAccessExpiryMinutes() { - return accessExpiryMinutes; - } - - @Override - public int getCacheModifiedExpiryMinutes() { - return modifiedExpiryMinutes; - } - - public int setAccessExpiryMinutes() { - - return IdentityExtensionsDataHolder.getInstance().getIdentityCacheAccessExpiry(); - } - - public int setModifiedExpiryMinutes() { - - return IdentityExtensionsDataHolder.getInstance().getIdentityCacheModifiedExpiry(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/cache/IdentityCacheKey.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/cache/IdentityCacheKey.java deleted file mode 100644 index 090cfefb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/cache/IdentityCacheKey.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.cache; - -import com.wso2.openbanking.accelerator.common.caching.OpenBankingBaseCacheKey; - -import java.io.Serializable; -import java.util.Objects; - -/** - * Cache Key for Open Banking Identity cache. - */ -public class IdentityCacheKey extends OpenBankingBaseCacheKey implements Serializable { - - private static final long serialVersionUID = 143057970021542120L; - public String identityCacheKey; - - public IdentityCacheKey(String identityCacheKey) { - - this.identityCacheKey = identityCacheKey; - } - - public static IdentityCacheKey of(String identityCacheKey) { - - return new IdentityCacheKey(identityCacheKey); - } - - @Override - public boolean equals(Object o) { - - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - IdentityCacheKey that = (IdentityCacheKey) o; - return Objects.equals(identityCacheKey, that.identityCacheKey); - } - - @Override - public int hashCode() { - - return Objects.hash(identityCacheKey); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBClaimProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBClaimProvider.java deleted file mode 100644 index b802f075..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBClaimProvider.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.claims; - -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.openidconnect.ClaimProvider; - -import java.util.Map; - -/** - * OB specific claim provider. - */ -public class OBClaimProvider implements ClaimProvider { - - private static ClaimProvider claimProvider; - - @Override - public Map getAdditionalClaims(OAuthAuthzReqMessageContext authAuthzReqMessageContext, - OAuth2AuthorizeRespDTO authorizeRespDTO) - throws IdentityOAuth2Exception { - - return getClaimProvider().getAdditionalClaims(authAuthzReqMessageContext, authorizeRespDTO); - - } - - @Override - public Map getAdditionalClaims(OAuthTokenReqMessageContext tokenReqMessageContext, - OAuth2AccessTokenRespDTO tokenRespDTO) - throws IdentityOAuth2Exception { - - return getClaimProvider().getAdditionalClaims(tokenReqMessageContext, tokenRespDTO); - } - - public static void setClaimProvider(ClaimProvider claimProvider) { - - OBClaimProvider.claimProvider = claimProvider; - } - - public static ClaimProvider getClaimProvider() { - - return claimProvider; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultClaimProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultClaimProvider.java deleted file mode 100644 index 187a10d9..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultClaimProvider.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.claims; - -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.identity.oauth.common.OAuthConstants; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; - -import java.text.ParseException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.wso2.carbon.identity.openidconnect.model.Constants.JWT_PART_DELIMITER; -import static org.wso2.carbon.identity.openidconnect.model.Constants.NUMBER_OF_PARTS_IN_JWE; - -/** - * Default OB specific claim provider implementation. - */ -public class OBDefaultClaimProvider extends OBClaimProvider { - - private static final Log log = LogFactory.getLog(OBDefaultClaimProvider.class); - - @Override - public Map getAdditionalClaims(OAuthAuthzReqMessageContext authAuthzReqMessageContext, - OAuth2AuthorizeRespDTO authorizeRespDTO) - throws IdentityOAuth2Exception { - - Map claims = new HashMap<>(); - String[] cachedRequests = null; - final String sessionDataKey = authAuthzReqMessageContext.getAuthorizationReqDTO().getSessionDataKey(); - if (StringUtils.isNotBlank(sessionDataKey)) { - cachedRequests = SessionDataCache.getInstance() - .getValueFromCache(new SessionDataCacheKey(sessionDataKey)).getParamMap().get("request"); - } - if (cachedRequests != null && !(cachedRequests[0].split(JWT_PART_DELIMITER).length == NUMBER_OF_PARTS_IN_JWE)) { - JSONObject requestBody = getRequestBodyFromCache(cachedRequests); - - /* State is an optional parameter, so the authorization server must successfully authenticate and - * must NOT return state nor s_hash. (FAPI1-ADV-5.2.2.1-5) - */ - final String state = requestBody.getAsString(OAuthConstants.OAuth20Params.STATE); - if (StringUtils.isNotEmpty(state)) { - claims.put(IdentityCommonConstants.S_HASH, IdentityCommonUtil.getHashValue(state, null)); - } else { - // state is empty, removing state from cache too - removeStateFromCache(sessionDataKey); - } - } - final String responseType = authAuthzReqMessageContext.getAuthorizationReqDTO().getResponseType(); - avoidSettingATHash(responseType, authorizeRespDTO, claims); - - return claims; - - } - - @Override - public Map getAdditionalClaims(OAuthTokenReqMessageContext tokenReqMessageContext, - OAuth2AccessTokenRespDTO tokenRespDTO) - throws IdentityOAuth2Exception { - - return new HashMap<>(); - } - - /** - * If response_type value is not 'code id_token token', avoid setting at_hash claim to the authorization - * endpoint id_token as it is OPTIONAL (OIDCC-3.3.2.11). - * - * @param responseType requested auth response_type - * @param authorizeRespDTO authorizeRespDTO - * @param claims returning claims map - */ - private void avoidSettingATHash(String responseType, OAuth2AuthorizeRespDTO authorizeRespDTO, - Map claims) { - - if (StringUtils.isNotBlank(responseType)) { - List responseTypes = Arrays.asList(responseType.trim().split("\\s+")); - if (!(responseTypes.contains(IdentityCommonConstants.CODE) - && responseTypes.contains(OAuthConstants.ID_TOKEN) - && responseTypes.contains(OAuthConstants.TOKEN))) { - if (StringUtils.isNotBlank(authorizeRespDTO.getAccessToken())) { - authorizeRespDTO.setAccessToken(null); - } - claims.put(OAuthConstants.OIDCClaims.AT_HASH, null); - } - } - } - - private JSONObject getRequestBodyFromCache(String[] cachedRequests) { - - try { - if (cachedRequests.length > 0) { - return JWTUtils.decodeRequestJWT(cachedRequests[0], "body"); - } - } catch (ParseException e) { - log.error("Exception occurred when decoding request. Caused by, ", e); - } - - return new JSONObject(); - } - - /** - * If request object state value is empty, ignore the session cache state value, as FAPI-RW says only parameters - * inside the request object should be used (FAPI1-ADV-5.2.2-10). - * - * @param sessionDataKey key used to store session cache - */ - private void removeStateFromCache(String sessionDataKey) { - - final SessionDataCacheKey sessionDataCacheKey = new SessionDataCacheKey(sessionDataKey); - SessionDataCacheEntry sessionDataCacheEntry = SessionDataCache.getInstance() - .getValueFromCache(sessionDataCacheKey); - - if (sessionDataCacheEntry != null) { - sessionDataCacheEntry.getoAuth2Parameters().setState(null); - sessionDataCacheEntry.getParamMap().put(OAuthConstants.OAuth20Params.STATE, new String[]{}); - - SessionDataCache.getInstance().addToCache(sessionDataCacheKey, sessionDataCacheEntry); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultOIDCClaimsCallbackHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultOIDCClaimsCallbackHandler.java deleted file mode 100644 index 52c8bdbb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultOIDCClaimsCallbackHandler.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.claims; - -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.X509CertUtils; -import com.nimbusds.jwt.JWTClaimsSet; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.model.HttpRequestHeader; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.openidconnect.DefaultOIDCClaimsCallbackHandler; - -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * This call back handler adds ob specific additional claims to self contained JWT access token. - */ -public class OBDefaultOIDCClaimsCallbackHandler extends DefaultOIDCClaimsCallbackHandler { - - private static Log log = LogFactory.getLog(OBDefaultOIDCClaimsCallbackHandler.class); - Map identityConfigurations = IdentityExtensionsDataHolder.getInstance().getConfigurationMap(); - - - @Override - public JWTClaimsSet handleCustomClaims(JWTClaimsSet.Builder jwtClaimsSetBuilder, OAuthTokenReqMessageContext - tokenReqMessageContext) throws IdentityOAuth2Exception { - - /* accessToken property check is done to omit the following claims getting bound to id_token - The access token property is added to the ID token message context before this method is invoked. */ - try { - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(tokenReqMessageContext.getOauth2AccessTokenReqDTO() - .getClientId()) && (tokenReqMessageContext.getProperty("accessToken") == null)) { - - Map userClaimsInOIDCDialect = new HashMap<>(); - JWTClaimsSet jwtClaimsSet = getJwtClaimsFromSuperClass(jwtClaimsSetBuilder, tokenReqMessageContext); - if (jwtClaimsSet != null) { - for (Map.Entry claimEntry : jwtClaimsSet.getClaims().entrySet()) { - userClaimsInOIDCDialect.put(claimEntry.getKey(), claimEntry.getValue()); - } - } - addCnfClaimToOIDCDialect(tokenReqMessageContext, userClaimsInOIDCDialect); - addConsentIDClaimToOIDCDialect(tokenReqMessageContext, userClaimsInOIDCDialect); - updateSubClaim(tokenReqMessageContext, userClaimsInOIDCDialect); - - for (Map.Entry claimEntry : userClaimsInOIDCDialect.entrySet()) { - if (IdentityCommonConstants.SCOPE.equals(claimEntry.getKey())) { - String[] nonInternalScopes = IdentityCommonUtil - .removeInternalScopes(claimEntry.getValue().toString() - .split(IdentityCommonConstants.SPACE_SEPARATOR)); - jwtClaimsSetBuilder.claim(IdentityCommonConstants.SCOPE, StringUtils.join(nonInternalScopes, - IdentityCommonConstants.SPACE_SEPARATOR)); - } else { - jwtClaimsSetBuilder.claim(claimEntry.getKey(), claimEntry.getValue()); - } - } - return jwtClaimsSetBuilder.build(); - } - } catch (OpenBankingException e) { - throw new IdentityOAuth2Exception(e.getMessage(), e); - } - return super.handleCustomClaims(jwtClaimsSetBuilder, tokenReqMessageContext); - } - - @Generated(message = "Excluding from code coverage since it makes is used to return claims from the super class") - public JWTClaimsSet getJwtClaimsFromSuperClass(JWTClaimsSet.Builder jwtClaimsSetBuilder, - OAuthTokenReqMessageContext tokenReqMessageContext) - throws IdentityOAuth2Exception { - - return super.handleCustomClaims(jwtClaimsSetBuilder, tokenReqMessageContext); - } - - private void addCnfClaimToOIDCDialect(OAuthTokenReqMessageContext tokenReqMessageContext, - Map userClaimsInOIDCDialect) { - Base64URL certThumbprint; - X509Certificate certificate; - String headerName = IdentityCommonUtil.getMTLSAuthHeader(); - - HttpRequestHeader[] requestHeaders = tokenReqMessageContext.getOauth2AccessTokenReqDTO() - .getHttpRequestHeaders(); - Optional certHeader = - Arrays.stream(requestHeaders).filter(h -> headerName.equals(h.getName())).findFirst(); - if (certHeader.isPresent()) { - try { - certificate = CertificateUtils.parseCertificate(certHeader.get().getValue()[0]); - certThumbprint = X509CertUtils.computeSHA256Thumbprint(certificate); - userClaimsInOIDCDialect.put("cnf", Collections.singletonMap("x5t#S256", certThumbprint)); - } catch (OpenBankingException e) { - log.error("Error while extracting the certificate", e); - } - } - } - - private void addConsentIDClaimToOIDCDialect(OAuthTokenReqMessageContext tokenReqMessageContext, - Map userClaimsInOIDCDialect) { - - String consentIdClaimName = - identityConfigurations.get(IdentityCommonConstants.CONSENT_ID_CLAIM_NAME).toString(); - String consentID = Arrays.stream(tokenReqMessageContext.getScope()) - .filter(scope -> scope.contains(IdentityCommonConstants.OB_PREFIX)).findFirst().orElse(null); - if (StringUtils.isEmpty(consentID)) { - consentID = Arrays.stream(tokenReqMessageContext.getScope()) - .filter(scope -> scope.contains(consentIdClaimName)) - .findFirst().orElse(StringUtils.EMPTY) - .replaceAll(consentIdClaimName, StringUtils.EMPTY); - } else { - consentID = consentID.replace(IdentityCommonConstants.OB_PREFIX, StringUtils.EMPTY); - } - - if (StringUtils.isNotEmpty(consentID)) { - userClaimsInOIDCDialect.put(consentIdClaimName, consentID); - } - } - - /** - * Update the subject claim of the JWT claims set if any of the following configurations are true - * 1. Remove tenant domain from subject (open_banking.identity.token.remove_tenant_domain_from_subject) - * 2. Remove user store domain from subject (open_banking.identity.token.remove_user_store_domain_from_subject) - * @param tokenReqMessageContext token request message context - * @param userClaimsInOIDCDialect user claims in OIDC dialect as a map - */ - private void updateSubClaim(OAuthTokenReqMessageContext tokenReqMessageContext, - Map userClaimsInOIDCDialect) { - - Object removeTenantDomainConfig = - identityConfigurations.get(IdentityCommonConstants.REMOVE_TENANT_DOMAIN_FROM_SUBJECT); - Boolean removeTenantDomain = removeTenantDomainConfig != null - && Boolean.parseBoolean(removeTenantDomainConfig.toString()); - - Object removeUserStoreDomainConfig = - identityConfigurations.get(IdentityCommonConstants.REMOVE_USER_STORE_DOMAIN_FROM_SUBJECT); - Boolean removeUserStoreDomain = removeUserStoreDomainConfig != null - && Boolean.parseBoolean(removeUserStoreDomainConfig.toString()); - - if (removeTenantDomain || removeUserStoreDomain) { - String subClaim = tokenReqMessageContext.getAuthorizedUser() - .getUsernameAsSubjectIdentifier(!removeUserStoreDomain, !removeTenantDomain); - userClaimsInOIDCDialect.put("sub", subClaim); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/RoleClaimProviderImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/RoleClaimProviderImpl.java deleted file mode 100644 index a0612685..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/claims/RoleClaimProviderImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.claims; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.base.IdentityRuntimeException; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.openidconnect.ClaimProvider; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * RoleClaimProviderImpl. - *

- * Adding Customer Care Officer user role to cater sso flow in consent mgt react app - */ -public class RoleClaimProviderImpl implements ClaimProvider { - private static final Log LOG = LogFactory.getLog(RoleClaimProviderImpl.class); - private static final String USER_ROLE = "user_role"; - private static final String OPENID_SCOPE = "openid"; - private static final String CUSTOMER_CARE_OFFICER = "customerCareOfficer"; - private static final String CUSTOMER_CARE_OFFICER_ROLE = "Internal/CustomerCareOfficerRole"; - private static final String CUSTOMER_CARE_OFFICER_SCOPE = "consents:read_all"; - - @Generated(message = "Do not contain logics") - @Override - public Map getAdditionalClaims(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext, - OAuth2AuthorizeRespDTO oAuth2AuthorizeRespDTO) - throws IdentityOAuth2Exception { - return Collections.emptyMap(); - } - - /** - * Method to add Role based claims for Token response to cater sso flow in consent mgt react app. - * - * @param oAuthTokenReqMessageContext token Request message context - * @param oAuth2AccessTokenRespDTO token Response DTO - * @return Map of additional claims - * @throws IdentityOAuth2Exception when failed to obtain claims - */ - @Override - public Map getAdditionalClaims(OAuthTokenReqMessageContext oAuthTokenReqMessageContext, - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO) - throws IdentityOAuth2Exception { - Map claims = new HashMap<>(); - - List scopes = Arrays.asList(oAuthTokenReqMessageContext.getScope()); - if (scopes.contains(CUSTOMER_CARE_OFFICER_SCOPE) && scopes.contains(OPENID_SCOPE)) { - final String userId = oAuthTokenReqMessageContext.getAuthorizedUser().getUserName(); - - try { - int tenantId = IdentityTenantUtil.getTenantIdOfUser(userId); - RealmService realmService = IdentityExtensionsDataHolder.getInstance().getRealmService(); - UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); - - String[] roles = userStoreManager.getRoleListOfUser(userId); - if (ArrayUtils.contains(roles, CUSTOMER_CARE_OFFICER_ROLE)) { - claims.put(USER_ROLE, CUSTOMER_CARE_OFFICER); - } - } catch (IdentityRuntimeException e) { - LOG.error("Error in retrieving user tenant name for user: " + userId + ". Caused by,", e); - } catch (UserStoreException e) { - LOG.error("Error in retrieving user role. Caused by,", e); - } - - } - return claims; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/clientauth/OBMutualTLSClientAuthenticator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/clientauth/OBMutualTLSClientAuthenticator.java deleted file mode 100644 index 87c6f5ed..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/clientauth/OBMutualTLSClientAuthenticator.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.clientauth; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnException; -import org.wso2.carbon.identity.oauth2.token.handler.clientauth.mutualtls.MutualTLSClientAuthenticator; -import org.wso2.carbon.identity.oauth2.token.handler.clientauth.mutualtls.utils.MutualTLSUtil; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -/** - * OpenBanking Mutual TLS Client Authenticator. - */ -public class OBMutualTLSClientAuthenticator extends MutualTLSClientAuthenticator { - - private static Log log = LogFactory.getLog(OBMutualTLSClientAuthenticator.class); - - @Override - public boolean canAuthenticate(HttpServletRequest request, Map bodyParams, - OAuthClientAuthnContext oAuthClientAuthnContext) { - - try { - String clientId = oAuthClientAuthnContext.getClientId(); - if (StringUtils.isEmpty(clientId)) { - clientId = (super.getClientId(request, bodyParams, oAuthClientAuthnContext) == null - && request.getParameter("client_id") != null) ? request.getParameter("client_id") : - super.getClientId(request, bodyParams, oAuthClientAuthnContext); - } - if ((IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId))) { - if (new IdentityCommonHelper().isMTLSAuthentication(request)) { - log.debug("Client ID and a valid certificate was found in the request attribute hence returning " + - "true."); - return true; - } else { - log.debug("Mutual TLS authenticator cannot handle this request. Client id is not available in " + - "body params or valid certificate not found in request attributes."); - return false; - } - } else { - return super.canAuthenticate(request, bodyParams, oAuthClientAuthnContext); - } - } catch (OpenBankingException | OAuthClientAuthnException e) { - if (log.isDebugEnabled()) { - log.debug("Mutual TLS authenticator cannot handle this request. " + e.getMessage()); - } - return false; - } - } - - @Override - public URL getJWKSEndpointOfSP(ServiceProvider serviceProvider, String clientID) throws OAuthClientAuthnException { - - String jwksUri = MutualTLSUtil.getPropertyValue(serviceProvider, IdentityCommonUtil.getJWKURITransportCert()); - if (StringUtils.isEmpty(jwksUri)) { - throw new OAuthClientAuthnException("jwks endpoint not configured for the service provider for client ID: " - + clientID, "server_error"); - } else { - try { - URL url = new URL(jwksUri); - if (log.isDebugEnabled()) { - log.debug("Configured JWKS URI found: " + jwksUri); - } - - return url; - } catch (MalformedURLException var6) { - throw new OAuthClientAuthnException("URL might be malformed " + clientID, "server_error", var6); - } - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/IdentityServiceExporter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/IdentityServiceExporter.java deleted file mode 100644 index fb03dfba..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/IdentityServiceExporter.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.common; - -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService; - -/** - * Exporter service to facilitate access to identity services in data holder from other modules. - */ -public class IdentityServiceExporter { - - private static OAuthClientAuthnService oAuthClientAuthnService; - - public static OAuthClientAuthnService getOAuthClientAuthnService() { - return oAuthClientAuthnService; - } - - public static void setOAuthClientAuthnService(OAuthClientAuthnService oAuthClientAuthnService) { - IdentityServiceExporter.oAuthClientAuthnService = oAuthClientAuthnService; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/AttributeChecks.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/AttributeChecks.java deleted file mode 100644 index 4fd54abc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/AttributeChecks.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Groups the validations for attributes - */ -public interface AttributeChecks { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/MandatoryChecks.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/MandatoryChecks.java deleted file mode 100644 index 6f2a082e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/MandatoryChecks.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Grouping the mandatory check constraints - */ -public interface MandatoryChecks { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/SignatureCheck.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/SignatureCheck.java deleted file mode 100644 index 25d302c6..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/SignatureCheck.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Groups the validation for signature - */ -public interface SignatureCheck { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/ValidityChecks.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/ValidityChecks.java deleted file mode 100644 index 477db36a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/common/annotations/validationgroups/ValidityChecks.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Groups the validations for the validity of a JWT - */ -public interface ValidityChecks { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/exception/DCRValidationException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/exception/DCRValidationException.java deleted file mode 100644 index dc8c3337..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/exception/DCRValidationException.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * DCR validation exception. - */ -public class DCRValidationException extends OpenBankingException { - - private String errorDescription; - private String errorCode; - - public String getErrorDescription() { - - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - - this.errorDescription = errorDescription; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - - public DCRValidationException(String errorCode, String error, String errorDescription, Throwable e) { - - super(error, e); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - } - - public DCRValidationException(String errorCode, String errorDescription) { - - super(errorDescription); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationError.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationError.java deleted file mode 100644 index 698f7239..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationError.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.model; - -/** - * Model class for dcr error response. - */ -public class RegistrationError { - - private String errorMessage; - private String errorCode; - - public String getErrorMessage() { - - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - - this.errorMessage = errorMessage; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationRequest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationRequest.java deleted file mode 100644 index 44663a5c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationRequest.java +++ /dev/null @@ -1,366 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.model; - -import com.google.gson.annotations.SerializedName; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.AttributeChecks; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.MandatoryChecks; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.SignatureCheck; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateAlgorithm; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateIssuer; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateRequiredParams; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateSignature; - -import java.util.List; -import java.util.Map; - -/** - * Model class for dcr registration request. - */ -@ValidateRequiredParams(message = "Required parameters cannot be null or empty:" + DCRCommonConstants.INVALID_META_DATA, - groups = MandatoryChecks.class) -@ValidateIssuer(issuerProperty = "issuer", ssa = "softwareStatement", - message = "Invalid issuer:" + DCRCommonConstants.INVALID_META_DATA, groups = AttributeChecks.class) -@ValidateSignature(ssaBody = "softwareStatementBody", ssa = "softwareStatement", message = "Invalid signature for SSA:" - + DCRCommonConstants.INVALID_SSA, groups = SignatureCheck.class) -@ValidateAlgorithm(idTokenAlg = "idTokenSignedResponseAlg", reqObjAlg = "requestObjectSigningAlg", - tokenAuthAlg = "tokenEndPointAuthSigningAlg", - message = "Invalid signing algorithm sent:" + DCRCommonConstants.INVALID_META_DATA, - groups = AttributeChecks.class) -public class RegistrationRequest { - - @SerializedName("aud") - private String aud; - - @SerializedName("iss") - private String issuer; - - @SerializedName("token_endpoint_auth_method") - private String tokenEndPointAuthMethod; - - @SerializedName("jwks_uri") - private String jwksURI; - - @SerializedName("grant_types") - private List grantTypes; - - @SerializedName("software_statement") - private String softwareStatement; - - @SerializedName("id_token_signed_response_alg") - private String idTokenSignedResponseAlg; - - @SerializedName("redirect_uris") - private List redirectUris; - - @SerializedName("token_endpoint_auth_signing_alg") - private String tokenEndPointAuthSigningAlg; - - @SerializedName("response_types") - private List responseTypes; - - @SerializedName("software_id") - private String softwareId; - - @SerializedName("scope") - private String scope; - - @SerializedName("application_type") - private String applicationType; - - @SerializedName("jti") - private String jti; - - @SerializedName("id_token_encrypted_response_alg") - private String idTokenEncryptionResponseAlg; - - @SerializedName("id_token_encrypted_response_enc") - private String idTokenEncryptionResponseEnc; - - @SerializedName("request_object_signing_alg") - private String requestObjectSigningAlg; - - @SerializedName("tls_client_auth_subject_dn") - private String tlsClientAuthSubjectDn; - - @SerializedName("backchannel_token_delivery_mode") - private String backchannelTokenDeliveryMode; - - @SerializedName("backchannel_authentication_request_signing_alg") - private String backchannelAuthenticationRequestSigningAlg; - - @SerializedName("backchannel_client_notification_endpoint") - private String backchannelClientNotificationEndpoint; - - @SerializedName("backchannel_user_code_parameter_supported") - private boolean backchannelUserCodeParameterSupported; - - private SoftwareStatementBody softwareStatementBody; - - private Map requestParameters; - - private Map ssaParameters; - - public Map getSsaParameters() { - - return ssaParameters; - } - - public void setSsaParameters(Map ssaParameters) { - - this.ssaParameters = ssaParameters; - } - - public Map getRequestParameters() { - - return requestParameters; - } - - public void setRequestParameters(Map requestParameters) { - - this.requestParameters = requestParameters; - } - - public SoftwareStatementBody getSoftwareStatementBody() { - - return softwareStatementBody; - } - - public void setSoftwareStatementBody(SoftwareStatementBody softwareStatementBody) { - - this.softwareStatementBody = softwareStatementBody; - } - - public boolean getBackchannelUserCodeParameterSupported() { - - return backchannelUserCodeParameterSupported; - } - - public void setBackchannelUserCodeParameterSupported(boolean backchannelUserCodeParameterSupported) { - - this.backchannelUserCodeParameterSupported = backchannelUserCodeParameterSupported; - } - - public String getBackchannelClientNotificationEndpoint() { - - return backchannelClientNotificationEndpoint; - } - - public void setBackchannelClientNotificationEndpoint(String backchannelClientNotificationEndpoint) { - - this.backchannelClientNotificationEndpoint = backchannelClientNotificationEndpoint; - } - - public String getBackchannelAuthenticationRequestSigningAlg() { - - return backchannelAuthenticationRequestSigningAlg; - } - - public void setBackchannelAuthenticationRequestSigningAlg(String backchannelAuthenticationRequestSigningAlg) { - - this.backchannelAuthenticationRequestSigningAlg = backchannelAuthenticationRequestSigningAlg; - } - - public String getBackchannelTokenDeliveryMode() { - - return backchannelTokenDeliveryMode; - } - - public void setBackchannelTokenDeliveryMode(String backchannelTokenDeliveryMode) { - - this.backchannelTokenDeliveryMode = backchannelTokenDeliveryMode; - } - - public String getTlsClientAuthSubjectDn() { - - return tlsClientAuthSubjectDn; - } - - public void setTlsClientAuthSubjectDn(String tlsClientAuthSubjectDn) { - - this.tlsClientAuthSubjectDn = tlsClientAuthSubjectDn; - } - - public String getRequestObjectSigningAlg() { - - return requestObjectSigningAlg; - } - - public void setRequestObjectSigningAlg(String requestObjectSigningAlg) { - - this.requestObjectSigningAlg = requestObjectSigningAlg; - } - - public String getIdTokenEncryptionResponseEnc() { - - return idTokenEncryptionResponseEnc; - } - - public void setIdTokenEncryptionResponseEnc(String idTokenEncryptionResponseEnc) { - - this.idTokenEncryptionResponseEnc = idTokenEncryptionResponseEnc; - } - - public String getIdTokenEncryptionResponseAlg() { - - return idTokenEncryptionResponseAlg; - } - - public void setIdTokenEncryptionResponseAlg(String idTokenEncryptionResponseAlg) { - - this.idTokenEncryptionResponseAlg = idTokenEncryptionResponseAlg; - } - - public String getApplicationType() { - - return applicationType; - } - - public void setApplicationType(String applicationType) { - - this.applicationType = applicationType; - } - - public String getScope() { - - return scope; - } - - public void setScope(String scope) { - - this.scope = scope; - } - - public String getSoftwareId() { - - return softwareId; - } - - public void setSoftwareId(String softwareId) { - - this.softwareId = softwareId; - } - - public List getResponseTypes() { - - return responseTypes; - } - - public void setResponseTypes(List responseTypes) { - - this.responseTypes = responseTypes; - } - - public String getTokenEndPointAuthSigningAlg() { - - return tokenEndPointAuthSigningAlg; - } - - public void setTokenEndPointAuthSigningAlg(String tokenEndPointAuthSigningAlg) { - - this.tokenEndPointAuthSigningAlg = tokenEndPointAuthSigningAlg; - } - - public List getCallbackUris() { - - return redirectUris; - } - - public void setCallbackUris(List redirectUris) { - - this.redirectUris = redirectUris; - } - - public String getIssuer() { - - return issuer; - } - - public void setIssuer(String issuer) { - - this.issuer = issuer; - } - - public String getTokenEndPointAuthentication() { - - return tokenEndPointAuthMethod; - } - - public void setTokenEndPointAuthentication(String tokenEndPointAuthMethod) { - - this.tokenEndPointAuthMethod = tokenEndPointAuthMethod; - } - - public List getGrantTypes() { - - return grantTypes; - } - - public void setGrantTypes(List grantTypes) { - - this.grantTypes = grantTypes; - } - - public String getSoftwareStatement() { - - return softwareStatement; - } - - public void setSoftwareStatement(String softwareStatement) { - - this.softwareStatement = softwareStatement; - } - - public String getIdTokenSignedResponseAlg() { - - return idTokenSignedResponseAlg; - } - - public void setIdTokenSignedResponseAlg(String idTokenSignedResponseAlg) { - - this.idTokenSignedResponseAlg = idTokenSignedResponseAlg; - } - - public String getAudience() { - - return aud; - } - public void setAudience(String aud) { - - this.aud = aud; - } - - public String getJti() { - - return jti; - } - - public void setJti(String jti) { - - this.jti = jti; - } - - public String getJwksURI() { - return jwksURI; - } - - public void setJwksURI(String jwksURI) { - this.jwksURI = jwksURI; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationResponse.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationResponse.java deleted file mode 100644 index 8078f34a..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/RegistrationResponse.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.model; - -import com.google.gson.annotations.SerializedName; - -import java.util.ArrayList; -import java.util.List; - -/** - * Model class for dcr response containing common attributes. - */ -public class RegistrationResponse { - - public String getToken() { - return this.token; - } - - public void setToken(String token) { - this.token = token; - } - - @SerializedName("registration_access_token") - protected String token = null; - - @SerializedName("client_id") - protected String clientId = null; - - @SerializedName("client_id_issued_at") - protected String clientIdIssuedAt = null; - - @SerializedName("redirect_uris") - protected List redirectUris = new ArrayList<>(); - - @SerializedName("grant_types") - protected List grantTypes = new ArrayList<>(); - - @SerializedName("response_types") - protected List responseTypes = new ArrayList<>(); - - @SerializedName("application_type") - protected String applicationType = null; - - @SerializedName("id_token_signed_response_alg") - protected String idTokenSignedResponseAlg = null; - - @SerializedName("request_object_signing_alg") - protected String requestObjectSigningAlg = null; - - @SerializedName("scope") - protected String scope = null; - - @SerializedName("software_id") - protected String softwareId = null; - - @SerializedName("jwks_uri") - private String jwksURI; - - @SerializedName("token_endpoint_auth_method") - protected String tokenEndpointAuthMethod = null; - - @SerializedName("registration_client_uri") - protected String registrationClientURI = null; - - @SerializedName("software_statement") - protected String softwareStatement = null; - - public String getSoftwareStatement() { - - return softwareStatement; - } - - public void setSoftwareStatement(String softwareStatement) { - - this.softwareStatement = softwareStatement; - } - - public String getTokenEndpointAuthMethod() { - - return tokenEndpointAuthMethod; - } - - public void setTokenEndpointAuthMethod(String tokenEndpointAuthMethod) { - - this.tokenEndpointAuthMethod = tokenEndpointAuthMethod; - } - - public List getResponseTypes() { - - return responseTypes; - } - - public void setResponseTypes(List responseTypes) { - - this.responseTypes = responseTypes; - } - - - public String getClientIdIssuedAt() { - - return clientIdIssuedAt; - } - - public void setClientIdIssuedAt(String clientIdIssuedAt) { - - this.clientIdIssuedAt = clientIdIssuedAt; - } - - public String getClientId() { - - return clientId; - } - - public void setClientId(String clientId) { - - this.clientId = clientId; - } - - public List getRedirectUris() { - - return redirectUris; - } - - public void setRedirectUris(List redirectUris) { - - this.redirectUris = redirectUris; - } - - public List getGrantTypes() { - - return grantTypes; - } - - public void setGrantTypes(List grantTypes) { - - this.grantTypes = grantTypes; - } - - public String getApplicationType() { - - return applicationType; - } - - public void setApplicationType(String applicationType) { - - this.applicationType = applicationType; - } - - public String getIdTokenSignedResponseAlg() { - - return idTokenSignedResponseAlg; - } - - public void setIdTokenSignedResponseAlg(String idTokenSignedResponseAlg) { - - this.idTokenSignedResponseAlg = idTokenSignedResponseAlg; - } - - public String getRequestObjectSigningAlg() { - - return requestObjectSigningAlg; - } - - public void setRequestObjectSigningAlg(String requestObjectSigningAlg) { - - this.requestObjectSigningAlg = requestObjectSigningAlg; - } - - public String getScope() { - - return scope; - } - - public void setScope(String scope) { - - this.scope = scope; - } - - public String getSoftwareId() { - - return softwareId; - } - - public void setSoftwareId(String softwareId) { - - this.softwareId = softwareId; - } - - public String getRegistrationClientURI() { - return registrationClientURI; - } - - public void setRegistrationClientURI(String registrationClientURI) { - this.registrationClientURI = registrationClientURI; - } - - public String getJwksURI() { - return jwksURI; - } - - public void setJwksURI(String jwksURI) { - this.jwksURI = jwksURI; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/SoftwareStatementBody.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/SoftwareStatementBody.java deleted file mode 100644 index c11651c8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/model/SoftwareStatementBody.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.model; - -import com.google.gson.annotations.SerializedName; - -import java.util.List; - -/** - * Model class containing common attributes for software statement. - */ -public class SoftwareStatementBody { - - @SerializedName("software_environment") - private String softwareEnvironment; - - @SerializedName("software_id") - private String softwareId; - - @SerializedName("org_id") - private String orgId; - - @SerializedName("org_name") - private String orgName; - - @SerializedName("scope") - private String scopes; - - @SerializedName(value = "software_client_name" , alternate = "client_name") - private String clientName; - - @SerializedName(value = "software_redirect_uris", alternate = "redirect_uris") - private List ssaRedirectURIs; - - @SerializedName(value = "software_jwks_endpoint", alternate = "jwks_uri") - private String jwksURI; - - @SerializedName("iss") - private String ssaIssuer; - - public String getSsaIssuer() { - - return ssaIssuer; - } - - public void setSsaIssuer(String ssaIssuer) { - - this.ssaIssuer = ssaIssuer; - } - - public String getJwksURI() { - - return jwksURI; - } - - public void setJwksURI(String jwksURI) { - - this.jwksURI = jwksURI; - } - - public List getCallbackUris() { - - return ssaRedirectURIs; - } - - public void setCallbackUris(List redirectURIs) { - - this.ssaRedirectURIs = redirectURIs; - } - - public String getClientName() { - - return clientName; - } - - public void setClientName(String clientName) { - - this.clientName = clientName; - } - - public String getScopes() { - - return scopes; - } - - public void setScopes(String scopes) { - - this.scopes = scopes; - } - - public String getSoftwareEnvironment() { - - return softwareEnvironment; - } - - public void setSoftwareEnvironment(String softwareEnvironment) { - - this.softwareEnvironment = softwareEnvironment; - } - - public String getSoftwareId() { - - return softwareId; - } - - public void setSoftwareId(String softwareId) { - - this.softwareId = softwareId; - } - - public String getOrgId() { - - return orgId; - } - - public void setOrgId(String orgId) { - - this.orgId = orgId; - } - - public String getOrgName() { - - return orgName; - } - - public void setOrgName(String orgName) { - - this.orgName = orgName; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/utils/ValidatorUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/utils/ValidatorUtils.java deleted file mode 100644 index ec7b9c92..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/utils/ValidatorUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.utils; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.validator.OpenBankingValidator; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.validation.validationgroups.ValidationOrder; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.model.HttpRequestHeader; - -/** - * Util class for validation logic implementation. - */ -public class ValidatorUtils { - - private static final Log log = LogFactory.getLog(ValidatorUtils.class); - - public static void getValidationViolations(RegistrationRequest registrationRequest) - throws DCRValidationException { - - String error = OpenBankingValidator.getInstance().getFirstViolation(registrationRequest, ValidationOrder.class); - if (error != null) { - String[] errors = error.split(":"); - throw new DCRValidationException(errors[1], errors[0]); - } - - } - - /** - * Create client credentials grant access token with PK JWT for DCR. - * @param clientId client ID - * @param tlsCert transport certificate - * @return String access token - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public static String generateAccessToken(String clientId, String tlsCert) { - OAuth2AccessTokenReqDTO tokenReqDTO = new OAuth2AccessTokenReqDTO(); - OAuthClientAuthnContext oauthClientAuthnContext = new OAuthClientAuthnContext(); - oauthClientAuthnContext.setClientId(clientId); - oauthClientAuthnContext.addAuthenticator(IdentityCommonConstants.PRIVATE_KEY); - oauthClientAuthnContext.setAuthenticated(true); - - tokenReqDTO.setoAuthClientAuthnContext(oauthClientAuthnContext); - tokenReqDTO.setGrantType(IdentityCommonConstants.CLIENT_CREDENTIALS); - tokenReqDTO.setClientId(clientId); - - String[] scopes = new String[2]; - - //add the appropriate scopes - scopes[0] = IdentityCommonUtil.getDCRScope(); - scopes[1] = IdentityCommonConstants.OPENID_SCOPE; - tokenReqDTO.setScope(scopes); - tokenReqDTO.setTenantDomain(IdentityCommonConstants.CARBON_SUPER); - - // set the tls cert as a header to bind the cnf value to the token - HttpRequestHeader[] requestHeaders = new HttpRequestHeader[1]; - requestHeaders[0] = new HttpRequestHeader(IdentityCommonUtil.getMTLSAuthHeader(), tlsCert); - tokenReqDTO.setHttpRequestHeaders(requestHeaders); - - tokenReqDTO.addAuthenticationMethodReference(IdentityCommonConstants.CLIENT_CREDENTIALS); - - OAuth2Service oAuth2Service = new OAuth2Service(); - OAuth2AccessTokenRespDTO tokenRespDTO = oAuth2Service.issueAccessToken(tokenReqDTO); - - return tokenRespDTO.getAccessToken(); - } - - /** - * Get Registration Client URI. - * @return String Registration client URI - */ - public static String getRegistrationClientURI() { - return String.valueOf(IdentityExtensionsDataHolder.getInstance() - .getConfigurationMap().getOrDefault(IdentityCommonConstants.DCR_REGISTRATION_CLIENT_URI, - IdentityCommonConstants.DEFAULT_REGISTRATION_CLIENT_URI)); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/AlgorithmValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/AlgorithmValidator.java deleted file mode 100644 index 61d9a0a3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/AlgorithmValidator.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateAlgorithm; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for validating the allowed algorithms. - */ -public class AlgorithmValidator implements ConstraintValidator { - - private String idTokenSigningAlgPath; - private String requestObjectSigningAlgPath; - private String tokenAuthSignignAlgPath; - private static Log log = LogFactory.getLog(AlgorithmValidator.class); - - @Override - public void initialize(ValidateAlgorithm validateAlgorithm) { - - this.idTokenSigningAlgPath = validateAlgorithm.idTokenAlg(); - this.requestObjectSigningAlgPath = validateAlgorithm.reqObjAlg(); - this.tokenAuthSignignAlgPath = validateAlgorithm.tokenAuthAlg(); - } - - @Override - public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { - - List allowedAlgorithmsList = new ArrayList<>(); - Object allowedAlgorithms = IdentityExtensionsDataHolder.getInstance() - .getConfigurationMap().get(OpenBankingConstants.SIGNATURE_ALGORITHMS); - if (allowedAlgorithms instanceof List) { - allowedAlgorithmsList = (List) allowedAlgorithms; - } else { - allowedAlgorithmsList.add(allowedAlgorithms.toString()); - } - String requestedIdTokenSigningAlg = null; - String requestedRequestObjSignignAlg = null; - String requestedTokenAuthSigningAlg = null; - try { - requestedIdTokenSigningAlg = BeanUtils.getProperty(object, idTokenSigningAlgPath); - requestedRequestObjSignignAlg = BeanUtils.getProperty(object, requestObjectSigningAlgPath); - requestedTokenAuthSigningAlg = BeanUtils.getProperty(object, tokenAuthSignignAlgPath); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - log.error("Error while resolving validation fields", e); - return false; - } - if (StringUtils.isNotEmpty(requestedIdTokenSigningAlg) && - !allowedAlgorithmsList.contains(requestedIdTokenSigningAlg)) { - return false; - } - if (StringUtils.isNotEmpty(requestedRequestObjSignignAlg) && - !allowedAlgorithmsList.contains(requestedRequestObjSignignAlg)) { - return false; - } - if (StringUtils.isNotEmpty(requestedTokenAuthSigningAlg) && - !allowedAlgorithmsList.contains(requestedTokenAuthSigningAlg)) { - return false; - } - return true; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/DCRCommonConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/DCRCommonConstants.java deleted file mode 100644 index 235aac36..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/DCRCommonConstants.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -/** - * Common constants for dcr. - */ -public class DCRCommonConstants { - - public static final String SOFTWARE_ID = "software_id"; - public static final String INVALID_META_DATA = "invalid_client_metadata"; - public static final String INVALID_SSA = "invalid_software_statement"; - - public static final String DCR_VALIDATOR = "DCR.Validator"; - public static final String DCR_JWKS_ENDPOINT_SANDBOX = "DCR.JwksUrlSandbox"; - public static final String DCR_JWKS_ENDPOINT_PRODUCTION = "DCR.JwksUrlProduction"; - public static final String DCR_JWKS_CONNECTION_TIMEOUT = "DCR.JWKS-Retriever.ConnectionTimeout"; - public static final String DCR_JWKS_READ_TIMEOUT = "DCR.JWKS-Retriever.ReadTimeout"; - public static final String ENVIRONMENT_PROD = "production"; - public static final String ENVIRONMENT_SANDBOX = "sandbox"; - public static final String ARRAY_ELEMENT_SEPERATOR = "#"; - public static final String DUPLICATE_APPLICATION_NAME = "CONFLICT_EXISTING_APPLICATION"; - public static final String DCR_REGISTRATION_PARAM_SCOPE = "scope"; - public static final String DCR_REGISTRATION_PARAM_REQUIRED = "Required"; - public static final String DCR_REGISTRATION_PARAM_ALLOWED_VALUES = "AllowedValues"; - public static final String DCR_REGISTRATION_PARAM_REQUIRED_TRUE = "true"; - - public static final String POST_APPLICATION_LISTENER = "DCR.ApplicationUpdaterImpl"; - public static final String SOFTWARE_STATEMENT = "software_statement"; - public static final String REGULATORY_ISSUERS = "DCR.RegulatoryIssuers.Issuer"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/DefaultRegistrationValidatorImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/DefaultRegistrationValidatorImpl.java deleted file mode 100644 index b7961df3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/DefaultRegistrationValidatorImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationResponse; -import com.wso2.openbanking.accelerator.identity.dcr.model.SoftwareStatementBody; -import com.wso2.openbanking.accelerator.identity.dcr.utils.ValidatorUtils; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Map; - -/** - * Default implementation for dcr registration VALIDATOR class. - */ -public class DefaultRegistrationValidatorImpl extends RegistrationValidator { - - private static final Log log = LogFactory.getLog(DefaultRegistrationValidatorImpl.class); - - @Override - public void validatePost(RegistrationRequest registrationRequest) throws DCRValidationException { - - } - - @Override - public void validateGet(String clientId) throws DCRValidationException { - - } - - @Override - public void validateDelete(String clientId) throws DCRValidationException { - - } - - @Override - public void validateUpdate(RegistrationRequest registrationRequest) throws DCRValidationException { - - } - - /** - * method to set the software statement payload according to the specification. - * - * @param registrationRequest model containing the dcr registration details - * @param decodedSSA decoded json string of the softwarestatement payload - */ - public void setSoftwareStatementPayload(RegistrationRequest registrationRequest, String decodedSSA) { - - SoftwareStatementBody softwareStatementPayload = new GsonBuilder().create() - .fromJson(decodedSSA, SoftwareStatementBody.class); - registrationRequest.setSoftwareStatementBody(softwareStatementPayload); - - } - - @Override - @Generated(message = "Excluding from code coverage since it requires to load JWKS URI and invoke service calls") - public String getRegistrationResponse(Map spMetaData) { - - // Append registration access token and registration client URI to the DCR response if the config is enabled - if (IdentityCommonUtil.getDCRModifyResponseConfig()) { - - String tlsCert = spMetaData.get(IdentityCommonConstants.TLS_CERT).toString(); - - String clientId = spMetaData.get(IdentityCommonConstants.CLIENT_ID).toString(); - - if (!spMetaData.containsKey(IdentityCommonConstants.REGISTRATION_ACCESS_TOKEN)) { - // add the access token to the response - spMetaData.put(IdentityCommonConstants.REGISTRATION_ACCESS_TOKEN, - ValidatorUtils.generateAccessToken(clientId, tlsCert)); - } - - // add the dcr url to the response with the client id appended at the end - spMetaData.put(IdentityCommonConstants.REGISTRATION_CLIENT_URI, - ValidatorUtils.getRegistrationClientURI() + clientId); - } - - Gson gson = new Gson(); - JsonElement jsonElement = gson.toJsonTree(spMetaData); - RegistrationResponse registrationResponse = gson.fromJson(jsonElement, RegistrationResponse.class); - return gson.toJson(registrationResponse); - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/IssuerValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/IssuerValidator.java deleted file mode 100644 index a7dfc3ef..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/IssuerValidator.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateIssuer; -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; -import java.text.ParseException; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for validating the issuer of the registration request. - */ -public class IssuerValidator implements ConstraintValidator { - - private static final Log log = LogFactory.getLog(IssuerValidator.class); - - private String issuerPath; - private String ssaPath; - - @Override - public void initialize(ValidateIssuer validateIssuer) { - - this.issuerPath = validateIssuer.issuerProperty(); - this.ssaPath = validateIssuer.ssa(); - } - - @Override - public boolean isValid(Object registrationRequest, ConstraintValidatorContext constraintValidatorContext) { - - try { - String issuer = BeanUtils.getProperty(registrationRequest, issuerPath); - String softwareStatement = BeanUtils.getProperty(registrationRequest, ssaPath); - if (issuer != null && softwareStatement != null) { - String softwareId = JWTUtils.decodeRequestJWT(softwareStatement, "body") - .getAsString(DCRCommonConstants.SOFTWARE_ID); - if (softwareId != null && softwareId.equals(issuer)) { - return true; - } - } else { - return true; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - log.error("Error while resolving validation fields", e); - } catch (ParseException e) { - log.error("Error while parsing the softwareStatement", e); - } - - return false; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RegistrationValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RegistrationValidator.java deleted file mode 100644 index 5390f667..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RegistrationValidator.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; - -import java.util.Map; - -/** - * Abstract class to perform spec specific validation for each crud operation. - * Implementation class for this should be configured in open-banking.xml - */ -public abstract class RegistrationValidator { - - private static RegistrationValidator registrationValidator; - - public static RegistrationValidator getRegistrationValidator() { - - return registrationValidator; - } - - public static void setRegistrationValidator(RegistrationValidator registrationValidator) { - - RegistrationValidator.registrationValidator = registrationValidator; - } - - /** - * method to set the software statement payload according to the specification. - * - * @param registrationRequest model containing the dcr registration details - * @param decodedSSA decoded json string of the softwarestatement payload - */ - public abstract void setSoftwareStatementPayload(RegistrationRequest registrationRequest, String decodedSSA); - - /** - * validate the request parameters when creating a registration. - * - * @param registrationRequest request - * @throws DCRValidationException if any validation failure occurs - */ - public abstract void validatePost(RegistrationRequest registrationRequest) throws DCRValidationException; - - /** - * do any validations before retrieving created registration details. - * - * @param clientId client ID of the registered application - * @throws DCRValidationException if any validation failure occurs - */ - public abstract void validateGet(String clientId) throws DCRValidationException; - - /** - * do any validations before deleting a created application. - * - * @param clientId client ID of the registered application - * @throws DCRValidationException if any validation failure occurs - */ - public abstract void validateDelete(String clientId) throws DCRValidationException; - - /** - * validate the request parameters when creating a registration. - * - * @param registrationRequest request - * @throws DCRValidationException if any validation failure occurs - */ - public abstract void validateUpdate(RegistrationRequest registrationRequest) throws DCRValidationException; - - /** - * method to return the response according to the implemented specification when retrieving registered data. - * - * @param clientMetaData object map containing the registered client meta data - * @return JSON string containing attributes of client that should be returned - */ - public abstract String getRegistrationResponse(Map clientMetaData); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RequiredParamsValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RequiredParamsValidator.java deleted file mode 100644 index 2b37bc65..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RequiredParamsValidator.java +++ /dev/null @@ -1,157 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateRequiredParams; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - - -/** - * Validator class for validating the required parameters. - */ -public class RequiredParamsValidator implements ConstraintValidator { - - private static final Log log = LogFactory.getLog(RequiredParamsValidator.class); - - private static ObjectMapper objMapper = new ObjectMapper(); - - @Override - public boolean isValid(Object registrationRequestObject, ConstraintValidatorContext constraintValidatorContext) { - - RegistrationRequest registrationRequest = (RegistrationRequest) registrationRequestObject; - - Map requestParameterMap = objMapper.convertValue(registrationRequest, Map.class); - - Map> dcrConfigs = IdentityExtensionsDataHolder.getInstance() - .getDcrRegistrationConfigMap(); - - for (Map.Entry> paramConfig : dcrConfigs.entrySet()) { - //convert first letter to lowercase in DCR registration config parameters - String camelCaseConfigParam = convertFirstLetterToLowerCase(paramConfig.getKey()); - //check whether required parameters are available in the request as expected - if (DCRCommonConstants.DCR_REGISTRATION_PARAM_REQUIRED_TRUE - .equalsIgnoreCase((String) paramConfig.getValue() - .get(DCRCommonConstants.DCR_REGISTRATION_PARAM_REQUIRED))) { - if (requestParameterMap.get(camelCaseConfigParam) == null) { - constraintValidatorContext.disableDefaultConstraintViolation(); - constraintValidatorContext - .buildConstraintViolationWithTemplate("Required parameter " + camelCaseConfigParam + - " cannot be null:" + DCRCommonConstants.INVALID_META_DATA) - .addConstraintViolation(); - return false; - } - //validate list type required parameters - if (requestParameterMap.get(camelCaseConfigParam) instanceof List) { - List param = (List) requestParameterMap.get(camelCaseConfigParam); - if (param.isEmpty()) { - constraintValidatorContext.disableDefaultConstraintViolation(); - constraintValidatorContext - .buildConstraintViolationWithTemplate("Required parameter " + camelCaseConfigParam + - " cannot be empty:" + DCRCommonConstants.INVALID_META_DATA) - .addConstraintViolation(); - return false; - } - } - //validate string type required parameters - if (requestParameterMap.get(camelCaseConfigParam) instanceof String) { - String param = (String) requestParameterMap.get(camelCaseConfigParam); - if (StringUtils.isBlank(param)) { - constraintValidatorContext.disableDefaultConstraintViolation(); - constraintValidatorContext - .buildConstraintViolationWithTemplate("Required parameter " + camelCaseConfigParam + - " cannot be empty:" + DCRCommonConstants.INVALID_META_DATA) - .addConstraintViolation(); - return false; - } - } - } - //checks whether tag is set in config and is not empty. - if (paramConfig.getValue().get(DCRCommonConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUES) != null && - requestParameterMap.get(camelCaseConfigParam) != null) { - //checks whether allowed values configurations contain any empty values - if (!((List) paramConfig.getValue().get(DCRCommonConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUES)) - .contains("")) { - //validate against allowed values provided in config - List allowedList = (List) paramConfig.getValue() - .get(DCRCommonConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUES); - //validate array type parameters - if (requestParameterMap.get(camelCaseConfigParam) instanceof List) { - List params = (ArrayList) requestParameterMap.get(camelCaseConfigParam); - for (Object paramObject : params) { - if (paramObject instanceof String) { - String param = (String) paramObject; - if (!allowedList.contains(param)) { - constraintValidatorContext.disableDefaultConstraintViolation(); - constraintValidatorContext - .buildConstraintViolationWithTemplate("Invalid " + - camelCaseConfigParam + " provided:" + - DCRCommonConstants.INVALID_META_DATA).addConstraintViolation(); - return false; - } - } - - } - } - //validate string type parameters - if (requestParameterMap.get(camelCaseConfigParam) instanceof String) { - String param = (String) requestParameterMap.get(camelCaseConfigParam); - //check scope validation since request is sending a space separated scopes list - if (camelCaseConfigParam.equalsIgnoreCase(DCRCommonConstants.DCR_REGISTRATION_PARAM_SCOPE)) { - List scopeList = Arrays.asList(param.split(" ")); - for (String scope : scopeList) { - if (!allowedList.contains(scope)) { - constraintValidatorContext - .buildConstraintViolationWithTemplate("Invalid " + - camelCaseConfigParam + " provided:" + - DCRCommonConstants.INVALID_META_DATA).addConstraintViolation(); - return false; - } - } - } else if (!allowedList.contains(param)) { - constraintValidatorContext.disableDefaultConstraintViolation(); - constraintValidatorContext - .buildConstraintViolationWithTemplate("Invalid " + - camelCaseConfigParam + " provided:" + - DCRCommonConstants.INVALID_META_DATA).addConstraintViolation(); - return false; - } - } - } - } - } - return true; - } - - private String convertFirstLetterToLowerCase(String configParameterValue) { - return configParameterValue.substring(0, 1).toLowerCase(Locale.ENGLISH) + configParameterValue.substring(1); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/SignatureValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/SignatureValidator.java deleted file mode 100644 index 0c5dd3f0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/SignatureValidator.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.proc.BadJOSEException; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.identity.IdentityConstants; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateSignature; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.text.ParseException; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -/** - * Validator class for signature validation of SSA. - */ -public class SignatureValidator implements ConstraintValidator { - - private static final Log log = LogFactory.getLog(SignatureValidator.class); - - private String softwareStatementPath; - private String ssaBodyPath; - - @Override - public void initialize(ValidateSignature validateSignature) { - - this.softwareStatementPath = validateSignature.ssa(); - this.ssaBodyPath = validateSignature.ssaBody(); - } - - @Override - public boolean isValid(Object registrationRequest, - ConstraintValidatorContext constraintValidatorContext) { - - try { - String softwareStatement = BeanUtils.getProperty(registrationRequest, softwareStatementPath); - if (StringUtils.isEmpty(softwareStatement)) { - return true; - } - SignedJWT signedJWT = SignedJWT.parse(softwareStatement); - String jwtString = signedJWT.getParsedString(); - String alg = signedJWT.getHeader().getAlgorithm().getName(); - String softwareEnvironmentFromSSA = OpenBankingUtils.getSoftwareEnvironmentFromSSA(jwtString); - String jwksURL; - - if (IdentityConstants.PRODUCTION.equals(softwareEnvironmentFromSSA)) { - // validate the signature against production jwks - jwksURL = IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .get(DCRCommonConstants.DCR_JWKS_ENDPOINT_PRODUCTION).toString(); - if (log.isDebugEnabled()) { - log.debug(String.format("Validating the signature from Production JwksUrl %s", - jwksURL.replaceAll("[\r\n]", ""))); - } - } else { - // else validate the signature against sandbox jwks - jwksURL = IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .get(DCRCommonConstants.DCR_JWKS_ENDPOINT_SANDBOX).toString(); - if (log.isDebugEnabled()) { - log.debug(String.format("Validating the signature from Sandbox JwksUrl %s", - jwksURL.replaceAll("[\r\n]", ""))); - } - } - return isValidateJWTSignature(jwksURL, jwtString, alg); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - log.error("Error while resolving validation fields", e); - } catch (ParseException e) { - log.error("Error while parsing the JWT string", e); - } - return false; - } - - private boolean isValidateJWTSignature(String jwksURL, String jwtString, String alg) { - - try { - return JWTUtils.validateJWTSignature(jwtString, jwksURL, alg); - } catch (ParseException e) { - log.error("Error while parsing the JWT string", e); - } catch (JOSEException | BadJOSEException | MalformedURLException e) { - log.error("Error occurred while validating the signature", e); - } - return false; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateAlgorithm.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateAlgorithm.java deleted file mode 100644 index 57b56d2d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateAlgorithm.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation.annotation; - -import com.wso2.openbanking.accelerator.identity.dcr.validation.AlgorithmValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for validating algorithm. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {AlgorithmValidator.class}) -public @interface ValidateAlgorithm { - - String message() default "Invalid algorithm provided"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String idTokenAlg() default "idTokenAlg"; - - String reqObjAlg() default "reqObjAlg"; - - String tokenAuthAlg() default "tokenAuthAlg"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateIssuer.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateIssuer.java deleted file mode 100644 index c3d0651e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateIssuer.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation.annotation; - -import com.wso2.openbanking.accelerator.identity.dcr.validation.IssuerValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for issuer validation. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {IssuerValidator.class}) -public @interface ValidateIssuer { - - String message() default "Invalid issuer"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String issuerProperty() default "issuerProperty"; - - String ssa() default "ssa"; -} - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateRequiredParams.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateRequiredParams.java deleted file mode 100644 index d8f0faf2..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateRequiredParams.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation.annotation; - -import com.wso2.openbanking.accelerator.identity.dcr.validation.RequiredParamsValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for required parameters validation. - */ -@Target(TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {RequiredParamsValidator.class}) -public @interface ValidateRequiredParams { - - String message() default "Missing required parameters"; - - Class[] groups() default {}; - - Class[] payload() default {}; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateSignature.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateSignature.java deleted file mode 100644 index d7696e97..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/annotation/ValidateSignature.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation.annotation; - -import com.wso2.openbanking.accelerator.identity.dcr.validation.SignatureValidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotation class for signature validation. - */ -@Target(ElementType.TYPE) -@Retention(RUNTIME) -@Documented -@Constraint(validatedBy = {SignatureValidator.class}) -public @interface ValidateSignature { - - String message() default "Invalid signature for the provided SSA"; - - Class[] groups() default {}; - - Class[] payload() default {}; - - String ssaBody() default "ssaBody"; - - String ssa() default "ssa"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/AttributeChecks.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/AttributeChecks.java deleted file mode 100644 index f65793bf..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/AttributeChecks.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.validation.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Groups the validations for attributes - */ -@Deprecated -public interface AttributeChecks { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/MandatoryChecks.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/MandatoryChecks.java deleted file mode 100644 index cb938dbb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/MandatoryChecks.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.validation.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Grouping the mandatory check constraints - */ -@Deprecated -public interface MandatoryChecks { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/SignatureCheck.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/SignatureCheck.java deleted file mode 100644 index 4ce4bacb..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/SignatureCheck.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.validation.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Groups the validation for signature - */ -@Deprecated -public interface SignatureCheck { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/ValidationOrder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/ValidationOrder.java deleted file mode 100644 index d42af484..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/ValidationOrder.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation.validationgroups; - -import javax.validation.GroupSequence; - -/** - * Class to define the order of execution for the hibernate validation groups. - */ -@GroupSequence({MandatoryChecks.class, AttributeChecks.class, SignatureCheck.class}) -@Deprecated -public interface ValidationOrder { - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/ValidityChecks.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/ValidityChecks.java deleted file mode 100644 index 4a011cca..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationgroups/ValidityChecks.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.validation.validationgroups; - -/** - * Interface for grouping the validation annotations. - * Groups the validations for the validity of a JWT - */ -@Deprecated -public interface ValidityChecks { - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationorder/ValidationOrder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationorder/ValidationOrder.java deleted file mode 100644 index 9a2355a4..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/validation/validationorder/ValidationOrder.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation.validationorder; - -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.AttributeChecks; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.MandatoryChecks; -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.SignatureCheck; - -import javax.validation.GroupSequence; - -/** - * Class to define the order of execution for the hibernate validation groups. - */ -@GroupSequence({MandatoryChecks.class, AttributeChecks.class, SignatureCheck.class}) -public interface ValidationOrder { - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dispute/resolution/DisputeResolutionFilter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dispute/resolution/DisputeResolutionFilter.java deleted file mode 100644 index d8bbcda7..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/dispute/resolution/DisputeResolutionFilter.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dispute.resolution; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import com.wso2.openbanking.accelerator.identity.token.wrapper.RequestWrapper; -import com.wso2.openbanking.accelerator.identity.token.wrapper.ResponseWrapper; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.IOException; -import java.time.Instant; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.StringJoiner; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static com.wso2.openbanking.accelerator.common.util.OpenBankingUtils.isPublishableDisputeData; -import static com.wso2.openbanking.accelerator.common.util.OpenBankingUtils.reduceStringLength; - -/** - * Dispute Resolution Filter. - */ -public class DisputeResolutionFilter implements Filter { - - private static final Log log = LogFactory.getLog(DisputeResolutionFilter.class); - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - - //Checking Dispute Resolution Feature is Enabled - if (!OpenBankingConfigParser.getInstance().isDisputeResolutionEnabled()) { - chain.doFilter(request, response); - } else { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - - // Create a custom response wrapper to capture the response output - ResponseWrapper responseWrapper = new ResponseWrapper(httpResponse); - - // Create a custom request wrapper to capture the request - RequestWrapper requestWrapper = new RequestWrapper(httpRequest); - - // Retrieve the captured request output - byte[] requestContent = requestWrapper.getCapturedRequest(); - - // Convert the request content to JSON - String jsonRequest = new String(requestContent, httpRequest.getCharacterEncoding()); - - //get headers from requestWrapper - Enumeration headersRequestWrapper = requestWrapper.getHeaderNames(); - - // Capture error request information - String httpMethod = httpRequest.getMethod(); - String resourceURL = httpRequest.getRequestURL().toString(); - Map requestParams = httpRequest.getParameterMap(); - - // Convert requestParams to JSON string representation - ObjectMapper objectMapper = new ObjectMapper(); - String requestParamsJson = objectMapper.writeValueAsString(requestParams); - - String requestBody = StringUtils.defaultIfEmpty(jsonRequest, requestParamsJson); - - Enumeration headersMap = headersRequestWrapper; - - //Convert the headerMap to a string - StringJoiner joiner = new StringJoiner(", "); - while (headersMap.hasMoreElements()) { - String element = headersMap.nextElement(); - joiner.add(element); - } - String headers = joiner.toString(); - - chain.doFilter(requestWrapper, responseWrapper); - - // Retrieve the captured response output - byte[] responseContent = responseWrapper.getData(); - - // Convert the response content to JSON - String jsonResponse = new String(responseContent, httpResponse.getCharacterEncoding()); - - Map disputeResolutionData = new HashMap<>(); - - // Capture the response information - int statusCode = httpResponse.getStatus(); - String responseBody = jsonResponse; - - long unixTimestamp = Instant.now().getEpochSecond(); - - //reduced Headers, Request and Response Body Lengths - requestBody = reduceStringLength(requestBody, - OpenBankingConfigParser.getInstance().getMaxRequestBodyLength()); - responseBody = reduceStringLength(responseBody, - OpenBankingConfigParser.getInstance().getMaxResponseBodyLength()); - headers = reduceStringLength(headers, - OpenBankingConfigParser.getInstance().getMaxHeaderLength()); - - // Add the captured data put into the disputeResolutionData Map - disputeResolutionData.put(OpenBankingConstants.REQUEST_BODY, requestBody); - disputeResolutionData.put(OpenBankingConstants.RESPONSE_BODY, responseBody); - disputeResolutionData.put(OpenBankingConstants.STATUS_CODE, statusCode); - disputeResolutionData.put(OpenBankingConstants.HTTP_METHOD, httpMethod); - disputeResolutionData.put(OpenBankingConstants.ELECTED_RESOURCE, resourceURL); - disputeResolutionData.put(OpenBankingConstants.TIMESTAMP, unixTimestamp); - disputeResolutionData.put(OpenBankingConstants.HEADERS, headers); - - //Checking configurations to publish Dispute Data - if (isPublishableDisputeData(statusCode)) { - OBDataPublisherUtil.publishData(OpenBankingConstants.DISPUTE_RESOLUTION_STREAM_NAME, - OpenBankingConstants.DISPUTE_RESOLUTION_STREAM_VERSION, disputeResolutionData); - } - - response.getOutputStream().write(responseWrapper.getData()); - } - - } - -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBAuthorizationCodeGrantHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBAuthorizationCodeGrantHandler.java deleted file mode 100644 index 40a19ba5..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBAuthorizationCodeGrantHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.grant.type.handlers; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationCodeGrantHandler; - -/** - * OB specific authorization code grant handler. - */ -public class OBAuthorizationCodeGrantHandler extends AuthorizationCodeGrantHandler { - - @Override - public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - try { - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(tokReqMsgCtx.getOauth2AccessTokenReqDTO() - .getClientId())) { - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO = super.issue(tokReqMsgCtx); - executeInitialStep(oAuth2AccessTokenRespDTO, tokReqMsgCtx); - tokReqMsgCtx.setScope(IdentityCommonUtil.removeInternalScopes(tokReqMsgCtx.getScope())); - publishUserAccessTokenData(oAuth2AccessTokenRespDTO); - return oAuth2AccessTokenRespDTO; - } - } catch (OpenBankingException e) { - throw new IdentityOAuth2Exception(e.getMessage()); - } - return super.issue(tokReqMsgCtx); - } - - /** - * Extend this method to publish access token related data. - * - * @param oAuth2AccessTokenRespDTO - */ - - public void publishUserAccessTokenData(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO) - throws IdentityOAuth2Exception { - - } - - /** - * Extend this method to perform any actions which requires internal scopes. - * - * @param oAuth2AccessTokenRespDTO - * @param tokReqMsgCtx - */ - public void executeInitialStep(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO, - OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - } - - /** - * Extend this method to perform any actions related when issuing refresh token. - * - * @return - */ - @Override - public boolean issueRefreshToken() throws IdentityOAuth2Exception { - - return super.issueRefreshToken(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBClientCredentialsGrantHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBClientCredentialsGrantHandler.java deleted file mode 100644 index ba66983c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBClientCredentialsGrantHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.grant.type.handlers; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; -import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; - -import java.util.Arrays; - -/** - * OB specific client credentials code grant handler. - */ -public class OBClientCredentialsGrantHandler extends ClientCredentialsGrantHandler { - - @Override - public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - try { - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(tokReqMsgCtx.getOauth2AccessTokenReqDTO() - .getClientId())) { - if (IdentityCommonUtil.getDCRModifyResponseConfig() && tokReqMsgCtx.getScope().length > 0 && - Arrays.asList(tokReqMsgCtx.getScope()).contains(IdentityCommonUtil.getDCRScope())) { - long validityPeriod = 999999999; - OAuthAppDO oAuthAppDO = OAuth2Util - .getAppInformationByClientId(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId()); - oAuthAppDO.setApplicationAccessTokenExpiryTime(validityPeriod); - tokReqMsgCtx.setValidityPeriod(validityPeriod); - } - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO = super.issue(tokReqMsgCtx); - executeInitialStep(oAuth2AccessTokenRespDTO, tokReqMsgCtx); - tokReqMsgCtx.setScope(IdentityCommonUtil.removeInternalScopes(tokReqMsgCtx.getScope())); - publishUserAccessTokenData(oAuth2AccessTokenRespDTO); - return oAuth2AccessTokenRespDTO; - } - } catch (OpenBankingException | InvalidOAuthClientException e) { - throw new IdentityOAuth2Exception(e.getMessage()); - } - return super.issue(tokReqMsgCtx); - } - - /** - * Extend this method to publish access token related data. - * - * @param oAuth2AccessTokenRespDTO - */ - - public void publishUserAccessTokenData(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO) - throws IdentityOAuth2Exception { - - } - - /** - * Extend this method to perform any actions which requires internal scopes. - * - * @param oAuth2AccessTokenRespDTO - * @param tokReqMsgCtx - */ - public void executeInitialStep(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO, - OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBPasswordGrantHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBPasswordGrantHandler.java deleted file mode 100644 index cbb978ea..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBPasswordGrantHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.grant.type.handlers; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler; - -/** - * OB specific password grant handler. - */ -public class OBPasswordGrantHandler extends PasswordGrantHandler { - - @Override - public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - try { - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(tokReqMsgCtx.getOauth2AccessTokenReqDTO() - .getClientId())) { - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO = super.issue(tokReqMsgCtx); - executeInitialStep(oAuth2AccessTokenRespDTO, tokReqMsgCtx); - tokReqMsgCtx.setScope(IdentityCommonUtil.removeInternalScopes(tokReqMsgCtx.getScope())); - publishUserAccessTokenData(oAuth2AccessTokenRespDTO); - return oAuth2AccessTokenRespDTO; - } - } catch (OpenBankingException e) { - throw new IdentityOAuth2Exception(e.getMessage()); - } - return super.issue(tokReqMsgCtx); - } - - /** - * Extend this method to publish access token related data. - * - * @param oAuth2AccessTokenRespDTO - */ - - public void publishUserAccessTokenData(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO) - throws IdentityOAuth2Exception { - - } - - /** - * Extend this method to perform any actions which requires internal scopes. - * - * @param oAuth2AccessTokenRespDTO - * @param tokReqMsgCtx - */ - public void executeInitialStep(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO, - OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBRefreshGrantHandler.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBRefreshGrantHandler.java deleted file mode 100644 index 8f9c458e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/grant/type/handlers/OBRefreshGrantHandler.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.grant.type.handlers; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.oauth2.token.handlers.grant.RefreshGrantHandler; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; - -/** - * OB specific refresh grant handler. - */ -public class OBRefreshGrantHandler extends RefreshGrantHandler { - - private static final Log log = LogFactory.getLog(OBRefreshGrantHandler.class); - - @Override - public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - try { - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(tokReqMsgCtx.getOauth2AccessTokenReqDTO() - .getClientId())) { - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO = super.issue(tokReqMsgCtx); - executeInitialStep(oAuth2AccessTokenRespDTO, tokReqMsgCtx); - tokReqMsgCtx.setScope(IdentityCommonUtil.removeInternalScopes(tokReqMsgCtx.getScope())); - publishUserAccessTokenData(oAuth2AccessTokenRespDTO); - if (tokReqMsgCtx.getScope().length == 0) { - oAuth2AccessTokenRespDTO.setAuthorizedScopes(""); - } - return oAuth2AccessTokenRespDTO; - } - } catch (OpenBankingException e) { - throw new IdentityOAuth2Exception(e.getMessage()); - } - return super.issue(tokReqMsgCtx); - } - - /** - * Extend this method to publish access token related data. - * - * @param oAuth2AccessTokenRespDTO - */ - - public void publishUserAccessTokenData(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO) - throws IdentityOAuth2Exception { - - } - - /** - * Extend this method to perform any actions which requires internal scopes. - * - * @param oAuth2AccessTokenRespDTO - * @param tokReqMsgCtx - */ - public void executeInitialStep(OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO, - OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - } - - @Override - public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { - - String[] grantedScopes = tokReqMsgCtx.getScope(); - if (!super.validateScope(tokReqMsgCtx)) { - return false; - } - - String[] requestedScopes = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getScope(); - if (ArrayUtils.isNotEmpty(requestedScopes)) { - //Adding internal scopes. - ArrayList requestedScopeList = new ArrayList<>(Arrays.asList(requestedScopes)); - String consentIdClaim = IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .get(IdentityCommonConstants.CONSENT_ID_CLAIM_NAME).toString(); - for (String scope : grantedScopes) { - if (scope.startsWith(consentIdClaim)) { - if (log.isDebugEnabled()) { - log.debug(String.format("Adding custom scope %s to the requested scopes", scope)); - } - requestedScopeList.add(scope); - } - } - - // remove duplicates in requestedScopeList - requestedScopeList = new ArrayList<>(new HashSet<>(requestedScopeList)); - - String[] modifiedScopes = requestedScopeList.toArray(new String[0]); - if (modifiedScopes.length != 0) { - tokReqMsgCtx.setScope(modifiedScopes); - } - } - return true; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/idtoken/OBIDTokenBuilder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/idtoken/OBIDTokenBuilder.java deleted file mode 100644 index 11a97f30..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/idtoken/OBIDTokenBuilder.java +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.idtoken; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -/** - * OB specific IDToken builder. - */ -public class OBIDTokenBuilder extends DefaultIDTokenBuilder { - - private static final Log log = LogFactory.getLog(OBIDTokenBuilder.class); - - public OBIDTokenBuilder() throws IdentityOAuth2Exception { - - } - - Map identityConfigurations = IdentityExtensionsDataHolder.getInstance().getConfigurationMap(); - Object ppidProperty = identityConfigurations.get(IdentityCommonConstants.ENABLE_SUBJECT_AS_PPID); - Object removeTenantDomainConfig = identityConfigurations. - get(IdentityCommonConstants.REMOVE_TENANT_DOMAIN_FROM_SUBJECT); - Boolean removeTenantDomain = removeTenantDomainConfig != null - && Boolean.parseBoolean(removeTenantDomainConfig.toString()); - Object removeUserStoreDomainConfig = identityConfigurations. - get(IdentityCommonConstants.REMOVE_USER_STORE_DOMAIN_FROM_SUBJECT); - Boolean removeUserStoreDomain = removeUserStoreDomainConfig != null - && Boolean.parseBoolean(removeUserStoreDomainConfig.toString()); - - // method to set the subject claim in id token returned in authorization as a pairwise pseudonymous ID - @Override - protected String getSubjectClaim(OAuthAuthzReqMessageContext authzReqMessageContext, - OAuth2AuthorizeRespDTO authorizeRespDTO, - String clientId, - String spTenantDomain, - AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { - - String callBackUri = authzReqMessageContext.getAuthorizationReqDTO().getCallbackUrl(); - String userId = StringUtils.EMPTY; - String subject = StringUtils.EMPTY; - String sectorIdentifierUri = null; - boolean setSubjectAsPPID = false; - if (ppidProperty != null) { - setSubjectAsPPID = Boolean.parseBoolean(ppidProperty.toString()); - } - try { - // for non regulatory scenarios, need to return the user id as the subject - if (!IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId)) { - return super.getSubjectClaim(authzReqMessageContext, authorizeRespDTO, clientId, spTenantDomain, - authorizedUser); - } - sectorIdentifierUri = getSectorIdentifierUri(clientId); - } catch (OpenBankingException e) { - log.error("Error occurred while retrieving service provider data", e); - throw new IdentityOAuth2Exception("Error occurred while retrieving service provider data"); - } - if (setSubjectAsPPID) { - if (authzReqMessageContext.getAuthorizationReqDTO().getUser() != null) { - userId = authzReqMessageContext.getAuthorizationReqDTO().getUser() - .getUsernameAsSubjectIdentifier(false, false); - } - subject = getSubjectClaimValue(sectorIdentifierUri, userId, callBackUri); - if (StringUtils.isNotBlank(subject)) { - return subject; - } else { - log.error("Subject claim cannot be empty"); - throw new IdentityOAuth2Exception("Subject claim cannot be empty"); - } - } else if (removeTenantDomain || removeUserStoreDomain) { - /* Update the subject claim of the JWT claims set if any of the following configurations are true - and if PPID is as the subject claim is not enabled. - 1. open_banking.identity.token.remove_user_store_domain_from_subject - 2. open_banking.identity.token.remove_tenant_domain_from_subject */ - return authorizedUser.getUsernameAsSubjectIdentifier(!removeUserStoreDomain, !removeTenantDomain); - } else { - return MultitenantUtils.getTenantAwareUsername(super.getSubjectClaim(authzReqMessageContext, - authorizeRespDTO, clientId, spTenantDomain, authorizedUser)); - } - } - - // method to set the subject claim in Id token returned in token response - @Override - protected String getSubjectClaim(OAuthTokenReqMessageContext tokenReqMessageContext, - OAuth2AccessTokenRespDTO tokenRespDTO, - String clientId, - String spTenantDomain, - AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { - - String callBackUri = tokenRespDTO.getCallbackURI(); - String userId = StringUtils.EMPTY; - String subject = StringUtils.EMPTY; - String sectorIdentifierUri = null; - boolean setSubjectAsPPID = false; - if (ppidProperty != null) { - setSubjectAsPPID = Boolean.parseBoolean(ppidProperty.toString()); - } - try { - // for non regulatory scenarios, need to return the user id as the subject - if (!IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId)) { - return super.getSubjectClaim(tokenReqMessageContext, tokenRespDTO, clientId, spTenantDomain, - authorizedUser); - } - sectorIdentifierUri = getSectorIdentifierUri(clientId); - } catch (OpenBankingException e) { - log.error("Error occurred while retrieving service provider data", e); - throw new IdentityOAuth2Exception("Error occurred while retrieving service provider data"); - } - if (setSubjectAsPPID) { - if (tokenReqMessageContext.getAuthorizedUser() != null) { - userId = tokenReqMessageContext.getAuthorizedUser() - .getUsernameAsSubjectIdentifier(false, false); - } - subject = getSubjectClaimValue(sectorIdentifierUri, userId, callBackUri); - if (StringUtils.isNotBlank(subject)) { - return subject; - } else { - log.error("Subject claim cannot be empty"); - throw new IdentityOAuth2Exception("Subject claim cannot be empty"); - } - } else if (removeTenantDomain || removeUserStoreDomain) { - /* Update the subject claim of the JWT claims set if any of the following configurations are true - and if PPID is as the subject claim is not enabled. - 1. open_banking.identity.token.remove_user_store_domain_from_subject - 2. open_banking.identity.token.remove_tenant_domain_from_subject */ - return authorizedUser.getUsernameAsSubjectIdentifier(!removeUserStoreDomain, !removeTenantDomain); - } else { - return MultitenantUtils.getTenantAwareUsername(super.getSubjectClaim(tokenReqMessageContext, - tokenRespDTO, clientId, spTenantDomain, authorizedUser)); - } - } - - /** - * Get the subject claim as a UUID with userId and call back uri host name as seed. - * - * @param callBackUri redirect uri of the data recipient - * @param userID user identification of the consumer - * @return - */ - private String getSubjectFromCallBackUris(String callBackUri, String userID) { - - List uris = unwrapURIString(callBackUri); - - if (!uris.isEmpty()) { - URI uri; - try { - // assuming all URIs have the same hostname, we just take the first URI - uri = new URI(uris.get(0)); - } catch (URISyntaxException e) { - log.error("Error while retrieving the host name of the redirect url ", e); - return StringUtils.EMPTY; - } - String hostname = uri.getHost(); - String seed = hostname.concat(userID); - return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString(); - } - log.error("Redirect URIs cannot be empty"); - return StringUtils.EMPTY; - } - - /** - * Get the subject claim as a UUID with userId and sector identifier uri host name as seed. - * - * @param sectorIdentifierUri sector identifier uri of the data recipient - * @param userID user identification of the consumer - * @return - */ - private String getSubjectFromSectorIdentifierUri(String sectorIdentifierUri, String userID) { - - URI uri; - try { - // assuming all URIs have the same hostname, we just take the first URI - uri = new URI(sectorIdentifierUri); - } catch (URISyntaxException e) { - log.error("Error while retrieving the host name of the redirect url ", e); - return StringUtils.EMPTY; - } - String hostname = uri.getHost(); - String seed = hostname.concat(userID); - return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString(); - } - - /** - * Given a string in regex format, unwrap and create list of seperate URIs. - * - * @param uriString The joined URIs in string format. - * @return List of URIs. - */ - private List unwrapURIString(String uriString) { - - Pattern outerPattern = Pattern.compile("regexp=\\((.*?)\\)"); - Pattern innerPattern = Pattern.compile("\\^(.*?)\\$"); - - Matcher matcher = outerPattern.matcher(uriString); - - String delimitedUri; - - if (matcher.find()) { - // remove regex= part - delimitedUri = matcher.group(1); - } else { - // URI is not having regex format - return Collections.singletonList(uriString); - } - - String[] uris = delimitedUri.split("\\|"); - - // remove ^..$ part - return Arrays.stream(uris) - .map(uri -> { - Matcher m = innerPattern.matcher(uri); - if (m.find()) { - return m.group(1); - } else { - return uri; - } - }).collect(Collectors.toList()); - } - - /** - * Get the sector identifier uri from sp metadata. - * - * @param clientId consumer id - * @return - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - protected String getSectorIdentifierUri(String clientId) throws OpenBankingException { - - return (new IdentityCommonHelper()).getAppPropertyFromSPMetaData(clientId, "sector_identifier_uri"); - } - - /** - * Validate and get subject value. - * - * @param sectorIdentifierUri sector identifier uri - * @param userId user id - * @param callBackUri call back uris - * @return subject value if validated or return empty string - */ - private String getSubjectClaimValue(String sectorIdentifierUri, String userId, String callBackUri) { - - if (StringUtils.isNotBlank(sectorIdentifierUri) && StringUtils.isNotBlank(userId)) { - log.debug("Calculating subject claim using sector identifier uri "); - return getSubjectFromSectorIdentifierUri(sectorIdentifierUri, userId); - } else if (StringUtils.isNotBlank(callBackUri) && StringUtils.isNotBlank(userId)) { - log.debug("Calculating subject claim using redirect uris "); - return getSubjectFromCallBackUris(callBackUri, userId); - } - return StringUtils.EMPTY; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/interceptor/OBDefaultIntrospectionDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/interceptor/OBDefaultIntrospectionDataProvider.java deleted file mode 100644 index b936ff6c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/interceptor/OBDefaultIntrospectionDataProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.interceptor; - -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuth2IntrospectionResponseDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * OB specific default introspection data provider implementation. - */ -public class OBDefaultIntrospectionDataProvider extends OBIntrospectionDataProvider { - - - @Override - public Map getIntrospectionData(OAuth2TokenValidationRequestDTO oAuth2TokenValidationRequestDTO, - OAuth2IntrospectionResponseDTO oAuth2IntrospectionResponseDTO) - throws IdentityOAuth2Exception { - - if (oAuth2IntrospectionResponseDTO.isActive()) { - return oAuth2IntrospectionResponseDTO.getProperties(); - } else { - return new HashMap<>(); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/interceptor/OBIntrospectionDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/interceptor/OBIntrospectionDataProvider.java deleted file mode 100644 index 5429a6ec..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/interceptor/OBIntrospectionDataProvider.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.interceptor; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.core.handler.AbstractIdentityHandler; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.IntrospectionDataProvider; -import org.wso2.carbon.identity.oauth2.dto.OAuth2IntrospectionResponseDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; - -import java.util.Map; - -/** - * OB specific introspection data provider. - */ -public class OBIntrospectionDataProvider extends AbstractIdentityHandler implements IntrospectionDataProvider { - - private static IntrospectionDataProvider introspectionDataProvider; - - @Override - public Map getIntrospectionData(OAuth2TokenValidationRequestDTO oAuth2TokenValidationRequestDTO, - OAuth2IntrospectionResponseDTO oAuth2IntrospectionResponseDTO) - throws IdentityOAuth2Exception { - - Map additionalDataMap = getIntrospectionDataProvider() - .getIntrospectionData(oAuth2TokenValidationRequestDTO, oAuth2IntrospectionResponseDTO); - String[] nonInternalScopes = IdentityCommonUtil.removeInternalScopes(oAuth2IntrospectionResponseDTO.getScope() - .split(IdentityCommonConstants.SPACE_SEPARATOR)); - oAuth2IntrospectionResponseDTO.setScope(StringUtils.join(nonInternalScopes, - IdentityCommonConstants.SPACE_SEPARATOR)); - additionalDataMap.put(IdentityCommonConstants.SCOPE, StringUtils.join(nonInternalScopes, - IdentityCommonConstants.SPACE_SEPARATOR)); - oAuth2IntrospectionResponseDTO.setProperties(additionalDataMap); - return additionalDataMap; - } - - public static IntrospectionDataProvider getIntrospectionDataProvider() { - - return introspectionDataProvider; - } - - public static void setIntrospectionDataProvider(IntrospectionDataProvider introspectionDataProvider) { - - OBIntrospectionDataProvider.introspectionDataProvider = introspectionDataProvider; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/internal/IdentityExtensionsDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/internal/IdentityExtensionsDataHolder.java deleted file mode 100644 index c7a14c02..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/internal/IdentityExtensionsDataHolder.java +++ /dev/null @@ -1,459 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function.OpenBankingAuthenticationWorker; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.OBRequestObjectValidator; -import com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler.OBResponseTypeHandler; -import com.wso2.openbanking.accelerator.identity.claims.OBClaimProvider; -import com.wso2.openbanking.accelerator.identity.common.IdentityServiceExporter; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.RegistrationValidator; -import com.wso2.openbanking.accelerator.identity.interceptor.OBIntrospectionDataProvider; -import com.wso2.openbanking.accelerator.identity.listener.application.AbstractApplicationUpdater; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.PushAuthRequestValidator; -import com.wso2.openbanking.accelerator.identity.token.DefaultTokenFilter; -import com.wso2.openbanking.accelerator.identity.token.TokenFilter; -import com.wso2.openbanking.accelerator.identity.token.validators.OBIdentityFilterValidator; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.throttler.service.OBThrottleService; -import org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; -import org.wso2.carbon.identity.oauth2.IntrospectionDataProvider; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService; -import org.wso2.carbon.identity.openidconnect.ClaimProvider; -import org.wso2.carbon.identity.openidconnect.RequestObjectService; -import org.wso2.carbon.user.core.service.RealmService; - -import java.security.KeyStore; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static com.wso2.openbanking.accelerator.common.util.OpenBankingUtils.getClassInstanceFromFQN; -import static com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants.PUSH_AUTH_REQUEST_VALIDATOR; -import static com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants.REQUEST_VALIDATOR; -import static com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants.RESPONSE_HANDLER; - -/** - * Data Holder for Open Banking Common. - */ -public class IdentityExtensionsDataHolder { - - private static volatile IdentityExtensionsDataHolder instance = new IdentityExtensionsDataHolder(); - private ApplicationManagementService applicationManagementService; - private RequestObjectService requestObjectService; - private OAuthAdminServiceImpl oAuthAdminService; - private OpenBankingConfigurationService openBankingConfigurationService; - private Map configurationMap; - private Map> dcrRegistrationConfigMap; - private List tokenValidators = new ArrayList<>(); - private DefaultTokenFilter defaultTokenFilter; - private RegistrationValidator registrationValidator; - private ClaimProvider claimProvider; - private IntrospectionDataProvider introspectionDataProvider; - private OBRequestObjectValidator obRequestObjectValidator; - private PushAuthRequestValidator pushAuthRequestValidator; - private KeyStore trustStore = null; - private OBResponseTypeHandler obResponseTypeHandler; - private AbstractApplicationUpdater abstractApplicationUpdater; - private int identityCacheAccessExpiry; - private int identityCacheModifiedExpiry; - private RealmService realmService; - private OBThrottleService obThrottleService; - private ConsentCoreService consentCoreService; - private OAuthClientAuthnService oAuthClientAuthnService; - private OAuth2Service oAuth2Service; - private JsFunctionRegistry jsFunctionRegistry; - - private Map workers = new HashMap<>(); - - private IdentityExtensionsDataHolder() { - - } - - public static IdentityExtensionsDataHolder getInstance() { - - if (instance == null) { - synchronized (IdentityExtensionsDataHolder.class) { - if (instance == null) { - instance = new IdentityExtensionsDataHolder(); - } - } - } - return instance; - } - - /** - * To get the the instance of {@link ApplicationManagementService}. - * - * @return applicationManagementService - */ - public ApplicationManagementService getApplicationManagementService() { - - return applicationManagementService; - } - - /** - * To set the RequestObjectService. - * - * @param requestObjectService instance of {@link RequestObjectService} - */ - public void setRequestObjectService(RequestObjectService requestObjectService) { - - this.requestObjectService = requestObjectService; - } - - public RequestObjectService getRequestObjectService() { - - return requestObjectService; - } - - - /** - * To set the ApplicationManagementService. - * - * @param applicationManagementService instance of {@link ApplicationManagementService} - */ - public void setApplicationManagementService(ApplicationManagementService applicationManagementService) { - - this.applicationManagementService = applicationManagementService; - } - - /** - * To get the the instance of {@link OAuthAdminServiceImpl}. - * - * @return oauthAdminService - */ - public OAuthAdminServiceImpl getOauthAdminService() { - - return oAuthAdminService; - } - - /** - * To set the OauthAdminService. - * - * @param oauthAdminService instance of {@link OAuthAdminServiceImpl} - */ - public void setOauthAdminService(OAuthAdminServiceImpl oauthAdminService) { - - this.oAuthAdminService = oauthAdminService; - } - - public OpenBankingConfigurationService getOpenBankingConfigurationService() { - - return openBankingConfigurationService; - } - - public void setConfigurationMap(Map confMap) { - - configurationMap = confMap; - } - - public Map getConfigurationMap() { - - return configurationMap; - } - - public void setOpenBankingConfigurationService( - OpenBankingConfigurationService openBankingConfigurationService) { - - this.openBankingConfigurationService = openBankingConfigurationService; - this.configurationMap = openBankingConfigurationService.getConfigurations(); - this.dcrRegistrationConfigMap = openBankingConfigurationService.getDCRRegistrationConfigurations(); - this.setTokenFilterValidators(); - TokenFilter.setValidators(getTokenFilterValidators()); - this.setDefaultTokenFilterImpl(); - TokenFilter.setDefaultTokenFilter(getDefaultTokenFilterImpl()); - RegistrationValidator dcrValidator = - (RegistrationValidator) OpenBankingUtils.getClassInstanceFromFQN(openBankingConfigurationService - .getConfigurations().get(DCRCommonConstants.DCR_VALIDATOR).toString()); - this.setRegistrationValidator(dcrValidator); - RegistrationValidator.setRegistrationValidator(dcrValidator); - obRequestObjectValidator = (OBRequestObjectValidator) - getClassInstanceFromFQN(IdentityExtensionsDataHolder.getInstance() - .getConfigurationMap().get(REQUEST_VALIDATOR).toString()); - PushAuthRequestValidator pushAuthRequestValidatorImpl = (PushAuthRequestValidator) - getClassInstanceFromFQN(IdentityExtensionsDataHolder.getInstance() - .getConfigurationMap().get(PUSH_AUTH_REQUEST_VALIDATOR).toString()); - this.setPushAuthRequestValidator(pushAuthRequestValidatorImpl); - PushAuthRequestValidator.setRegistrationValidator(pushAuthRequestValidatorImpl); - obResponseTypeHandler = (OBResponseTypeHandler) getClassInstanceFromFQN(openBankingConfigurationService - .getConfigurations().get(RESPONSE_HANDLER).toString()); - abstractApplicationUpdater = (AbstractApplicationUpdater) OpenBankingUtils.getClassInstanceFromFQN - (openBankingConfigurationService.getConfigurations().get(DCRCommonConstants.POST_APPLICATION_LISTENER) - .toString()); - this.setClaimProvider((ClaimProvider) OpenBankingUtils.getClassInstanceFromFQN(openBankingConfigurationService - .getConfigurations().get(IdentityCommonConstants.CLAIM_PROVIDER).toString())); - OBClaimProvider.setClaimProvider(getClaimProvider()); - this.setIntrospectionDataProvider((IntrospectionDataProvider) OpenBankingUtils - .getClassInstanceFromFQN(openBankingConfigurationService.getConfigurations() - .get(IdentityCommonConstants.INTROSPECTION_DATA_PROVIDER).toString())); - OBIntrospectionDataProvider.setIntrospectionDataProvider(getIntrospectionDataProvider()); - setIdentityCacheAccessExpiry((String) openBankingConfigurationService - .getConfigurations().get("IdentityCache.CacheAccessExpiry")); - setIdentityCacheModifiedExpiry((String) openBankingConfigurationService - .getConfigurations().get("IdentityCache.CacheModifiedExpiry")); - - Map authenticationWorkers = openBankingConfigurationService.getAuthenticationWorkers(); - authenticationWorkers.forEach((key, value) -> - addWorker((OpenBankingAuthenticationWorker) OpenBankingUtils.getClassInstanceFromFQN(value), key)); - } - - public List getTokenFilterValidators() { - - return tokenValidators; - - } - - public void setTokenFilterValidators() { - - for (Object element : extractTokenFilterValidators()) { - tokenValidators - .add((OBIdentityFilterValidator) OpenBankingUtils.getClassInstanceFromFQN(element.toString())); - } - } - - private List extractTokenFilterValidators() { - - Object validators = configurationMap.get(IdentityCommonConstants.TOKEN_VALIDATORS); - - if (validators != null) { - if (validators instanceof List) { - return (List) configurationMap.get(IdentityCommonConstants.TOKEN_VALIDATORS); - } else { - return Arrays.asList(validators); - } - } else { - return new ArrayList<>(); - } - } - - public DefaultTokenFilter getDefaultTokenFilterImpl() { - - return defaultTokenFilter; - - } - - public void setDefaultTokenFilterImpl() { - - defaultTokenFilter = - (DefaultTokenFilter) OpenBankingUtils.getClassInstanceFromFQN(configurationMap - .get(IdentityCommonConstants.TOKEN_FILTER).toString()); - } - - public OBResponseTypeHandler getObResponseTypeHandler() { - return obResponseTypeHandler; - } - - public RegistrationValidator getRegistrationValidator() { - - return registrationValidator; - } - - public void setRegistrationValidator(RegistrationValidator registrationValidator) { - - this.registrationValidator = registrationValidator; - } - - public ClaimProvider getClaimProvider() { - - return claimProvider; - } - - public void setClaimProvider(ClaimProvider claimProvider) { - - this.claimProvider = claimProvider; - } - - public IntrospectionDataProvider getIntrospectionDataProvider() { - - return introspectionDataProvider; - } - - public void setIntrospectionDataProvider(IntrospectionDataProvider introspectionDataProvider) { - - this.introspectionDataProvider = introspectionDataProvider; - } - - public OBRequestObjectValidator getObRequestObjectValidator() { - return obRequestObjectValidator; - } - - public PushAuthRequestValidator getPushAuthRequestValidator() { - - return pushAuthRequestValidator; - } - - public void setPushAuthRequestValidator(PushAuthRequestValidator pushAuthRequestValidator) { - - this.pushAuthRequestValidator = pushAuthRequestValidator; - } - - public void setDcrRegistrationConfigMap(Map> dcrRegConfigMap) { - - dcrRegistrationConfigMap = dcrRegConfigMap; - } - - public Map> getDcrRegistrationConfigMap() { - - return dcrRegistrationConfigMap; - } - - public AbstractApplicationUpdater getAbstractApplicationUpdater() { - - return abstractApplicationUpdater; - } - - public void setAbstractApplicationUpdater(AbstractApplicationUpdater abstractApplicationUpdater) { - - this.abstractApplicationUpdater = abstractApplicationUpdater; - } - - - public int getIdentityCacheAccessExpiry() { - - return identityCacheAccessExpiry; - } - - public void setIdentityCacheAccessExpiry(String identityCacheAccessExpiry) { - - this.identityCacheAccessExpiry = identityCacheAccessExpiry == null ? 60 : - Integer.parseInt(identityCacheAccessExpiry); - } - - public int getIdentityCacheModifiedExpiry() { - - return identityCacheModifiedExpiry; - } - - public void setIdentityCacheModifiedExpiry(String identityCacheModifiedExpiry) { - - this.identityCacheModifiedExpiry = identityCacheModifiedExpiry == null ? 60 : - Integer.parseInt(identityCacheModifiedExpiry); - } - - public KeyStore getTrustStore() { - return trustStore; - } - - public void setTrustStore(KeyStore trustStore) { - this.trustStore = trustStore; - } - - public RealmService getRealmService() { - - if (realmService == null) { - throw new RuntimeException("Realm Service is not available. Component did not start correctly."); - } - return realmService; - } - - void setRealmService(RealmService realmService) { - - this.realmService = realmService; - } - - /** - * Return OBThrottleService. - * - * @return OBThrottleService - */ - public OBThrottleService getOBThrottleService() { - return obThrottleService; - } - - /** - * Set OBThrottleService. - */ - public void setOBThrottleService(OBThrottleService obThrottleService) { - this.obThrottleService = obThrottleService; - } - public ConsentCoreService getConsentCoreService() { - - return consentCoreService; - } - - public void setConsentCoreService(ConsentCoreService consentCoreService) { - - this.consentCoreService = consentCoreService; - } - - /** - * Return OAuthClientAuthnService. - * - * @return OAuthClientAuthnService - */ - public OAuthClientAuthnService getOAuthClientAuthnService() { - return oAuthClientAuthnService; - } - - /** - * Set OAuthClientAuthnService. - */ - public void setOAuthClientAuthnService(OAuthClientAuthnService oAuthClientAuthnService) { - this.oAuthClientAuthnService = oAuthClientAuthnService; - IdentityServiceExporter.setOAuthClientAuthnService(oAuthClientAuthnService); - } - - /** - * To get the instance of {@link OAuth2Service}. - * - * @return OAuth2Service - */ - public OAuth2Service getOAuth2Service() { - - return oAuth2Service; - } - - /** - * To set the OAuth2Service. - * - * @param oAuth2Service instance of {@link OAuth2Service} - */ - public void setOAuth2Service(OAuth2Service oAuth2Service) { - - this.oAuth2Service = oAuth2Service; - } - - public void setJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) { - - this.jsFunctionRegistry = jsFunctionRegistry; - } - - public JsFunctionRegistry getJsFunctionRegistry() { - - return jsFunctionRegistry; - } - - public Map getWorkers() { - return workers; - } - - public void addWorker(OpenBankingAuthenticationWorker worker, String workerName) { - this.workers.put(workerName, worker); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/internal/IdentityExtensionsServiceComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/internal/IdentityExtensionsServiceComponent.java deleted file mode 100644 index a1f76804..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/internal/IdentityExtensionsServiceComponent.java +++ /dev/null @@ -1,279 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.identity.app2app.App2AppAuthenticator; -import com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function.OpenBankingAuthenticationWorkerFunction; -import com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function.OpenBankingAuthenticationWorkerFunctionImpl; -import com.wso2.openbanking.accelerator.identity.authenticator.OBIdentifierAuthenticator; -import com.wso2.openbanking.accelerator.identity.claims.OBClaimProvider; -import com.wso2.openbanking.accelerator.identity.claims.RoleClaimProviderImpl; -import com.wso2.openbanking.accelerator.identity.clientauth.OBMutualTLSClientAuthenticator; -import com.wso2.openbanking.accelerator.identity.interceptor.OBIntrospectionDataProvider; -import com.wso2.openbanking.accelerator.identity.keyidprovider.OBKeyIDProvider; -import com.wso2.openbanking.accelerator.identity.listener.TokenRevocationListener; -import com.wso2.openbanking.accelerator.identity.listener.application.OBApplicationManagementListener; -import com.wso2.openbanking.accelerator.throttler.service.OBThrottleService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator; -import org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener; -import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; -import org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor; -import org.wso2.carbon.identity.oauth2.IntrospectionDataProvider; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthenticator; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService; -import org.wso2.carbon.identity.oauth2.keyidprovider.KeyIDProvider; -import org.wso2.carbon.identity.openidconnect.ClaimProvider; -import org.wso2.carbon.identity.openidconnect.RequestObjectService; -import org.wso2.carbon.user.core.service.RealmService; - -/** - * Identity open banking common data holder. - */ -@Component( - name = "com.wso2.openbanking.accelerator.identity.IdentityExtensionsServiceComponent", - immediate = true -) -public class IdentityExtensionsServiceComponent { - - private static Log log = LogFactory.getLog(IdentityExtensionsServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - BundleContext bundleContext = context.getBundleContext(); - log.debug("Registering OB related Identity services."); - bundleContext.registerService(ApplicationMgtListener.class, new OBApplicationManagementListener(), null); - bundleContext.registerService(OAuthClientAuthenticator.class.getName(), - new OBMutualTLSClientAuthenticator(), null); - bundleContext.registerService(ApplicationManagementService.class, ApplicationManagementService.getInstance(), - null); - bundleContext.registerService(ClaimProvider.class.getName(), new OBClaimProvider(), null); - bundleContext.registerService(IntrospectionDataProvider.class.getName(), new OBIntrospectionDataProvider(), - null); - bundleContext.registerService(KeyIDProvider.class.getName(), new OBKeyIDProvider(), null); - bundleContext.registerService(ApplicationAuthenticator.class.getName(), - new OBIdentifierAuthenticator(), null); - bundleContext.registerService(ClaimProvider.class.getName(), new RoleClaimProviderImpl(), null); - bundleContext.registerService(OAuthEventInterceptor.class, new TokenRevocationListener(), null); - App2AppAuthenticator app2AppAuthenticator = new App2AppAuthenticator(); - bundleContext.registerService(ApplicationAuthenticator.class.getName(), - app2AppAuthenticator, null); - - if (IdentityExtensionsDataHolder.getInstance().getJsFunctionRegistry() != null) { - JsFunctionRegistry jsFunctionRegistry = IdentityExtensionsDataHolder.getInstance().getJsFunctionRegistry(); - OpenBankingAuthenticationWorkerFunction worker = new OpenBankingAuthenticationWorkerFunctionImpl(); - jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "OBAuthenticationWorker", - worker); - } - - } - - @Reference( - name = "ApplicationManagementService", - service = ApplicationManagementService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetApplicationManagementService" - ) - protected void setApplicationManagementService(ApplicationManagementService mgtService) { - - IdentityExtensionsDataHolder.getInstance().setApplicationManagementService(mgtService); - } - - protected void unsetApplicationManagementService(ApplicationManagementService mgtService) { - - IdentityExtensionsDataHolder.getInstance().setApplicationManagementService(null); - } - - @Reference( - name = "RequestObjectService", - service = RequestObjectService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRequestObjectService" - ) - protected void setRequestObjectService(RequestObjectService requestObjectService) { - - IdentityExtensionsDataHolder.getInstance().setRequestObjectService(requestObjectService); - } - - protected void unsetRequestObjectService(RequestObjectService requestObjectService) { - - IdentityExtensionsDataHolder.getInstance().setRequestObjectService(null); - } - - @Reference( - service = OAuthAdminServiceImpl.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOauthAdminService" - ) - protected void setOauthAdminService(OAuthAdminServiceImpl oauthAdminService) { - - IdentityExtensionsDataHolder.getInstance().setOauthAdminService(oauthAdminService); - } - - protected void unsetOauthAdminService(OAuthAdminServiceImpl oAuthAdminService) { - - IdentityExtensionsDataHolder.getInstance().setOauthAdminService(null); - } - - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - IdentityExtensionsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - IdentityExtensionsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - @Reference( - name = "realm.service", - service = RealmService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRealmService" - ) - protected void setRealmService(RealmService realmService) { - - log.debug("Setting the Realm Service"); - IdentityExtensionsDataHolder.getInstance().setRealmService(realmService); - } - - protected void unsetRealmService(RealmService realmService) { - - log.debug("UnSetting the Realm Service"); - IdentityExtensionsDataHolder.getInstance().setRealmService(null); - } - - @Reference(name = "open.banking.throttle.service", - service = OBThrottleService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOBThrottleService" - ) - protected void setOBThrottleService(OBThrottleService throttleService) { - - log.debug("OBThrottleService bound to the ob-identifier-authenticator"); - IdentityExtensionsDataHolder.getInstance().setOBThrottleService(throttleService); - } - - protected void unsetOBThrottleService(OBThrottleService throttleService) { - - log.debug("OBThrottleService unbound from the ob-identifier-authenticator"); - IdentityExtensionsDataHolder.getInstance().setOBThrottleService(null); - } - - @Reference( - service = com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConsentCoreService" - ) - public void setConsentCoreService(ConsentCoreService consentCoreService) { - - log.debug("Setting the Consent Core Service"); - IdentityExtensionsDataHolder.getInstance().setConsentCoreService(consentCoreService); - } - - public void unsetConsentCoreService(ConsentCoreService consentCoreService) { - - log.debug("UnSetting the Consent Core Service"); - IdentityExtensionsDataHolder.getInstance().setConsentCoreService(null); - } - - @Reference(name = "oauth.client.authn.service", - service = OAuthClientAuthnService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOAuthClientAuthnService" - ) - protected void setOAuthClientAuthnService(OAuthClientAuthnService oAuthClientAuthnService) { - IdentityExtensionsDataHolder.getInstance().setOAuthClientAuthnService(oAuthClientAuthnService); - } - - protected void unsetOAuthClientAuthnService(OAuthClientAuthnService oAuthClientAuthnService) { - IdentityExtensionsDataHolder.getInstance().setOAuthClientAuthnService(null); - } - - @Reference( - service = OAuth2Service.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOAuth2Service" - ) - public void setOAuth2Service(OAuth2Service oAuth2Service) { - log.debug("Setting the OAuth2 Service"); - IdentityExtensionsDataHolder.getInstance().setOAuth2Service(oAuth2Service); - } - - public void unsetOAuth2Service(OAuth2Service oAuth2Service) { - log.debug("UnSetting the OAuth2 Service"); - IdentityExtensionsDataHolder.getInstance().setOAuth2Service(null); - } - - @Deactivate - protected void deactivate(ComponentContext ctxt) { - - if (IdentityExtensionsDataHolder.getInstance().getJsFunctionRegistry() != null) { - JsFunctionRegistry jsFunctionRegistry = IdentityExtensionsDataHolder.getInstance().getJsFunctionRegistry(); - jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "OBAuthenticationWorker", - null); - } - log.debug("Open banking Key Manager Extensions component is deactivated"); - } - - @Reference( - service = JsFunctionRegistry.class, - cardinality = ReferenceCardinality.OPTIONAL, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetJsFunctionRegistry" - ) - public void setJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) { - - IdentityExtensionsDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistry); - } - - public void unsetJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) { - - IdentityExtensionsDataHolder.getInstance().setJsFunctionRegistry(null); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/keyidprovider/OBKeyIDProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/keyidprovider/OBKeyIDProvider.java deleted file mode 100644 index 1d362066..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/keyidprovider/OBKeyIDProvider.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.keyidprovider; - -import com.nimbusds.jose.JWSAlgorithm; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.keyidprovider.DefaultKeyIDProviderImpl; - -import java.security.cert.Certificate; -import java.util.Optional; - -/** - * OB specific Key ID provider implementation. - */ -public class OBKeyIDProvider extends DefaultKeyIDProviderImpl { - - private static final Log log = LogFactory.getLog(OBKeyIDProvider.class); - - /** - * Method containing the KeyID calculation logic for OB. - * - * @param certificate Signing Certificate. - * @param signatureAlgorithm Signature Algorithm configured. - * @param tenantDomain tenant domain of the user. - * @return Key ID as a String. - * @throws IdentityOAuth2Exception When fail to generate the Key ID. - */ - @Override - public String getKeyId(Certificate certificate, JWSAlgorithm signatureAlgorithm, String tenantDomain) - throws IdentityOAuth2Exception { - - String kid; - Optional primaryCertKid = Optional.ofNullable(IdentityExtensionsDataHolder.getInstance() - .getConfigurationMap().get(IdentityCommonConstants.SIGNING_CERT_KID)); - if (primaryCertKid.isPresent()) { - kid = primaryCertKid.get().toString(); - if (log.isDebugEnabled()) { - log.debug("KID value is configured in the open-banking.xml. Therefore returning configured value :" - + kid + " as the KID"); - } - return kid; - } else { - if (log.isDebugEnabled()) { - log.debug("KID value is not configured in the open-banking.xml Therefore calling the default Key ID " + - "provider implementation"); - } - return super.getKeyId(certificate, signatureAlgorithm, tenantDomain); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/TokenRevocationListener.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/TokenRevocationListener.java deleted file mode 100644 index 2953ce34..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/TokenRevocationListener.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.listener; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth.event.AbstractOAuthEventInterceptor; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO; -import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; -import org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO; - -import java.util.Map; - -/** - * Event listener to revoke consents when access token is revoked. - */ -public class TokenRevocationListener extends AbstractOAuthEventInterceptor { - - private static final Log log = LogFactory.getLog(TokenRevocationListener.class); - private static final ConsentCoreServiceImpl consentCoreService = new ConsentCoreServiceImpl(); - - /** - * Revoke the consent bound to the access token after revoking the access token. - * - * @param revokeRequestDTO - * @param revokeResponseDTO - * @param accessTokenDO - * @param refreshTokenDO - * @param params - * @throws IdentityOAuth2Exception - */ - @Override - @Generated(message = "Excluding from code coverage since it requires a service call") - public void onPostTokenRevocationByClient(OAuthRevocationRequestDTO revokeRequestDTO, - OAuthRevocationResponseDTO revokeResponseDTO, - AccessTokenDO accessTokenDO, - RefreshTokenValidationDataDO refreshTokenDO, - Map params) throws IdentityOAuth2Exception { - - if (!revokeRequestDTO.getoAuthClientAuthnContext().isAuthenticated()) { - return; - } - String consentId = ""; - if (accessTokenDO != null) { - consentId = getConsentIdFromScopes(accessTokenDO.getScope()); - } else if (refreshTokenDO != null) { - consentId = getConsentIdFromScopes(refreshTokenDO.getScope()); - } - if (StringUtils.isNotEmpty(consentId)) { - try { - // Skip consent revocation if the request is from consent revocation flow. - boolean isConsentRevocationFlow = revokeRequestDTO.getoAuthClientAuthnContext().getParameters(). - containsKey(OpenBankingConstants.IS_CONSENT_REVOCATION_FLOW) && (boolean) revokeRequestDTO. - getoAuthClientAuthnContext().getParameter(OpenBankingConstants.IS_CONSENT_REVOCATION_FLOW); - if (!isConsentRevocationFlow) { - consentCoreService.revokeConsentWithReason(consentId, OpenBankingConstants. - DEFAULT_STATUS_FOR_REVOKED_CONSENTS, null, false, "Revoked by token revocation"); - } - } catch (ConsentManagementException e) { - log.error(String.format("Error occurred while revoking consent on token revocation. %s", - e.getMessage().replaceAll("[\r\n]", ""))); - } - } - } - - /** - * Return consent-id when a string array of scopes is given. - * - * @param scopes - * @return - */ - public String getConsentIdFromScopes(String[] scopes) { - - String consentIdClaim = OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.CONSENT_ID_CLAIM_NAME).toString(); - if (scopes != null) { - for (String scope : scopes) { - if (scope.contains(consentIdClaim)) { - return scope.split(consentIdClaim)[1]; - } - } - } - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/AbstractApplicationUpdater.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/AbstractApplicationUpdater.java deleted file mode 100644 index 6317af07..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/AbstractApplicationUpdater.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.listener.application; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; - -import java.util.Map; - -/** - * Abstract class for extending methods to be invoked by the application listener. - */ -public abstract class AbstractApplicationUpdater { - - public abstract void setOauthAppProperties(boolean isRegulatoryApp, OAuthConsumerAppDTO oauthApplication, - Map spMetaData) throws OpenBankingException; - - public abstract void setServiceProviderProperties(boolean isRegulatoryApp, ServiceProvider serviceProvider, - ServiceProviderProperty[] serviceProvideProperties) - throws OpenBankingException; - - public abstract void setAuthenticators(boolean isRegulatoryApp, String tenantDomain, - ServiceProvider serviceProvider, - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig) - throws OpenBankingException; - - public abstract void setConditionalAuthScript (boolean isRegulatoryApp, ServiceProvider serviceProvider, - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig) - throws OpenBankingException; - - public abstract void publishData(Map spMetaData, OAuthConsumerAppDTO oAuthConsumerAppDTO) - throws OpenBankingException; - - public abstract void doPreCreateApplication(boolean isRegulatoryApp, ServiceProvider serviceProvider, - LocalAndOutboundAuthenticationConfig - localAndOutboundAuthenticationConfig, - String tenantDomain, String userName) throws OpenBankingException; - - public abstract void doPostGetApplication(ServiceProvider serviceProvider, String applicationName, - String tenantDomain) throws OpenBankingException; - - public abstract void doPreUpdateApplication(boolean isRegulatoryApp, OAuthConsumerAppDTO oauthApplication, - ServiceProvider serviceProvider, LocalAndOutboundAuthenticationConfig - localAndOutboundAuthenticationConfig, String tenantDomain, - String userName) - throws OpenBankingException; - - public abstract void doPreDeleteApplication(String applicationName, String tenantDomain, String userName) - throws OpenBankingException; - - public abstract void doPostDeleteApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) - throws OpenBankingException; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/ApplicationUpdaterImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/ApplicationUpdaterImpl.java deleted file mode 100644 index 01055137..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/ApplicationUpdaterImpl.java +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.listener.application; - -import com.google.gson.Gson; -import com.wso2.openbanking.accelerator.common.config.TextFileReader; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.AuthenticationStep; -import org.wso2.carbon.identity.application.common.model.IdentityProvider; -import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.model.script.AuthenticationScriptConfig; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; -import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Default implementation class for AbstractApplicationUpdater which should be extended for spec specific. - * tasks - */ -public class ApplicationUpdaterImpl extends AbstractApplicationUpdater { - - private static final Log logger = LogFactory.getLog(ApplicationUpdaterImpl.class); - - public void setOauthAppProperties(boolean isRegulatoryApp, OAuthConsumerAppDTO oauthApplication, - Map spMetaData) throws OpenBankingException { - - } - - public void setServiceProviderProperties(boolean isRegulatoryApp, ServiceProvider serviceProvider, - ServiceProviderProperty[] serviceProvideProperties) - throws OpenBankingException { - - } - - public void setAuthenticators (boolean isRegulatoryApp, String tenantDomain, ServiceProvider serviceProvider, - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig) - throws OpenBankingException { - - IdentityExtensionsDataHolder identityExtensionsDataHolder = IdentityExtensionsDataHolder.getInstance(); - if (isRegulatoryApp) { - - Map configMap = identityExtensionsDataHolder.getConfigurationMap(); - List authSteps = new ArrayList<>(); - - //Read the identity provider from open-banking.xml - String idpName = configMap.get(IdentityCommonConstants.IDENTITY_PROVIDER_NAME) == null - ? null : configMap.get(IdentityCommonConstants.IDENTITY_PROVIDER_NAME).toString(); - String idpStep = configMap.get(IdentityCommonConstants.IDENTITY_PROVIDER_STEP) == null - ? null : configMap.get(IdentityCommonConstants.IDENTITY_PROVIDER_STEP).toString(); - - IdentityProvider configuredIdentityProvider = null; - - if (StringUtils.isNotEmpty(idpName)) { - try { - IdentityProvider[] federatedIdPs = identityExtensionsDataHolder - .getApplicationManagementService().getAllIdentityProviders(tenantDomain); - if (federatedIdPs != null && federatedIdPs.length > 0) { - for (IdentityProvider identityProvider : federatedIdPs) { - if (idpName.equals(identityProvider.getIdentityProviderName())) { - configuredIdentityProvider = identityProvider; - break; - } - } - } - } catch (IdentityApplicationManagementException e) { - throw new OpenBankingException("Error while reading configured Identity providers", e); - } - - } - - if (StringUtils.isNotEmpty(idpStep) && idpStep.equals("1")) { - //Step 1 - Federated Authentication - if (configuredIdentityProvider != null) { - IdentityProvider[] identityProviders = new IdentityProvider[1]; - identityProviders[0] = configuredIdentityProvider; - - AuthenticationStep federatedAuthStep = new AuthenticationStep(); - federatedAuthStep.setStepOrder(1); - federatedAuthStep.setFederatedIdentityProviders(identityProviders); - //set step 1 - authSteps.add(federatedAuthStep); - if (logger.isDebugEnabled()) { - logger.debug("Authentication step 1 added: " + idpName); - } - localAndOutboundAuthenticationConfig.setAuthenticationSteps( - authSteps.toArray(new AuthenticationStep[0])); - } else { - throw new OpenBankingException("Error! An Identity Provider has not been configured."); - } - } else { - //Step 1 - Default basic authentication - LocalAuthenticatorConfig localAuthenticatorConfig = new LocalAuthenticatorConfig(); - LocalAuthenticatorConfig[] localAuthenticatorConfigs = new LocalAuthenticatorConfig[1]; - AuthenticationStep basicAuthenticationStep = new AuthenticationStep(); - - String authenticatorDisplayName = configMap. - get(IdentityCommonConstants.PRIMARY_AUTHENTICATOR_DISPLAYNAME).toString(); - String authenticatorName = configMap.get(IdentityCommonConstants.PRIMARY_AUTHENTICATOR_NAME).toString(); - - localAuthenticatorConfig.setDisplayName(authenticatorDisplayName); - localAuthenticatorConfig.setEnabled(true); - localAuthenticatorConfig.setName(authenticatorName); - localAuthenticatorConfigs[0] = localAuthenticatorConfig; - - basicAuthenticationStep.setStepOrder(1); - basicAuthenticationStep.setLocalAuthenticatorConfigs(localAuthenticatorConfigs); - basicAuthenticationStep.setAttributeStep(true); - basicAuthenticationStep.setSubjectStep(true); - //set step 1 - authSteps.add(basicAuthenticationStep); - - if (logger.isDebugEnabled()) { - logger.debug(String.format("Authentication step 1 added: %s", authenticatorName)); - } - - //Step 2 - federated authentication - if (configuredIdentityProvider != null) { - IdentityProvider[] identityProviders = new IdentityProvider[1]; - identityProviders[0] = configuredIdentityProvider; - - AuthenticationStep federatedAuthStep = new AuthenticationStep(); - federatedAuthStep.setStepOrder(2); - federatedAuthStep.setFederatedIdentityProviders(identityProviders); - //set step 2 - authSteps.add(federatedAuthStep); - if (logger.isDebugEnabled()) { - logger.debug("Authentication step 2 added: " + idpName); - } - } - localAndOutboundAuthenticationConfig.setAuthenticationSteps(authSteps.toArray( - new AuthenticationStep[0])); - } - } - } - - public void setConditionalAuthScript(boolean isRegulatoryApp, ServiceProvider serviceProvider, - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig) - throws OpenBankingException { - - if (isRegulatoryApp) { - if (localAndOutboundAuthenticationConfig.getAuthenticationScriptConfig() == null) { - TextFileReader textFileReader = TextFileReader.getInstance(); - try { - String authScript = textFileReader.readFile - (IdentityCommonConstants.CONDITIONAL_COMMON_AUTH_SCRIPT_FILE_NAME); - if (StringUtils.isNotEmpty(authScript)) { - AuthenticationScriptConfig scriptConfig = new AuthenticationScriptConfig(); - scriptConfig.setContent(authScript); - scriptConfig.setEnabled(true); - localAndOutboundAuthenticationConfig.setAuthenticationScriptConfig(scriptConfig); - } - } catch (IOException e) { - throw new OpenBankingException("Error occurred while reading file", e); - } - - } - } - } - - public void publishData(Map spMetaData, OAuthConsumerAppDTO oAuthConsumerAppDTO) - throws OpenBankingException { - - } - - public void doPreCreateApplication(boolean isRegulatoryApp, ServiceProvider serviceProvider, - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig, - String tenantDomain, String userName) throws OpenBankingException { - - } - - public void doPostGetApplication(ServiceProvider serviceProvider, String applicationName, - String tenantDomain) throws OpenBankingException { - - } - - public void doPreUpdateApplication(boolean isRegulatoryApp, OAuthConsumerAppDTO oauthApplication, - ServiceProvider serviceProvider, LocalAndOutboundAuthenticationConfig - localAndOutboundAuthenticationConfig, String tenantDomain, - String userName) throws OpenBankingException { - - try { - boolean updateAuthenticator = false; - List spProperties = new ArrayList<>(Arrays.asList - (serviceProvider.getSpProperties())); - ServiceProviderProperty appCreateRequest = spProperties.stream() - .filter(serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase("AppCreateRequest")).findAny().orElse(null); - // Authenticators are updated only when creating the app or when an authenticator change - // is made from the IS carbon console - if (appCreateRequest != null) { - updateAuthenticator = Boolean.parseBoolean(appCreateRequest.getValue()); - // Removing the added additional SP property to identify create and update requests - spProperties.remove(appCreateRequest); - serviceProvider.setSpProperties(spProperties.toArray(new ServiceProviderProperty[0])); - } else { - ApplicationManagementService applicationManagementService = IdentityExtensionsDataHolder.getInstance() - .getApplicationManagementService(); - ServiceProvider existingSP = applicationManagementService - .getServiceProvider(serviceProvider.getApplicationID()); - // Checking whether any change have been made in the Local & Outbound Configs of the SP - if (!new Gson().toJson(localAndOutboundAuthenticationConfig).equals(new Gson().toJson(existingSP - .getLocalAndOutBoundAuthenticationConfig()))) { - updateAuthenticator = true; - } - } - - if (localAndOutboundAuthenticationConfig == null) { - localAndOutboundAuthenticationConfig = new LocalAndOutboundAuthenticationConfig(); - } - localAndOutboundAuthenticationConfig.setUseTenantDomainInLocalSubjectIdentifier(true); - localAndOutboundAuthenticationConfig.setUseUserstoreDomainInLocalSubjectIdentifier(true); - - if (updateAuthenticator) { - localAndOutboundAuthenticationConfig.setAuthenticationType("flow"); - setAuthenticators(isRegulatoryApp, tenantDomain, serviceProvider, localAndOutboundAuthenticationConfig); - setConditionalAuthScript(isRegulatoryApp, serviceProvider, localAndOutboundAuthenticationConfig); - } - //update service provider Properties - setServiceProviderProperties(isRegulatoryApp, serviceProvider, serviceProvider.getSpProperties()); - serviceProvider.setLocalAndOutBoundAuthenticationConfig(localAndOutboundAuthenticationConfig); - IdentityExtensionsDataHolder identityExtensionsDataHolder = IdentityExtensionsDataHolder.getInstance(); - Map spMetaData = IdentityCommonUtil.getSpMetaData(serviceProvider); - //update oauth application - setOauthAppProperties(isRegulatoryApp, oauthApplication, spMetaData); - if (StringUtils.isNotBlank(CarbonContext.getThreadLocalCarbonContext().getUsername())) { - identityExtensionsDataHolder.getOauthAdminService().updateConsumerApplication(oauthApplication); - } - publishData(spMetaData, oauthApplication); - } catch (IdentityOAuthAdminException e) { - throw new OpenBankingException("Error occurred while updating application ", e); - } catch (IdentityApplicationManagementException e) { - throw new OpenBankingException("Error occurred while retrieving service provider ", e); - } - } - - public void doPreDeleteApplication(String applicationName, String tenantDomain, String userName) - throws OpenBankingException { - - } - - public void doPostDeleteApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) - throws OpenBankingException { - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/OBApplicationManagementListener.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/OBApplicationManagementListener.java deleted file mode 100644 index 8b27eea6..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/listener/application/OBApplicationManagementListener.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.listener.application; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.mgt.listener.AbstractApplicationMgtListener; -import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; -import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; -import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Application listener. - */ -public class OBApplicationManagementListener extends AbstractApplicationMgtListener { - - private static final Log log = LogFactory.getLog(OBApplicationManagementListener.class); - private IdentityExtensionsDataHolder identityExtensionsDataHolder = IdentityExtensionsDataHolder.getInstance(); - - @Override - public int getDefaultOrderId() { - - return 1000; - } - - @Override - public boolean doPreUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) - throws IdentityApplicationManagementException { - - try { - boolean isRegulatory = false; - List regulatoryIssuerList = new ArrayList<>(); - Object regulatoryIssuers = identityExtensionsDataHolder.getConfigurationMap() - .get(DCRCommonConstants.REGULATORY_ISSUERS); - if (regulatoryIssuers != null) { - if (regulatoryIssuers instanceof List) { - regulatoryIssuerList = (List) regulatoryIssuers; - } else { - regulatoryIssuerList.add(regulatoryIssuers.toString()); - } - } - - List spProperties = new ArrayList<>(Arrays.asList - (serviceProvider.getSpProperties())); - - ServiceProviderProperty ssaIssuerProperty = spProperties.stream() - .filter(serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase("ssaIssuer")).findAny().orElse(null); - - ServiceProviderProperty regulatoryProperty = spProperties.stream() - .filter(serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase(OpenBankingConstants.REGULATORY)).findAny().orElse(null); - - if (ssaIssuerProperty != null) { - String ssaIssuer = ssaIssuerProperty.getValue(); - isRegulatory = regulatoryIssuerList.stream().anyMatch(issuer -> issuer.equals(ssaIssuer)); - } else if (regulatoryProperty != null) { - isRegulatory = Boolean.parseBoolean(regulatoryProperty.getValue()); - } - - //check whether regulatory property is already stored - if (regulatoryProperty == null && isRegulatory) { - - spProperties.add(IdentityCommonUtil.getServiceProviderProperty(OpenBankingConstants.REGULATORY, - "true")); - - } else if (regulatoryProperty == null && !isRegulatory) { - - spProperties.add(IdentityCommonUtil.getServiceProviderProperty(OpenBankingConstants.REGULATORY, - "false")); - - } else if (regulatoryProperty != null && isRegulatory) { - spProperties.remove(regulatoryProperty); - spProperties.add(IdentityCommonUtil.getServiceProviderProperty(OpenBankingConstants.REGULATORY, - "true")); - } - serviceProvider.setSpProperties(spProperties.toArray(new ServiceProviderProperty[0])); - OAuthConsumerAppDTO oAuthConsumerAppDTO; - OAuthAdminServiceImpl oAuthAdminService = identityExtensionsDataHolder.getOauthAdminService(); - - oAuthConsumerAppDTO = oAuthAdminService - .getOAuthApplicationDataByAppName(serviceProvider.getApplicationName()); - oAuthConsumerAppDTO.setTokenType("JWT"); - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = serviceProvider - .getLocalAndOutBoundAuthenticationConfig(); - - identityExtensionsDataHolder.getAbstractApplicationUpdater() - .doPreUpdateApplication(isRegulatory, oAuthConsumerAppDTO, serviceProvider, - localAndOutboundAuthenticationConfig, tenantDomain, userName); - - } catch (OpenBankingException e) { - log.error("Error occurred while updating application.", e); - return false; - } catch (IdentityOAuthAdminException e) { - //returning true here because this error code is returned when there is no oauth app created - //when running integration tests of IS, test cases fail since apps are update before key generation in tests - if ("OAUTH-60002".equals(e.getErrorCode())) { - return true; - } - log.error("Error while retrieving oauth application", e); - return false; - } - return true; - } - - @Override - public boolean doPostGetServiceProvider(ServiceProvider serviceProvider, String applicationName, - String tenantDomain) throws IdentityApplicationManagementException { - - try { - identityExtensionsDataHolder.getAbstractApplicationUpdater() - .doPostGetApplication(serviceProvider, applicationName, tenantDomain); - } catch (OpenBankingException e) { - log.error("Error occurred while updating application.", e); - return false; - } - return true; - - } - - @Override - public boolean doPreDeleteApplication(String applicationName, String tenantDomain, String userName) - throws IdentityApplicationManagementException { - - try { - identityExtensionsDataHolder.getAbstractApplicationUpdater() - .doPreDeleteApplication(applicationName, tenantDomain, userName); - } catch (OpenBankingException e) { - log.error("Error occurred while updating application.", e); - return false; - } - return true; - - } - - @Override - public boolean doPostDeleteApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) - throws IdentityApplicationManagementException { - - try { - identityExtensionsDataHolder.getAbstractApplicationUpdater() - .doPostDeleteApplication(serviceProvider, tenantDomain, userName); - } catch (OpenBankingException e) { - log.error("Error occurred while updating application.", e); - return false; - } - return true; - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/PushAuthRequestValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/PushAuthRequestValidator.java deleted file mode 100644 index bbbbeeb5..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/PushAuthRequestValidator.java +++ /dev/null @@ -1,304 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.constants.PushAuthRequestConstants; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.exception.PushAuthRequestValidatorException; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.model.PushAuthErrorResponse; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util.PushAuthRequestValidatorUtils; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO; - -import java.text.ParseException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import static org.wso2.carbon.identity.openidconnect.model.Constants.JWT_PART_DELIMITER; -import static org.wso2.carbon.identity.openidconnect.model.Constants.NUMBER_OF_PARTS_IN_JWE; - -/** - * The extension class for enforcing OB Push Auth Request Validations. - */ -public class PushAuthRequestValidator { - - private static final Log log = LogFactory.getLog(PushAuthRequestValidator.class); - private static PushAuthRequestValidator pushAuthRequestValidator; - private static final String ERROR_DESCRIPTION = "error_description"; - private static final String ERROR = "error"; - - public static PushAuthRequestValidator getPushAuthRequestValidator() { - - return pushAuthRequestValidator; - } - - public static void setRegistrationValidator(PushAuthRequestValidator pushAuthRequestValidator) { - - PushAuthRequestValidator.pushAuthRequestValidator = pushAuthRequestValidator; - } - - public final Map validateParams(HttpServletRequest request, - Map> parameterMap) - throws PushAuthRequestValidatorException { - - Map parameters = new HashMap<>(); - - for (Map.Entry> paramEntry : parameterMap.entrySet()) { - if (paramEntry.getValue().size() > 1) { - if (log.isDebugEnabled()) { - log.debug("Repeated param found:" + paramEntry.getKey()); - } - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Repeated parameter found in the request"); - } - parameters.put(paramEntry.getKey(), paramEntry.getValue().get(0)); - } - // push auth request cannot contain "request_uri" parameter - if (parameters.containsKey(PushAuthRequestConstants.REQUEST_URI)) { - log.error("Request does not allow request_uri parameter"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Request does not allow request_uri parameter"); - } - JSONObject requestBodyJson; - JSONObject requestHeaderJson; - String requestObjectString; - - // if "request" parameter is available, decode it and put it into parameter map - if (parameters.containsKey(PushAuthRequestConstants.REQUEST)) { - // validate form body when "request" parameter is present - PushAuthRequestValidatorUtils.validateRequestFormBody(parameters); - - try { - String requestParam = parameters.get(PushAuthRequestConstants.REQUEST).toString(); - // check whether request is of type JWE - if (requestParam.split(JWT_PART_DELIMITER).length == NUMBER_OF_PARTS_IN_JWE) { - // decrypt JWE - requestObjectString = PushAuthRequestValidatorUtils.decrypt(requestParam, - parameters.get(PushAuthRequestConstants.CLIENT_ID) != null ? - parameters.get(PushAuthRequestConstants.CLIENT_ID).toString() : null); - } else { - requestObjectString = requestParam; - } - // decode jwt assuming it is a JWS otherwise, it will throw parse exception - requestBodyJson = JWTUtils.decodeRequestJWT(requestObjectString, PushAuthRequestConstants.BODY); - requestHeaderJson = JWTUtils.decodeRequestJWT(requestObjectString, PushAuthRequestConstants.HEADER); - // add to parameters map - parameters.put(PushAuthRequestConstants.DECODED_JWT_BODY, requestBodyJson); - parameters.put(PushAuthRequestConstants.DECODED_JWT_HEADER, requestHeaderJson); - - } catch (ParseException e) { - log.error("Exception while decoding JWT. Returning error.", e); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "Unable to decode JWT.", e); - } - if (requestBodyJson != null && requestHeaderJson != null) { - - validateRedirectUri(requestBodyJson); - - // validate client id and redirect uri - OAuth2ClientValidationResponseDTO oAuth2ClientValidationResponseDTO = - getClientValidationInfo(requestBodyJson); - - if (!oAuth2ClientValidationResponseDTO.isValidClient()) { - log.error(oAuth2ClientValidationResponseDTO.getErrorMsg()); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, - oAuth2ClientValidationResponseDTO.getErrorMsg()); - } - validateSignatureAlgorithm(requestHeaderJson - .get(PushAuthRequestConstants.ALG_HEADER)); - validateSignature(requestObjectString, requestBodyJson); - validateResponseType(requestBodyJson); - validateNonceParameter(requestBodyJson); - validateScope(requestBodyJson); - validateAudience(requestBodyJson); - validateIssuer(requestBodyJson); - validateExpirationTime(requestBodyJson); - validateNotBeforeClaim(requestBodyJson); - validatePKCEParameters(requestBodyJson); - - if (StringUtils.isNotBlank(requestBodyJson.getAsString(PushAuthRequestConstants.REQUEST)) - || StringUtils.isNotBlank(requestBodyJson - .getAsString(PushAuthRequestConstants.REQUEST_URI))) { - log.error("Both request and request_uri parameters are not allowed in the request object"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "Both request and request_uri parameters are not allowed in the request object"); - } - } else { - log.error("Invalid JWT as request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Invalid JWT as request"); - } - } - - // call additional validations from toolkit extensions - validateAdditionalParams(parameters); - return parameters; - } - - /** - * Extend this method to perform additional validations on toolkits. - * - * @param parameters parameter map - */ - public void validateAdditionalParams(Map parameters) throws PushAuthRequestValidatorException { - - } - - /** - * Extend this method to validate the redirect URI of the request object. - * @param requestBodyJson request object - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateRedirectUri(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateRedirectUri(requestBodyJson); - } - - /** - * Extend this method to validate scopes of the request object. - * @param requestBodyJson request object - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateScope(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateScope(requestBodyJson); - } - - /** - * Extend this method to validate signature algorithm of the request object. - * @param algorithm signature algorithm - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateSignatureAlgorithm(Object algorithm) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateSignatureAlgorithm(algorithm); - } - - /** - * Extend this method to validate nonce parameter of the request object. - * @param requestBodyJson request object - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateNonceParameter(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateNonceParameter(requestBodyJson); - } - - /** - * Extend this method to validate issuer of the request object. - * @param requestBodyJson request object - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateIssuer(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateIssuer(requestBodyJson); - } - - /** - * Extend this method to validate expiration time of the request object. - * @param requestBodyJson request object - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateExpirationTime(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateExpirationTime(requestBodyJson); - } - - /** - * Extend this method to validate nbf claim of the request object. - * @param requestBodyJson request object - * @throws PushAuthRequestValidatorException if validation fails - */ - public void validateNotBeforeClaim(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateNotBeforeClaim(requestBodyJson); - } - - /** - * Extend this method to create error response on toolkits. Set necessary status codes and error payloads to - * PushAuthErrorResponse. - * - * @param httpStatusCode Http status code - * @param errorCode Error code - * @param errorDescription Error description - */ - public PushAuthErrorResponse createErrorResponse(int httpStatusCode, String errorCode, String errorDescription) { - - PushAuthErrorResponse pushAuthErrorResponse = new PushAuthErrorResponse(); - JSONObject errorResponse = new JSONObject(); - errorResponse.put(ERROR_DESCRIPTION, errorDescription); - errorResponse.put(ERROR, errorCode); - pushAuthErrorResponse.setPayload(errorResponse); - pushAuthErrorResponse.setHttpStatusCode(httpStatusCode); - - return pushAuthErrorResponse; - } - - @Generated(message = "Excluding from code coverage since it requires a service call") - protected OAuth2ClientValidationResponseDTO getClientValidationInfo(JSONObject requestBodyJson) { - - return new OAuth2Service().validateClientInfo(requestBodyJson.getAsString(PushAuthRequestConstants.CLIENT_ID), - requestBodyJson.getAsString(PushAuthRequestConstants.REDIRECT_URI)); - } - - @Generated(message = "Excluding from code coverage since it requires a service call") - protected void validateSignature(String requestObjectString, JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateSignature(requestObjectString, requestBodyJson); - } - - @Generated(message = "Excluding from code coverage since it requires a service call") - protected void validateAudience(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateAudience(requestBodyJson); - } - - protected void validatePKCEParameters(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validatePKCEParameters(requestBodyJson); - } - - protected void validateResponseType(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - PushAuthRequestValidatorUtils.validateResponseType(requestBodyJson); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/constants/PushAuthRequestConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/constants/PushAuthRequestConstants.java deleted file mode 100644 index 55fd9e4c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/constants/PushAuthRequestConstants.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.constants; - -/** - * Constant class for push auth request. - */ -public class PushAuthRequestConstants { - - // PAR request parameters - public static final String REQUEST = "request"; - public static final String REQUEST_URI = "request_uri"; - public static final String RESPONSE_TYPE = "response_type"; - public static final String NONCE = "nonce"; - public static final String SCOPE = "scope"; - public static final String CODE_CHALLENGE = "code_challenge"; - public static final String CODE_CHALLENGE_METHOD = "code_challenge_method"; - public static final String CLIENT_ID = "client_id"; - public static final String REDIRECT_URI = "redirect_uri"; - - // error constants - public static final String SERVER_ERROR = "server_error"; - public static final String INVALID_REQUEST = "invalid_request"; - public static final String INVALID_REQUEST_OBJECT = "invalid_request_object"; - - // custom jwt body constants - public static final String DECODED_JWT_BODY = "decodedJWTBody"; - public static final String DECODED_JWT_HEADER = "decodedJWTHeader"; - - // jwt constants - public static final String ALG_HEADER = "alg"; - public static final String AUDIENCE = "aud"; - public static final String ISSUER = "iss"; - public static final String EXPIRY = "exp"; - public static final long ONE_HOUR_IN_MILLIS = 3600000; - public static final String NOT_BEFORE = "nbf"; - public static final String ALG_HEADER_NONE = "none"; - - // jwt parts - public static final String BODY = "body"; - public static final String HEADER = "head"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/exception/PushAuthRequestValidatorException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/exception/PushAuthRequestValidatorException.java deleted file mode 100644 index bcc08f33..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/exception/PushAuthRequestValidatorException.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * PAR validation exception. - */ -public class PushAuthRequestValidatorException extends OpenBankingException { - - private String errorDescription; - private String errorCode; - private int httpStatusCode; - - public int getHttpStatusCode() { - - return httpStatusCode; - } - - public void setHttpStatusCode(int httpStatusCode) { - - this.httpStatusCode = httpStatusCode; - } - - public String getErrorDescription() { - - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - - this.errorDescription = errorDescription; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - - public PushAuthRequestValidatorException(int httpStatusCode, String errorCode, String errorDescription, - Throwable e) { - - super(errorDescription, e); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - this.httpStatusCode = httpStatusCode; - - } - - public PushAuthRequestValidatorException(int httpStatusCode, String errorCode, String errorDescription) { - - super(errorDescription); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - this.httpStatusCode = httpStatusCode; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/model/PushAuthErrorResponse.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/model/PushAuthErrorResponse.java deleted file mode 100644 index 37a207e3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/model/PushAuthErrorResponse.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.model; - -import net.minidev.json.JSONObject; - -/** - * Model class for push authorisation error. - */ -public class PushAuthErrorResponse { - - private int httpStatusCode = 0; - private JSONObject payload = null; - - public int getHttpStatusCode() { - - return httpStatusCode; - } - public void setHttpStatusCode(int httpStatusCode) { - - this.httpStatusCode = httpStatusCode; - } - - public JSONObject getPayload() { - - return payload; - } - public void setPayload(JSONObject payload) { - - this.payload = payload; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/PushAuthRequestValidatorUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/PushAuthRequestValidatorUtils.java deleted file mode 100644 index 0513bf17..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/PushAuthRequestValidatorUtils.java +++ /dev/null @@ -1,648 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEObject; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.crypto.RSADecrypter; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jwt.EncryptedJWT; -import com.nimbusds.jwt.PlainJWT; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.constants.PushAuthRequestConstants; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.exception.PushAuthRequestValidatorException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; -import org.wso2.carbon.identity.application.common.model.IdentityProvider; -import org.wso2.carbon.identity.application.common.model.Property; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes; -import org.wso2.carbon.identity.oauth.common.OAuthConstants; -import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; -import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; -import org.wso2.carbon.identity.oauth2.validators.jwt.JWKSBasedJWTValidator; -import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; -import org.wso2.carbon.idp.mgt.IdentityProviderManager; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import java.net.MalformedURLException; -import java.net.URL; -import java.security.Key; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.wso2.carbon.identity.oauth2.util.OAuth2Util.getX509CertOfOAuthApp; -import static org.wso2.carbon.identity.openidconnect.model.Constants.JWKS_URI; -import static org.wso2.carbon.identity.openidconnect.model.Constants.JWT_PART_DELIMITER; -import static org.wso2.carbon.identity.openidconnect.model.Constants.NUMBER_OF_PARTS_IN_JWS; - -/** - * The utility functions required for the push authorization module. - */ -public class PushAuthRequestValidatorUtils { - - private static Log log = LogFactory.getLog(PushAuthRequestValidatorUtils.class); - private static final String OIDC_IDP_ENTITY_ID = "IdPEntityId"; - private static final String OAUTH2_TOKEN_EP_URL = "OAuth2TokenEPUrl"; - private static final String OIDC_ID_TOKEN_ISSUER_ID = "OAuth.OpenIDConnect.IDTokenIssuerID"; - private static final ArrayList ALLOWED_FORM_BODY_PARAMS = new ArrayList() { - { - add("client_id"); - add("client_assertion"); - add("client_assertion_type"); - } - }; - - /** - * Check whether push auth request only contains client_id, client_assertion and client_assertion_type when request - * parameter is present. - */ - public static void validateRequestFormBody(Map parameters) - throws PushAuthRequestValidatorException { - - for (Map.Entry parameter: parameters.entrySet()) { - if (!PushAuthRequestConstants.REQUEST.equalsIgnoreCase(parameter.getKey()) && - !ALLOWED_FORM_BODY_PARAMS.contains(parameter.getKey())) { - log.error("Invalid parameters found in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Invalid parameters found in the request"); - } - } - } - - /** - * Check whether the algorithm used to sign the request object is valid. - */ - public static void validateSignatureAlgorithm(Object algorithm) throws PushAuthRequestValidatorException { - - boolean isValid = false; - if (algorithm != null && StringUtils.isNotBlank((String) algorithm)) { - List allowedAlgorithmsList = new ArrayList<>(); - Object allowedAlgorithms = IdentityExtensionsDataHolder.getInstance() - .getConfigurationMap().get(OpenBankingConstants.SIGNATURE_ALGORITHMS); - if (allowedAlgorithms instanceof List) { - allowedAlgorithmsList = (List) allowedAlgorithms; - } else { - allowedAlgorithmsList.add(allowedAlgorithms.toString()); - } - isValid = allowedAlgorithmsList.isEmpty() || allowedAlgorithmsList.contains(algorithm); - } - if (!isValid) { - log.error("Invalid request object signing algorithm"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "Invalid request object signing algorithm"); - } - - } - - /** - * Checks whether the given authentication flow requires nonce as a mandatory parameter. - */ - public static boolean isNonceMandatory(String responseType) { - - // nonce parameter is required for the OIDC hybrid flow and implicit flow grant types requesting ID_TOKEN. - return Arrays.stream(responseType.split("\\s+")).anyMatch(OAuthConstants.ID_TOKEN::equals); - } - - /** - * Validates the nonce parameter as mandatory. - */ - public static void validateNonceParameter(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - if (StringUtils.isNotBlank(requestBodyJson.getAsString(PushAuthRequestConstants.RESPONSE_TYPE))) { - if (isNonceMandatory(requestBodyJson.getAsString(PushAuthRequestConstants.RESPONSE_TYPE)) && - requestBodyJson.getAsString(PushAuthRequestConstants.NONCE) == null) { - log.error("Invalid Nonce parameter in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Invalid Nonce parameter in the request"); - } - } - } - - /** - * Validates the mandatory PKCE parameters. - */ - public static void validatePKCEParameters(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - if (StringUtils.isEmpty(requestBodyJson.getAsString(PushAuthRequestConstants.CODE_CHALLENGE))) { - log.error("Mandatory parameter code_challenge, not found in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "Mandatory parameter code_challenge, not found in the request"); - } - - if (StringUtils.isEmpty(requestBodyJson.getAsString(PushAuthRequestConstants.CODE_CHALLENGE_METHOD))) { - log.error("Mandatory parameter code_challenge_method, not found in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "Mandatory parameter code_challenge_method, not found in the request"); - } - } - - /** - * Validates the mandatory response_type parameter. - */ - public static void validateResponseType(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - if (StringUtils.isEmpty(requestBodyJson.getAsString(PushAuthRequestConstants.RESPONSE_TYPE))) { - log.error("Mandatory parameter response_type, not found in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "Mandatory parameter response_type, not found in the request"); - } - } - - /** - * Validates the redirect URI parameter to verify if the parameter is available and not null. - */ - public static void validateRedirectUri(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - if (StringUtils.isBlank(requestBodyJson.getAsString(PushAuthRequestConstants.REDIRECT_URI))) { - log.error("Mandatory parameter redirect_uri, not found in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, - "Mandatory parameter redirect_uri, not found in the request"); - } - } - - /** - * Validates the scope parameter to verify only allowed scopes for the application are passed in the request. - */ - public static void validateScope(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - if (StringUtils.isNotBlank(requestBodyJson.getAsString(PushAuthRequestConstants.SCOPE))) { - - List requestedScopes = Arrays.asList(requestBodyJson.getAsString(PushAuthRequestConstants.SCOPE) - .split("\\s+")); - - List allowedScopes; - try { - allowedScopes = Arrays.asList(new IdentityCommonHelper() - .getAppPropertyFromSPMetaData(requestBodyJson.getAsString(PushAuthRequestConstants.CLIENT_ID), - IdentityCommonConstants.SCOPE).split("\\s+")); - } catch (OpenBankingException e) { - log.error("Error while retrieving sp meta data", e); - throw new PushAuthRequestValidatorException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - PushAuthRequestConstants.SERVER_ERROR, "Error while retrieving sp meta data", e); - } - - for (String scope : requestedScopes) { - if (!allowedScopes.contains(scope)) { - log.error("Invalid scopes in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Invalid scopes in the request"); - } - } - } else { - log.error("Mandatory parameter scope, not found in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, - "Mandatory parameter scope, not found in the request"); - } - } - - /** - * Validates the audience parameter to check whether it matches any supported audience value. - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public static void validateAudience(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - String clientId = requestBodyJson.getAsString(PushAuthRequestConstants.CLIENT_ID); - Object audValue = requestBodyJson.get(PushAuthRequestConstants.AUDIENCE); - boolean isValid = false; - - if (audValue == null) { - log.error("aud parameter is missing in the request object"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "aud parameter is missing in the request object"); - } - - List validAudUrls = getAllowedPARAudienceValues(getSPTenantDomainFromClientId(clientId)); - - if (audValue instanceof String) { - // If the aud value is a string, check whether it is equal to the allowed audience value. - isValid = validAudUrls.contains(audValue); - } else if (audValue instanceof JSONArray) { - // If the aud value is an array, check whether it is equal to one of the allowed audience values. - JSONArray audArray = (JSONArray) audValue; - for (Object aud : audArray) { - if (validAudUrls.contains(aud)) { - isValid = true; - break; - } - } - } - - if (!isValid) { - log.error("Invalid audience value in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "Invalid audience value in the request"); - } - } - - /** - * Validates the issuer parameter to check whether its similar to the client id. - */ - public static void validateIssuer(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - String issuer = requestBodyJson.getAsString(PushAuthRequestConstants.ISSUER); - String clientId = requestBodyJson.getAsString(PushAuthRequestConstants.CLIENT_ID); - boolean isValid = false; - - if (StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(clientId)) { - isValid = issuer.equals(clientId); - } - if (!isValid) { - log.error("Invalid issuer in the request"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "Invalid issuer in the request"); - } - } - - - /** - * Validates the expiration status of the request object. - */ - public static void validateExpirationTime(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - String exp = requestBodyJson.getAsString(PushAuthRequestConstants.EXPIRY); - - if (StringUtils.isNotBlank(exp)) { - Date expirationTime = new Date(Integer.parseInt(exp) * 1000L); - long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000; - long expirationTimeInMillis = expirationTime.getTime(); - long currentTimeInMillis = System.currentTimeMillis(); - // exp parameter should not be over 1 hour in the future. - if ((expirationTimeInMillis - (currentTimeInMillis + timeStampSkewMillis)) > - PushAuthRequestConstants.ONE_HOUR_IN_MILLIS) { - log.error("exp parameter in the request object is over 1 hour in the future"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "exp parameter in the request object " + - "is over 1 hour in the future"); - } - // exp parameter should not be in the past. - if ((currentTimeInMillis + timeStampSkewMillis) > expirationTimeInMillis) { - log.error("Request object expired"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, "Request object expired"); - } - } else { - log.error("exp parameter is missing in the request object"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "exp parameter is missing in the request object"); - } - } - - /** - * Validates the nbf claim in the request object. - */ - public static void validateNotBeforeClaim(JSONObject requestBodyJson) throws PushAuthRequestValidatorException { - - String nbf = requestBodyJson.getAsString(PushAuthRequestConstants.NOT_BEFORE); - - if (StringUtils.isNotBlank(nbf)) { - Date notBeforeTime = new Date(Integer.parseInt(nbf) * 1000L); - long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000; - long notBeforeTimeInMillis = notBeforeTime.getTime(); - long currentTimeInMillis = System.currentTimeMillis(); - //request object should be used on or after nbf value. - if ((currentTimeInMillis + timeStampSkewMillis) < notBeforeTimeInMillis) { - log.error("Request object is not valid yet"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "Request object is not valid yet"); - } - // nbf parameter should not be over 1 hour in the past. - if (((currentTimeInMillis + timeStampSkewMillis) - notBeforeTimeInMillis) > - PushAuthRequestConstants.ONE_HOUR_IN_MILLIS) { - log.error("nbf parameter in the request object is over 1 hour in the past"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, "nbf parameter in the request object " + - "is over 1 hour in the past"); - } - } else { - log.error("nbf parameter is missing in the request object"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, - "nbf parameter is missing in the request object"); - } - } - - /** - * Validates signature of the request object. - */ - @Generated(message = "Excluding from code coverage since it requires several service calls") - public static void validateSignature(String requestObject, JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - String jwksUri = null; - ServiceProviderProperty[] spProperties = null; - - // Get Service provider properties - try { - spProperties = OAuth2Util.getServiceProvider(requestBodyJson - .getAsString(PushAuthRequestConstants.CLIENT_ID)).getSpProperties(); - } catch (IdentityOAuth2Exception exception) { - log.error("Unable to extract Service Provider Properties", exception); - throw new PushAuthRequestValidatorException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - PushAuthRequestConstants.SERVER_ERROR, exception.getMessage(), exception); - } - - // Extract JWKS Uri from properties - if (spProperties != null) { - for (ServiceProviderProperty spProperty : spProperties) { - if (JWKS_URI.equals(spProperty.getName())) { - jwksUri = spProperty.getValue(); - } - } - } - if (log.isDebugEnabled()) { - log.debug("Retrieved JWKS URI: " + jwksUri); - } - - SignedJWT jwt; - - try { - jwt = SignedJWT.parse(requestObject); - } catch (ParseException exception) { - log.error("Unable to parse JWT object", exception); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, exception.getMessage(), exception); - } - - boolean isVerified = false; - - if (StringUtils.isBlank(jwksUri)) { - log.debug("Validating from certificate"); - String tenantDomain = getSPTenantDomainFromClientId(requestBodyJson - .getAsString(PushAuthRequestConstants.CLIENT_ID)); - - // Validate from Certificate Content - Certificate certificate; - try { - certificate = getX509CertOfOAuthApp(requestBodyJson - .getAsString(PushAuthRequestConstants.CLIENT_ID), tenantDomain); - } catch (IdentityOAuth2Exception exception) { - log.error("Unable to get certificate from app", exception); - throw new PushAuthRequestValidatorException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - PushAuthRequestConstants.SERVER_ERROR, exception.getMessage(), exception); - } - - isVerified = isSignatureVerified(jwt, certificate); - } else { - log.debug("Validating from JWKS URI"); - - // Validate from JWKS Uri - String alg = jwt.getHeader().getAlgorithm().getName(); - Map options = new HashMap<>(); - try { - isVerified = new JWKSBasedJWTValidator().validateSignature(jwt.getParsedString(), jwksUri, - alg, options); - } catch (IdentityOAuth2Exception exception) { - log.error("Unable to validate JWT using JWKS URL", exception); - String errorMessage = getCustomSignatureValidationErrorMessage(exception); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST_OBJECT, errorMessage, exception); - } - } - if (!isVerified) { - log.error("Request object signature validation failed"); - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, - PushAuthRequestConstants.INVALID_REQUEST, - "Request object signature validation failed"); - } - } - - /** - * Validate signature of a sign JWT against a given certificate. - */ - @Generated(message = "Excluding from code coverage since it requires several service calls") - private static boolean isSignatureVerified(SignedJWT signedJWT, Certificate x509Certificate) { - JWSHeader header = signedJWT.getHeader(); - if (x509Certificate == null) { - if (log.isDebugEnabled()) { - log.debug("Unable to locate certificate for JWT " + header.toString()); - } - return false; - } else { - String alg = signedJWT.getHeader().getAlgorithm().getName(); - if (log.isDebugEnabled()) { - log.debug("Signature Algorithm found in the JWT Header: " + alg); - } - - // allowed RS and PS for the moment - if (alg.indexOf("RS") != 0 && alg.indexOf("PS") != 0) { - if (log.isDebugEnabled()) { - log.debug("Signature Algorithm not supported yet : " + alg); - } - return false; - } else { - PublicKey publicKey = x509Certificate.getPublicKey(); - if (publicKey instanceof RSAPublicKey) { - RSASSAVerifier verifier = new RSASSAVerifier((RSAPublicKey) publicKey); - - try { - return signedJWT.verify(verifier); - } catch (JOSEException e) { - if (log.isDebugEnabled()) { - log.debug("Unable to verify the signature of the request object: " + signedJWT.serialize()); - } - return false; - } - } else { - log.debug("Public key is not an RSA public key."); - return false; - } - } - } - } - - /** - * Return the alias of the resident IDP (issuer of Authorization Server), PAR Endpoint and Token Endpoint - * to validate the audience value of the PAR Request Object. - */ - @Generated(message = "Excluding from code coverage since it requires several service calls") - private static List getAllowedPARAudienceValues(String tenantDomain) - throws PushAuthRequestValidatorException { - - List validAudUrls = new ArrayList<>(); - String residentIdpAlias = StringUtils.EMPTY; - IdentityProvider residentIdP; - try { - residentIdP = IdentityProviderManager.getInstance().getResidentIdP(tenantDomain); - FederatedAuthenticatorConfig oidcFedAuthn = IdentityApplicationManagementUtil - .getFederatedAuthenticator(residentIdP.getFederatedAuthenticatorConfigs(), - IdentityApplicationConstants.Authenticator.OIDC.NAME); - - Property idPEntityIdProperty = - IdentityApplicationManagementUtil.getProperty(oidcFedAuthn.getProperties(), OIDC_IDP_ENTITY_ID); - if (idPEntityIdProperty != null) { - residentIdpAlias = idPEntityIdProperty.getValue(); - if (log.isDebugEnabled()) { - log.debug("Found IdPEntityID: " + residentIdpAlias + " for tenantDomain: " + tenantDomain); - } - } - - Property oAuth2TokenEPUrlProperty = - IdentityApplicationManagementUtil.getProperty(oidcFedAuthn.getProperties(), OAUTH2_TOKEN_EP_URL); - if (oAuth2TokenEPUrlProperty != null) { - // add Token EP Url as a valid "aud" value - validAudUrls.add(oAuth2TokenEPUrlProperty.getValue()); - if (log.isDebugEnabled()) { - log.debug("Found OAuth2TokenEPUrl: " + oAuth2TokenEPUrlProperty.getValue() + - " for tenantDomain: " + tenantDomain); - } - } - } catch (IdentityProviderManagementException e) { - log.error("Error while loading OAuth2TokenEPUrl of the resident IDP of tenant:" + tenantDomain, e); - throw new PushAuthRequestValidatorException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - OAuth2ErrorCodes.SERVER_ERROR, "Server Error while validating audience " + - "of Request Object.", e); - } - - if (StringUtils.isEmpty(residentIdpAlias)) { - residentIdpAlias = IdentityUtil.getProperty(OIDC_ID_TOKEN_ISSUER_ID); - if (StringUtils.isNotEmpty(residentIdpAlias)) { - if (log.isDebugEnabled()) { - log.debug("'IdPEntityID' property was empty for tenantDomain: " + tenantDomain + ". Using " + - "OIDC IDToken Issuer value: " + residentIdpAlias + " as alias to identify Resident IDP."); - } - } - } - - // add IdPEntityID or the "issuer" as a valid "aud" value - validAudUrls.add(residentIdpAlias); - - try { - URL residentIdPUrl = new URL(residentIdpAlias); - // derive PAR EP URL from the residentIdP base URL - URL parEpUrl = new URL(residentIdPUrl, IdentityCommonConstants.PAR_ENDPOINT); - // add PAR EP URL as a valid "aud" value - validAudUrls.add(parEpUrl.toString()); - } catch (MalformedURLException exception) { - log.error("Error occurred while deriving PAR endpoint URL.", exception); - throw new PushAuthRequestValidatorException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - OAuth2ErrorCodes.SERVER_ERROR, "Server Error while deriving PAR endpoint URL.", exception); - } - - return validAudUrls; - } - - /** - * Return the tenant domain for a given client. - */ - public static String getSPTenantDomainFromClientId(String clientId) { - - try { - OAuthAppDO oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId); - return OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO); - } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) { - return MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; - } - } - - /** - * Decrypt an encrypted request object. - */ - public static String decrypt(String requestObject, String clientId) throws PushAuthRequestValidatorException { - EncryptedJWT encryptedJWT; - try { - encryptedJWT = EncryptedJWT.parse(requestObject); - RSAPrivateKey rsaPrivateKey = getRSAPrivateKey(clientId); - RSADecrypter decrypter = new RSADecrypter(rsaPrivateKey); - encryptedJWT.decrypt(decrypter); - - JWEObject jweObject = JWEObject.parse(requestObject); - jweObject.decrypt(decrypter); - - if (jweObject.getPayload() != null && jweObject.getPayload().toString() - .split(JWT_PART_DELIMITER).length == NUMBER_OF_PARTS_IN_JWS) { - return jweObject.getPayload().toString(); - } else { - return new PlainJWT(encryptedJWT.getJWTClaimsSet()).serialize(); - } - - } catch (JOSEException | IdentityOAuth2Exception | ParseException e) { - String errorMessage = "Failed to decrypt Request Object"; - if (log.isDebugEnabled()) { - log.debug(errorMessage + " from " + requestObject, e); - } - throw new PushAuthRequestValidatorException(HttpStatus.SC_BAD_REQUEST, "invalid_request", errorMessage, e); - } - } - - /** - * Get RSA private key from tenant domain for registered client. - */ - private static RSAPrivateKey getRSAPrivateKey(String clientId) throws IdentityOAuth2Exception { - - String tenantDomain = PushAuthRequestValidatorUtils.getSPTenantDomainFromClientId(clientId); - int tenantId = OAuth2Util.getTenantId(tenantDomain); - Key key = OAuth2Util.getPrivateKey(tenantDomain, tenantId); - return (RSAPrivateKey) key; - } - - /** - * Get custom error message for signature validation errors. - */ - private static String getCustomSignatureValidationErrorMessage(IdentityOAuth2Exception exception) { - - String errorMessage = exception.getCause().getMessage(); - if (StringUtils.isEmpty(errorMessage)) { - return exception.getMessage(); - } - - if (errorMessage.equalsIgnoreCase("JWT before use time")) { - return "Invalid not before time. 'nbf' must be a past value."; - } - - if (errorMessage.equalsIgnoreCase("Expired JWT")) { - return "Invalid expiry time. 'exp' claim must be a future value."; - } - - return errorMessage; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/sp/metadata/extension/SPMetadataFilter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/sp/metadata/extension/SPMetadataFilter.java deleted file mode 100644 index a3b26111..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/sp/metadata/extension/SPMetadataFilter.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.sp.metadata.extension; - -import java.util.Map; - -/** - * The interface to define how the service provider metadata filter extension should be implemented. - */ -public interface SPMetadataFilter { - - /** - * Filter logic for metadata map. - * @param metadata - * @return - */ - Map filter(Map metadata); - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/sp/metadata/extension/impl/DefaultSPMetadataFilter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/sp/metadata/extension/impl/DefaultSPMetadataFilter.java deleted file mode 100644 index 6d539fbc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/sp/metadata/extension/impl/DefaultSPMetadataFilter.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.sp.metadata.extension.impl; - -import com.google.common.collect.ImmutableMap; -import com.wso2.openbanking.accelerator.identity.sp.metadata.extension.SPMetadataFilter; - -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Impl of the SPMetadataFilterInterface. - */ -public class DefaultSPMetadataFilter implements SPMetadataFilter { - - @Override - public Map filter(Map metadata) { - - // Ex: ("client_name", "software_client_name"), property will read as "software_client_name" from metadata - // and put as "client_name" - Map propertiesVsMappingName = ImmutableMap.of( - "client_name", "client_name", - "software_client_name", "software_client_name", - "software_id", "software_id", - "logo_uri", "logo_uri", - "org_name", "org_name" - ); - - return propertiesVsMappingName.entrySet().stream() - .collect(Collectors.toMap( - Map.Entry::getKey, - e -> metadata.getOrDefault(e.getValue(), "") - )); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/DefaultTokenFilter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/DefaultTokenFilter.java deleted file mode 100644 index fe85498d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/DefaultTokenFilter.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -/** - * Default token filter class to represent the abstract implementation. - */ -public class DefaultTokenFilter { - - private static final Log log = LogFactory.getLog(DefaultTokenFilter.class); - - /** - * Handle filter request. - * - * @param request - * @return ServletRequest - * @throws ServletException - */ - public ServletRequest handleFilterRequest(ServletRequest request) throws ServletException { - return request; - } - - /** - * Handle filter response. - * - * @param response - * @return ServletResponse - * @throws ServletException - */ - public ServletResponse handleFilterResponse(ServletResponse response) throws ServletException { - - return response; - } - - /** - * Respond when there is a failure in filter validation. - * - * @param response HTTP servlet response object - * @param status HTTP status code - * @param error error - * @param errorMessage error description - * @throws IOException - */ - public void handleValidationFailure(HttpServletResponse response, int status, String error, String errorMessage) - throws IOException { - - JSONObject errorJSON = new JSONObject(); - errorJSON.put(IdentityCommonConstants.OAUTH_ERROR, error); - errorJSON.put(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION, errorMessage); - - try (OutputStream outputStream = response.getOutputStream()) { - response.setStatus(status); - response.setContentType(MediaType.APPLICATION_JSON); - outputStream.write(errorJSON.toString().getBytes(StandardCharsets.UTF_8)); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/TokenFilter.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/TokenFilter.java deleted file mode 100644 index f744ad05..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/TokenFilter.java +++ /dev/null @@ -1,298 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token; - -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; -import com.wso2.openbanking.accelerator.identity.token.validators.OBIdentityFilterValidator; -import com.wso2.openbanking.accelerator.identity.token.wrapper.RequestWrapper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; -import java.util.Optional; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Filter engaged for /token request. - */ -public class TokenFilter implements Filter { - - private static final Log log = LogFactory.getLog(TokenFilter.class); - private static DefaultTokenFilter defaultTokenFilter; - private String clientId = null; - private static List validators = new ArrayList<>(); - - private static final String BASIC_AUTH_ERROR_MSG = "Unable to find client id in the request. " + - "Invalid Authorization header found."; - - @Generated(message = "Ignoring because it's a the init method") - @Override - public void init(FilterConfig filterConfig) { - - ServletContext context = filterConfig.getServletContext(); - context.log("TokenFilter initialized"); - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - - try { - clientId = this.extractClientId(request); - } catch (TokenFilterException e) { - getDefaultTokenFilter().handleValidationFailure((HttpServletResponse) response, e.getErrorCode(), - e.getMessage(), e.getErrorDescription()); - return; - } - - try { - request = cleanClientCertificateAndAppendTransportHeader(request); - if (IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId)) { - request = appendTransportHeader(request, response); - request = getDefaultTokenFilter().handleFilterRequest(request); - for (OBIdentityFilterValidator validator : getValidators()) { - validator.validate(request, clientId); - } - response = getDefaultTokenFilter().handleFilterResponse(response); - } - chain.doFilter(request, response); - } catch (TokenFilterException e) { - getDefaultTokenFilter().handleValidationFailure((HttpServletResponse) response, - e.getErrorCode(), e.getMessage(), e.getErrorDescription()); - } catch (CertificateEncodingException e) { - throw new ServletException("Certificate not valid", e); - } catch (OpenBankingException e) { - if (e.getMessage().contains("Error occurred while retrieving OAuth2 application data")) { - getDefaultTokenFilter().handleValidationFailure((HttpServletResponse) response, - HttpServletResponse.SC_INTERNAL_SERVER_ERROR, IdentityCommonConstants - .OAUTH2_INTERNAL_SERVER_ERROR, "OAuth2 application data retrieval failed." - + e.getMessage()); - } else { - getDefaultTokenFilter().handleValidationFailure((HttpServletResponse) response, - HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants.OAUTH2_INVALID_REQUEST_MESSAGE, - "Service provider metadata retrieval failed. " + e.getMessage()); - } - } - } - - /** - * Append the transport header to the request. - * - * @param request - * @param response - * @return ServletRequest - * @throws ServletException - */ - private ServletRequest appendTransportHeader(ServletRequest request, ServletResponse response) throws - ServletException, IOException, CertificateEncodingException { - - if (request instanceof HttpServletRequest) { - Object certAttribute = request.getAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE); - String x509Certificate = ((HttpServletRequest) request).getHeader(IdentityCommonUtil.getMTLSAuthHeader()); - if (new IdentityCommonHelper().isTransportCertAsHeaderEnabled() && x509Certificate != null) { - return request; - } else if (certAttribute != null) { - RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request); - X509Certificate certificate = IdentityCommonUtil.getCertificateFromAttribute(certAttribute); - requestWrapper.setHeader(IdentityCommonUtil.getMTLSAuthHeader(), - new IdentityCommonHelper().encodeCertificateContent(certificate)); - return requestWrapper; - } else { - getDefaultTokenFilter().handleValidationFailure((HttpServletResponse) response, - HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants.OAUTH2_INVALID_REQUEST_MESSAGE, - "Transport certificate not found in the request"); - } - } else { - throw new ServletException("Error occurred when handling the request, passed request is not a " + - "HttpServletRequest"); - } - return request; - } - - /** - * Invoked after all execution of the filter has completed and the filter is being taken out of service. - */ - @Generated(message = "Ignoring because it's a clean up code") - @Override - public void destroy() { - // No special cleanup is required in this filter. - } - - /** - * @return Token filter - */ - @Generated(message = "Ignoring because the method is reading the configuration") - public DefaultTokenFilter getDefaultTokenFilter() { - - return defaultTokenFilter; - } - - /** - * Extracts the client id from the request parameter or from the assertion. - * - * @param request servlet request containing the request data - * @return clientId - * @throws ParseException - */ - private String extractClientId(ServletRequest request) throws TokenFilterException { - - try { - Optional signedObject = - Optional.ofNullable(request.getParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION)); - Optional clientIdAsReqParam = - Optional.ofNullable(request.getParameter(IdentityCommonConstants.CLIENT_ID)); - if (signedObject.isPresent()) { - SignedJWT signedJWT = SignedJWT.parse(signedObject.get()); - return signedJWT.getJWTClaimsSet().getIssuer(); - } else if (clientIdAsReqParam.isPresent()) { - return clientIdAsReqParam.get(); - } else if (((HttpServletRequest) request).getHeader("Authorization") != null) { - // This added condition will only affect the requests with Basic Authentication and the others will be - // handled by the above conditions as previously. - String authorizationHeader = ((HttpServletRequest) request).getHeader("Authorization"); - if (authorizationHeader.split(" ").length == 2) { - String authToken = ((HttpServletRequest) request).getHeader("Authorization").split(" ")[1]; - byte[] decodedBytes = Base64.getUrlDecoder().decode(authToken.getBytes(StandardCharsets.UTF_8)); - String decodedAuthToken = new String(decodedBytes, StandardCharsets.UTF_8); - if (decodedAuthToken.split(":").length == 2) { - return decodedAuthToken.split(":")[0]; - } else { - log.error(BASIC_AUTH_ERROR_MSG); - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, - "Could not retrieve Client ID", BASIC_AUTH_ERROR_MSG); - } - } else { - log.error(BASIC_AUTH_ERROR_MSG); - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, "Could not retrieve Client ID", - BASIC_AUTH_ERROR_MSG); - } - } else { - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, "Unable to find client id in the request"); - } - } catch (ParseException e) { - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, "Error occurred while parsing the signed assertion", e); - } - } - - public static void setDefaultTokenFilter(DefaultTokenFilter tokenFilter) { - - defaultTokenFilter = tokenFilter; - } - - public static void setValidators(List validators) { - - TokenFilter.validators = validators; - } - - public List getValidators() { - - return validators; - } - - /** - * validates the transport header certificate and re-add to the header. - * - * @param request ServletRequest - * @return request - * @throws OpenBankingException - * @throws ServletException - */ - private ServletRequest cleanClientCertificateAndAppendTransportHeader(ServletRequest request) - throws ServletException, OpenBankingException { - - if (request instanceof HttpServletRequest) { - IdentityCommonHelper identityCommonHelper = new IdentityCommonHelper(); - if (identityCommonHelper.isTransportCertAsHeaderEnabled()) { - log.debug("Retrieving client transport certificate from header."); - String x509Certificate = ((HttpServletRequest) request) - .getHeader(IdentityCommonUtil.getMTLSAuthHeader()); - if (StringUtils.isNotEmpty(x509Certificate) && isClientCertificateEncoded()) { - try { - log.debug("Received encoded client certificate. URLDecoding cert."); - x509Certificate = URLDecoder.decode(x509Certificate, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new OpenBankingException("Cannot decode the transport certificate passed through " + - "the request", e); - } - } - - try { - X509Certificate certificate = CertificateUtils.parseCertificate(x509Certificate); - if (certificate != null) { - RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request); - requestWrapper.setHeader(IdentityCommonUtil.getMTLSAuthHeader(), - new IdentityCommonHelper().encodeCertificateContent(certificate)); - return requestWrapper; - } - } catch (CertificateEncodingException e) { - throw new ServletException("Certificate not valid", e); - } catch (OpenBankingException e) { - // Ignore the error here, MTLSEnforcementValidator will validate the certificate - log.error("Invalid transport certificate received. Caused by, ", e); - } - } - } else { - throw new ServletException("Error occurred when handling the request, passed request is not a " + - "HttpServletRequest"); - } - return request; - } - - /** - * Get the clientCertificateEncode configuration. - * - * @return false if clientCertificateEncode configured as false, default true - */ - public boolean isClientCertificateEncoded() { - - Object isClientCertEncoded = IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .getOrDefault(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, true); - - return Boolean.parseBoolean(String.valueOf(isClientCertEncoded)); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/util/TokenFilterException.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/util/TokenFilterException.java deleted file mode 100644 index 008f5c71..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/util/TokenFilterException.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * Token filter exception. - */ -public class TokenFilterException extends OpenBankingException { - - private String errorDescription; - private int errorCode; - - public TokenFilterException(int errorCode, String error, String errorDescription, Throwable e) { - - super(error, e); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - } - - public TokenFilterException(int errorCode, String error, String errorDescription) { - - super(error); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - } - - public TokenFilterException(String message, Throwable e) { - - super(message, e); - } - - public String getErrorDescription() { - - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - - this.errorDescription = errorDescription; - } - - public int getErrorCode() { - - return errorCode; - } - - public void setErrorCode(int errorCode) { - - this.errorCode = errorCode; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/ClientAuthenticatorValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/ClientAuthenticatorValidator.java deleted file mode 100644 index 0a3983b0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/ClientAuthenticatorValidator.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; -import com.wso2.openbanking.accelerator.identity.util.ClientAuthenticatorEnum; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Validates whether the registered client authentication method is invoked. - */ -public class ClientAuthenticatorValidator implements OBIdentityFilterValidator { - - private static final Log log = LogFactory.getLog(ClientAuthenticatorValidator.class); - - @Override - public void validate(ServletRequest request, String clientId) throws TokenFilterException, ServletException { - - if (request instanceof HttpServletRequest) { - String registeredClientAuthMethod = retrieveRegisteredAuthMethod(clientId); - - if (registeredClientAuthMethod.equals(IdentityCommonConstants.NOT_APPLICABLE)) { - return; - } - - // There can be multiple registered client auth methods - if (!(registeredClientAuthMethod.contains(retrieveRequestAuthMethod(request)))) { - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, "Request does not follow the registered token endpoint auth " + - "method " + registeredClientAuthMethod); - } - } else { - throw new ServletException("Error occurred during request validation, passed request is not a " + - "HttpServletRequest"); - } - } - - /** - * Get the authentication method that matches the request. - * - * @param request servlet request - * @return authentication method - */ - @Generated(message = "Excluding from code coverage because a the actual implementation test cases are coverd") - public String retrieveRequestAuthMethod(ServletRequest request) throws TokenFilterException { - - try { - if (isPrivateKeyJWTAuthentication(request)) { - log.debug("Validating request with JWT client authentication method"); - return ClientAuthenticatorEnum.PRIVATE_KEY_JWT.toString(); - } else if (new IdentityCommonHelper().isMTLSAuthentication(request)) { - log.debug("Validating request with MTLS client authentication method"); - return ClientAuthenticatorEnum.TLS_CLIENT_AUTH.toString(); - } - return "INVALID_AUTH"; - } catch (OpenBankingException e) { - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, e.getMessage()); - } - } - - /** - * Validate whether the request follows the private key jwt authentication pattern. - * - * @param request servlet request - * @return whether request fallows PKJWT pattern - */ - public boolean isPrivateKeyJWTAuthentication(ServletRequest request) { - - String oauthJWTAssertionType = request.getParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE); - String oauthJWTAssertion = request.getParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION); - return IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(oauthJWTAssertionType) && - StringUtils.isNotEmpty(oauthJWTAssertion); - } - - /** - * Retrieve client authentication method from sp metadata. - * - * @param clientId auth client ID - * @return the value of the client authentication method registered - * @throws TokenFilterException - */ - @Generated(message = "Excluding from code coverage because a service call is required for the method") - public String retrieveRegisteredAuthMethod(String clientId) throws TokenFilterException { - - try { - if (!(StringUtils.isNotEmpty(new IdentityCommonHelper().getCertificateContent(clientId)) - && IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId))) { - return new IdentityCommonHelper().getAppPropertyFromSPMetaData(clientId, - IdentityCommonConstants.TOKEN_ENDPOINT_AUTH_METHOD); - } - } catch (OpenBankingException e) { - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, "Client authentication method not registered", e); - } - return IdentityCommonConstants.NOT_APPLICABLE; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSCertificateValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSCertificateValidator.java deleted file mode 100644 index d1f45971..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSCertificateValidator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. - * - * This software is the property of WSO2 LLC. and its suppliers, if any. - * Dissemination of any information or reproduction of any material contained - * herein in any form is strictly forbidden, unless permitted by WSO2 expressly. - * You may not alter or remove any copyright or other notice from copies of this content. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.security.cert.X509Certificate; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * MTLS Certificate Validator. - * Validates the expiry status of the certificate. - */ -public class MTLSCertificateValidator implements OBIdentityFilterValidator { - - private static final Log log = LogFactory.getLog(MTLSCertificateValidator.class); - private static final String CERT_EXPIRED_ERROR = "Certificate with the serial number %s issued by the CA %s is " + - "expired"; - - @Override - public void validate(ServletRequest request, String clientId) throws TokenFilterException, ServletException { - - HttpServletRequest servletRequest = (HttpServletRequest) request; - String mtlsCertificate = servletRequest.getHeader(IdentityCommonUtil.getMTLSAuthHeader()); - // MTLSEnforcementValidator validates the presence of the certificate. - if (mtlsCertificate != null) { - try { - X509Certificate x509Certificate = CertificateUtils.parseCertificate(mtlsCertificate); - - if (CertificateUtils.isExpired(x509Certificate)) { - log.error(String.format(CERT_EXPIRED_ERROR, x509Certificate.getSerialNumber(), - x509Certificate.getIssuerDN().toString())); - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, - "Invalid mutual TLS request. Client certificate is expired", - String.format(CERT_EXPIRED_ERROR, x509Certificate.getSerialNumber(), - x509Certificate.getIssuerDN().toString())); - } - log.debug("Client certificate expiry validation completed successfully"); - } catch (OpenBankingException e) { - log.error("Invalid mutual TLS request. Client certificate is invalid", e); - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_CLIENT_MESSAGE, e.getMessage()); - } - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSEnforcementValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSEnforcementValidator.java deleted file mode 100644 index de5b0780..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSEnforcementValidator.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Mutual TLS Enforcement Filter Validator. - * Enforces whether the Request is sent with MTLS cert as a header. - */ -public class MTLSEnforcementValidator implements OBIdentityFilterValidator { - - private static final Log log = LogFactory.getLog(MTLSEnforcementValidator.class); - - @Override - public void validate(ServletRequest request, String clientId) throws TokenFilterException, ServletException { - - if (request instanceof HttpServletRequest) { - - HttpServletRequest servletRequest = (HttpServletRequest) request; - String x509Certificate = servletRequest.getHeader(IdentityCommonUtil.getMTLSAuthHeader()); - try { - if (!(StringUtils.isNotEmpty(x509Certificate) && - CertificateUtils.parseCertificate(x509Certificate) != null)) { - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, "Transport certificate not passed through the " + - "request or the certificate is not valid"); - } - } catch (TokenFilterException e) { - throw new TokenFilterException(e.getErrorCode(), e.getMessage(), e.getErrorDescription()); - } catch (OpenBankingException e) { - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants - .OAUTH2_INVALID_CLIENT_MESSAGE, "Invalid transport certificate. " + - e.getMessage(), e); - } - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/OBIdentityFilterValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/OBIdentityFilterValidator.java deleted file mode 100644 index 4cf41457..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/OBIdentityFilterValidator.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; - -/** - * An interface which used to implement additional validations - * needed for the token endpoint in the Key Manager (oauth2/token). - */ -public interface OBIdentityFilterValidator { - - void validate(ServletRequest request, String clientId) throws TokenFilterException, ServletException; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/SignatureAlgorithmEnforcementValidator.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/SignatureAlgorithmEnforcementValidator.java deleted file mode 100644 index a7065b3b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/validators/SignatureAlgorithmEnforcementValidator.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.token.util.TokenFilterException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.text.ParseException; - -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Filter validator to check if the client assertion is signed with the registered algorithm. - */ -public class SignatureAlgorithmEnforcementValidator implements OBIdentityFilterValidator { - - private static final Log log = LogFactory.getLog(SignatureAlgorithmEnforcementValidator.class); - - @Override - public void validate(ServletRequest request, String clientId) throws TokenFilterException { - - if (request instanceof HttpServletRequest) { - String signedObject = request.getParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION); - if (StringUtils.isNotEmpty(signedObject) && - StringUtils.isNotEmpty(getRegisteredSigningAlgorithm(clientId))) { - validateInboundSignatureAlgorithm(getRequestSigningAlgorithm(signedObject), - getRegisteredSigningAlgorithm(clientId)); - } - } - } - - /** - * Checks if the incoming signed request is signed with the registered algorithms during service provider creation. - * - * @param requestSigningAlgorithm the algorithm of signed message - * @param registeredSigningAlgorithm the algorithm registered during client authentication - */ - public void validateInboundSignatureAlgorithm(String requestSigningAlgorithm, String registeredSigningAlgorithm) - throws TokenFilterException { - - if (log.isDebugEnabled()) { - log.debug(String.format("Validating request algorithm %s against registered algorithm %s.", - requestSigningAlgorithm, registeredSigningAlgorithm)); - } - if (registeredSigningAlgorithm.equals(IdentityCommonConstants.NOT_APPLICABLE)) { - return; - } - if (!(StringUtils.isNotEmpty(requestSigningAlgorithm) && - requestSigningAlgorithm.equals(registeredSigningAlgorithm))) { - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_CLIENT_MESSAGE, "Registered algorithm does not match with the token " + - "signed algorithm"); - } - } - - @Generated(message = "Ignoring because it requires a service call") - public String getRegisteredSigningAlgorithm(String clientId) throws TokenFilterException { - - try { - if (!(StringUtils.isNotEmpty(new IdentityCommonHelper().getCertificateContent(clientId)) - && IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId))) { - return new IdentityCommonHelper().getAppPropertyFromSPMetaData(clientId, - IdentityCommonConstants.TOKEN_ENDPOINT_AUTH_SIGNING_ALG); - } - } catch (OpenBankingException e) { - throw new TokenFilterException(HttpServletResponse.SC_UNAUTHORIZED, IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE, "Token signing algorithm not registered", e); - } - return IdentityCommonConstants.NOT_APPLICABLE; - } - - public String getRequestSigningAlgorithm(String signedObject) throws TokenFilterException { - //retrieve algorithm from the signed JWT - try { - SignedJWT signedJWT = SignedJWT.parse(signedObject); - return signedJWT.getHeader().getAlgorithm().getName(); - } catch (ParseException e) { - throw new TokenFilterException(HttpServletResponse.SC_BAD_REQUEST, IdentityCommonConstants - .OAUTH2_INVALID_CLIENT_MESSAGE, "Error occurred while parsing the signed assertion", e); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/wrapper/RequestWrapper.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/wrapper/RequestWrapper.java deleted file mode 100644 index 7515bd7d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/wrapper/RequestWrapper.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.wrapper; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - -/** - * Request wrapper implementation. - */ -public class RequestWrapper extends HttpServletRequestWrapper { - - private Map headerMap = new HashMap<>(); - - /** - * Constructs a request object wrapping the given request. - * - * @param request - * @throws IllegalArgumentException if the request is null. - */ - private final ByteArrayOutputStream byteArrayOutputStream; - - public RequestWrapper(HttpServletRequest request) { - super(request); - byteArrayOutputStream = new ByteArrayOutputStream(); - } - - @Override - public ServletInputStream getInputStream() throws IOException { - final ServletInputStream originalInputStream = super.getInputStream(); - - return new ServletInputStream() { - @Override - public int read() throws IOException { - int data = originalInputStream.read(); - if (data != -1) { - byteArrayOutputStream.write(data); - } - return data; - } - - @Override - public boolean isFinished() { - return originalInputStream.isFinished(); - } - - @Override - public boolean isReady() { - return originalInputStream.isReady(); - } - - @Override - public void setReadListener(ReadListener readListener) { - originalInputStream.setReadListener(readListener); - } - }; - } - - public byte[] getCapturedRequest() { - return byteArrayOutputStream.toByteArray(); - } - - /** - * Set the header map to hold the header values. - * - * @param name - * @param value - */ - public void setHeader(String name, String value) { - - headerMap.put(name, value); - } - - @Override - public String getHeader(String name) { - - String headerValue = super.getHeader(name); - if (headerMap.containsKey(name)) { - headerValue = headerMap.get(name); - } - return headerValue; - } - - @Override - public Enumeration getHeaderNames() { - - List headerNames = Collections.list(super.getHeaderNames()); - for (Map.Entry entry: headerMap.entrySet()) { - // prevent adding duplicate entries to headerNames list - headerNames.remove(entry.getKey()); - } - headerNames.addAll(headerMap.keySet()); - return Collections.enumeration(headerNames); - } - - @Override - public Enumeration getHeaders(String name) { - - if (headerMap.containsKey(name)) { - return Collections.enumeration(Collections.singletonList(headerMap.get(name))); - } - return Collections.enumeration(Collections.list(super.getHeaders(name))); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/wrapper/ResponseWrapper.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/wrapper/ResponseWrapper.java deleted file mode 100644 index 916dbdcc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/token/wrapper/ResponseWrapper.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.wrapper; - -import net.sf.ehcache.constructs.web.filter.FilterServletOutputStream; - -import java.io.ByteArrayOutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -/** - * Response wrapper implementation. - */ -public class ResponseWrapper extends HttpServletResponseWrapper { - - private ByteArrayOutputStream output; - private int contentLength; - private String contentType; - - public ResponseWrapper(HttpServletResponse response) { - - super(response); - output = new ByteArrayOutputStream(); - } - - public byte[] getData() { - - return output.toByteArray(); - } - - public ServletOutputStream getOutputStream() { - - return new FilterServletOutputStream(output); - } - - public PrintWriter getWriter() { - - return new PrintWriter(new OutputStreamWriter(getOutputStream(), StandardCharsets.UTF_8), true); - } - - public int getContentLength() { - - return contentLength; - } - - public void setContentLength(int length) { - - this.contentLength = length; - super.setContentLength(length); - } - - public String getContentType() { - - return contentType; - } - - public void setContentType(String type) { - - this.contentType = type; - super.setContentType(type); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/ClientAuthenticatorEnum.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/ClientAuthenticatorEnum.java deleted file mode 100644 index 5ea72436..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/ClientAuthenticatorEnum.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.util; - -/** - * Enumerations for client authenticators. - */ -public enum ClientAuthenticatorEnum { - PRIVATE_KEY_JWT("private_key_jwt"), - TLS_CLIENT_AUTH("tls_client_auth"); - - private final String value; - - ClientAuthenticatorEnum(String value) { - - this.value = value; - } - - public static ClientAuthenticatorEnum fromValue(String text) { - - for (ClientAuthenticatorEnum authenticatorEnum : ClientAuthenticatorEnum.values()) { - if (String.valueOf(authenticatorEnum.value).equals(text)) { - return authenticatorEnum; - } - } - return null; - } - - @Override - public String toString() { - - return String.valueOf(value); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/HTTPClientUtils.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/HTTPClientUtils.java deleted file mode 100644 index 33eca0a0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/HTTPClientUtils.java +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContexts; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.core.UserStoreException; - - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.Base64; - -import javax.net.ssl.SSLContext; - -/** - * HTTP Client Utility methods. - */ -public class HTTPClientUtils { - - public static final String ALLOW_ALL = "AllowAll"; - public static final String STRICT = "Strict"; - public static final String HOST_NAME_VERIFIER = "httpclient.hostnameVerifier"; - public static final String HTTP_PROTOCOL = "http"; - public static final String HTTPS_PROTOCOL = "https"; - private static final String[] SUPPORTED_HTTP_PROTOCOLS = {"TLSv1.2"}; - private static final Log log = LogFactory.getLog(HTTPClientUtils.class); - - /** - * Get closeable https client. - * - * @return Closeable https client - * @throws OpenBankingException OpenBankingException exception - */ - @Generated(message = "Unit testable components are covered") - public static CloseableHttpClient getHttpsClient() throws OpenBankingException { - - SSLConnectionSocketFactory sslsf = createSSLConnectionSocketFactory(); - - Registry socketFactoryRegistry = RegistryBuilder.create() - .register(HTTP_PROTOCOL, new PlainConnectionSocketFactory()) - .register(HTTPS_PROTOCOL, sslsf) - .build(); - - final PoolingHttpClientConnectionManager connectionManager = (socketFactoryRegistry != null) ? - new PoolingHttpClientConnectionManager(socketFactoryRegistry) : - new PoolingHttpClientConnectionManager(); - - return HttpClients.custom().setConnectionManager(connectionManager).build(); - } - - /** - * create a SSL Connection Socket Factory. - * - * @return SSLConnectionSocketFactory - * @throws OpenBankingException - */ - @Generated(message = "Ignoring because ServerConfiguration cannot be mocked") - private static SSLConnectionSocketFactory createSSLConnectionSocketFactory() - throws OpenBankingException { - - KeyStore trustStore = null; - - trustStore = loadKeyStore( - ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Location"), - ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Password")); - - // Trust own CA and all self-signed certs - SSLContext sslcontext = null; - try { - sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); - } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { - throw new OpenBankingException("Unable to create the ssl context", e); - } - - // Allow TLSv1 protocol only - return new SSLConnectionSocketFactory(sslcontext, SUPPORTED_HTTP_PROTOCOLS, - null, getX509HostnameVerifier()); - - } - - /** - * Load the keystore when the location and password is provided. - * - * @param keyStoreLocation Location of the keystore - * @param keyStorePassword Keystore password - * @return Keystore as an object - * @throws OpenBankingException when failed to load Keystore from given details - */ - @SuppressFBWarnings("PATH_TRAVERSAL_IN") - // Suppressed content - new FileInputStream(keyStoreLocation) - // Suppression reason - False Positive : Keystore location is obtained from deployment.toml. So it can be marked - // as a trusted filepath - // Suppressed warning count - 1 - public static KeyStore loadKeyStore(String keyStoreLocation, String keyStorePassword) - throws OpenBankingException { - - KeyStore keyStore; - - try (FileInputStream inputStream = new FileInputStream(keyStoreLocation)) { - keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(inputStream, keyStorePassword.toCharArray()); - return keyStore; - } catch (KeyStoreException e) { - throw new OpenBankingException("Error while retrieving aliases from keystore", e); - } catch (IOException | CertificateException | NoSuchAlgorithmException e) { - throw new OpenBankingException("Error while loading keystore", e); - } - } - - /** - * Get the Hostname Verifier property in set in system properties. - * - * @return X509HostnameVerifier - */ - public static X509HostnameVerifier getX509HostnameVerifier() { - - String hostnameVerifierOption = System.getProperty(HOST_NAME_VERIFIER); - X509HostnameVerifier hostnameVerifier; - - if (ALLOW_ALL.equalsIgnoreCase(hostnameVerifierOption)) { - hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - } else if (STRICT.equalsIgnoreCase(hostnameVerifierOption)) { - hostnameVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; - } else { - hostnameVerifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; - } - - if (log.isDebugEnabled()) { - log.debug(String.format("Proceeding with %s : %s", HOST_NAME_VERIFIER, - hostnameVerifierOption)); - } - return hostnameVerifier; - - } - - /** - * Get base 64 encoded credentials of basic authentication for protected consent APIs. - * - * @return basic auth - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public static String getBasicAuthCredentials() throws OpenBankingException { - RealmConfiguration realmConfiguration; - try { - realmConfiguration = IdentityExtensionsDataHolder.getInstance().getRealmService() - .getBootstrapRealm().getUserStoreManager().getRealmConfiguration(); - } catch (UserStoreException e) { - throw new OpenBankingException("Error while retrieving session data", e); - } - - String adminUsername = realmConfiguration.getAdminUserName(); - char[] adminPassword = realmConfiguration.getAdminPassword().toCharArray(); - - String credentials = adminUsername + ":" + String.valueOf(adminPassword); - return Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonConstants.java deleted file mode 100644 index 0b9c38ef..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonConstants.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.util; - -/** - * Class containing the constants for Open Banking Common module. - */ -public class IdentityCommonConstants { - - public static final String CLIENT_ID = "client_id"; - public static final String REQUEST_URI = "request_uri"; - public static final String REQUEST = "request"; - public static final String RESPONSE_TYPE = "response_type"; - public static final String REDIRECT_URI = "redirect_uri"; - public static final String CARBON_HOME = "carbon.home"; - public static final String REGULATORY_COMPLIANCE = "regulatory"; - public static final String TOKEN_ENDPOINT_AUTH_METHOD = "token_endpoint_auth_method"; - public static final String TOKEN_ENDPOINT_AUTH_SIGNING_ALG = "token_endpoint_auth_signing_alg"; - public static final String REQUEST_OBJECT_SIGNING_ALG = "request_object_signing_alg"; - public static final String CLIENT_ID_ERROR = "Client id not found"; - public static final String OAUTH_CLIENT_ID = "client_id"; - public static final String OAUTH_CLIENT_SECRET = "client_secret"; - public static final String AUTHORIZATION_HEADER = "authorization"; - public static final String OAUTH_JWT_ASSERTION = "client_assertion"; - public static final String OAUTH_JWT_ASSERTION_TYPE = "client_assertion_type"; - public static final String OAUTH_JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; - public static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; - public static final String END_CERT = "-----END CERTIFICATE-----"; - public static final String MTLS_AUTH_HEADER = "MutualTLS.ClientCertificateHeader"; - public static final String X509 = "X.509"; - public static final String TOKEN_FILTER = "Identity.Filters.TokenFilter"; - public static final String TOKEN_VALIDATORS = "Identity.TokenFilterValidators.Validator"; - public static final String CLAIM_PROVIDER = "Identity.Extensions.ClaimProvider"; - public static final String INTROSPECTION_DATA_PROVIDER = "Identity.Extensions.IntrospectionDataProvider"; - public static final String SIGNING_CERT_KID = "Identity.SigningCertificateKid"; - public static final String OAUTH_ERROR = "error"; - public static final String OAUTH_ERROR_DESCRIPTION = "error_description"; - public static final String JAVAX_SERVLET_REQUEST_CERTIFICATE = "javax.servlet.request.X509Certificate"; - public static final String OB_CONSENT_ID_PREFIX = "OB_CONSENT_ID_"; - public static final String OB_PREFIX = "OB_"; - public static final String TIME_PREFIX = "TIME_"; - public static final String TLS_CERT = "tls_cert"; - public static final String CERT_PREFIX = "x5t#"; - public static final String CERTIFICATE_HEADER = "x-wso2-mutual-auth-cert"; - public static final String CERTIFICATE_HEADER_ATTRIBUTE = "x-wso2-mutual-auth-cert-attribute"; - public static final String SPACE_SEPARATOR = " "; - public static final String SCOPE = "scope"; - public static final String CONDITIONAL_COMMON_AUTH_SCRIPT_FILE_NAME = "common.auth.script.js"; - public static final String PRIMARY_AUTHENTICATOR_DISPLAYNAME = "SCA.PrimaryAuthenticator.DisplayName"; - public static final String PRIMARY_AUTHENTICATOR_NAME = "SCA.PrimaryAuthenticator.Name"; - public static final String IDENTITY_PROVIDER_NAME = "SCA.IdpName"; - public static final String IDENTITY_PROVIDER_STEP = "SCA.IdpStep"; - public static final String REQUEST_VALIDATOR = "Identity.Extensions.RequestObjectValidator"; - public static final String PUSH_AUTH_REQUEST_VALIDATOR = "Identity.Extensions.PushAuthRequestValidator"; - public static final String RESPONSE_HANDLER = "Identity.Extensions.ResponseTypeHandler"; - public static final String ENABLE_TRANSPORT_CERT_AS_HEADER = "Identity.ClientTransportCertAsHeaderEnabled"; - public static final String ENABLE_SUBJECT_AS_PPID = "Identity.EnableSubjectPPID"; - public static final String REMOVE_USER_STORE_DOMAIN_FROM_SUBJECT = - "Identity.TokenSubject.RemoveUserStoreDomainFromSubject"; - public static final String REMOVE_TENANT_DOMAIN_FROM_SUBJECT = - "Identity.TokenSubject.RemoveTenantDomainFromSubject"; - - public static final String AUTH_SERVLET_EXTENSION = "Identity.Extensions.AuthenticationWebApp.ServletExtension"; - public static final String CONSENT_ID_CLAIM_NAME = "Identity.ConsentIDClaimName"; - public static final String SP_ACCESS_TOKEN_INPUT_STREAM = "AccessTokenInputStream"; - public static final String INPUT_STREAM_VERSION = "1.0.0"; - public static final String ACCESS_TOKEN_ID = "accessTokenID"; - public static final String NOT_APPLICABLE = "N/A"; - public static final String CONSENT_JWT_PAYLOAD_VALIDATION = "Consent.Validation.JWTPayloadValidation"; - - public static final String S_HASH = "s_hash"; - public static final String CODE = "code"; - public static final String DCR_INTERNAL_SCOPE = "OB_DCR"; - public static final String OPENID_SCOPE = "openid"; - public static final String CLIENT_CREDENTIALS = "client_credentials"; - public static final String CARBON_SUPER = "carbon.super"; - public static final String REGISTRATION_ACCESS_TOKEN = "registration_access_token"; - public static final String REGISTRATION_CLIENT_URI = "registration_client_uri"; - public static final String PRIVATE_KEY = "pvt_key"; - public static final String ALG_ES256 = "ES256"; - public static final String ALG_PS256 = "PS256"; - public static final String DEFAULT_JWKS_URI = "software_jwks_endpoint"; - public static final String DEFAULT_REGISTRATION_CLIENT_URI = "https://localhost:8243/open-banking/0.1/register/"; - public static final String PAR_ENDPOINT = "/api/openbanking/push-authorization/par"; - - public static final String TLS_CERT_JWKS = "Identity.MutualTLS.TransportCertificateJWKS"; - public static final String CLIENT_CERTIFICATE_ENCODE = "Identity.MutualTLS.ClientCertificateEncode"; - public static final String DCR_MODIFY_RESPONSE = "DCR.ModifyResponse"; - public static final String DCR_SCOPE = "DCR.Scope"; - public static final String DCR_REGISTRATION_CLIENT_URI = "DCR.RegistrationClientURI"; - - //Error Constants - public static final String OAUTH2_INVALID_CLIENT_MESSAGE = "invalid_client"; - public static final String OAUTH2_INVALID_REQUEST_MESSAGE = "invalid_request"; - public static final String OAUTH2_INTERNAL_SERVER_ERROR = "server_error"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonHelper.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonHelper.java deleted file mode 100644 index 43d1863c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonHelper.java +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.util; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CertificateUtils; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.oltu.oauth2.common.message.types.GrantType; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.core.UserStoreException; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.nio.charset.StandardCharsets; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.annotation.Nullable; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; - -/** - * Identity common helper class. - */ -public class IdentityCommonHelper { - - private static final Log log = LogFactory.getLog(IdentityCommonHelper.class); - - /** - * Utility method get the application property from SP Meta Data. - * @param clientId ClientId of the application - * @return the service provider certificate - * @throws OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public String getCertificateContent(String clientId) throws OpenBankingException { - - Optional serviceProvider; - try { - serviceProvider = Optional.ofNullable(IdentityExtensionsDataHolder.getInstance() - .getApplicationManagementService().getServiceProviderByClientId(clientId, - IdentityApplicationConstants.OAuth2.NAME, - ServiceProviderUtils.getSpTenantDomain(clientId))); - if (serviceProvider.isPresent()) { - return serviceProvider.get().getCertificateContent(); - } - } catch (IdentityApplicationManagementException e) { - log.error(String.format("Error occurred while retrieving OAuth2 application data for clientId %s", - clientId), e); - throw new OpenBankingException("Error occurred while retrieving OAuth2 application data for clientId" - , e); - } - return ""; - } - - /** - * Utility method get the application property from SP Meta Data. - * - * @param clientId ClientId of the application - * @param property Property of the application - * @return the property value from SP metadata - * @throws OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public String getAppPropertyFromSPMetaData(String clientId, String property) throws OpenBankingException { - - String spProperty = null; - - if (StringUtils.isNotEmpty(clientId)) { - Optional serviceProvider; - try { - serviceProvider = Optional.ofNullable(IdentityExtensionsDataHolder.getInstance() - .getApplicationManagementService().getServiceProviderByClientId(clientId, - IdentityApplicationConstants.OAuth2.NAME, - ServiceProviderUtils.getSpTenantDomain(clientId))); - if (serviceProvider.isPresent()) { - spProperty = Arrays.stream(serviceProvider.get().getSpProperties()) - .collect(Collectors.toMap(ServiceProviderProperty::getName, - ServiceProviderProperty::getValue)) - .get(property); - } - } catch (IdentityApplicationManagementException e) { - log.error(String.format("Error occurred while retrieving OAuth2 application data for clientId %s", - clientId), e); - throw new OpenBankingException("Error occurred while retrieving OAuth2 application data for clientId" - , e); - } - } else { - log.error(IdentityCommonConstants.CLIENT_ID_ERROR); - throw new OpenBankingException(IdentityCommonConstants.CLIENT_ID_ERROR); - } - - return spProperty; - } - - /** - * Validate whether the request follows mtls authentication pattern. - * - * @param request servlet request - * @return whether request fallows MTLS pattern - */ - public boolean isMTLSAuthentication(ServletRequest request) throws - OpenBankingException { - - if (request instanceof HttpServletRequest) { - String oauthClientID = request.getParameter(IdentityCommonConstants.OAUTH_CLIENT_ID); - String oauthClientSecret = request.getParameter(IdentityCommonConstants.OAUTH_CLIENT_SECRET); - String oauthJWTAssertion = request.getParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION); - String oauthJWTAssertionType = request.getParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE); - HttpServletRequest servletRequest = (HttpServletRequest) request; - String authorizationHeader = servletRequest.getHeader(IdentityCommonConstants.AUTHORIZATION_HEADER); - String x509Certificate = servletRequest.getHeader(IdentityCommonUtil.getMTLSAuthHeader()); - return (StringUtils.isNotEmpty(oauthClientID) && StringUtils.isEmpty(oauthClientSecret) && - StringUtils.isEmpty(oauthJWTAssertion) && StringUtils.isEmpty(oauthJWTAssertionType) && - StringUtils.isEmpty(authorizationHeader) && x509Certificate != null && - CertificateUtils.parseCertificate(x509Certificate) != null); - } else { - throw new OpenBankingException("Error occurred during request validation, passed request is not a " + - "HttpServletRequest"); - } - } - - /** - * Get the configured value of the transport cert as header enable. - * - * @return value of the transport cert as header enable - */ - public boolean isTransportCertAsHeaderEnabled() { - - Optional certAsHeader = - Optional.ofNullable(IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .get(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER)); - return certAsHeader.filter(isEnabled -> Boolean.parseBoolean(isEnabled.toString())).isPresent(); - } - - /** - * Retrieve all Service provider information. - * - * @return list of service providers - * @throws IdentityApplicationManagementException when get application basic info fails - * @throws UserStoreException when get realm configuration fails - */ - @Generated(message = "Excluding from code coverage since it requires a service call") - public List getAllServiceProviders() - throws IdentityApplicationManagementException, UserStoreException { - - ApplicationManagementService applicationManagementService = IdentityExtensionsDataHolder.getInstance() - .getApplicationManagementService(); - - List serviceProviderList = new ArrayList<>(); - if (applicationManagementService != null) { - - RealmConfiguration realmConfig = IdentityExtensionsDataHolder.getInstance().getRealmService() - .getBootstrapRealm().getUserStoreManager().getRealmConfiguration(); - - final String adminUsername = realmConfig.getAdminUserName(); - final String tenantDomain = MultitenantUtils.getTenantDomain(adminUsername); - final int totalApplicationCount = applicationManagementService - .getCountOfAllApplications(tenantDomain, adminUsername); - - ApplicationBasicInfo[] applicationBasicInfo = applicationManagementService - .getApplicationBasicInfo(tenantDomain, adminUsername, 0, totalApplicationCount); - // Set tenant domain before calling applicationManagementService - if (CarbonContext.getThreadLocalCarbonContext().getTenantDomain() == null) { - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); - } - if (applicationBasicInfo != null && applicationBasicInfo.length > 0) { - for (ApplicationBasicInfo basicInfo : applicationBasicInfo) { - serviceProviderList - .add(applicationManagementService.getServiceProvider(basicInfo.getApplicationId())); - } - } - } - return serviceProviderList; - } - - /** - * Encode the certificate content. - * @param certificate - * @return - * @throws CertificateEncodingException - */ - public String encodeCertificateContent(X509Certificate certificate) throws CertificateEncodingException { - if (certificate != null) { - byte[] encodedContent = certificate.getEncoded(); - return IdentityCommonConstants.BEGIN_CERT + new String(Base64.getEncoder().encode(encodedContent), - StandardCharsets.UTF_8) + IdentityCommonConstants.END_CERT; - } else { - return null; - } - } - - /** - * Revokes access tokens for the given client id. - * - * @param clientId consumer key of the application - * @throws IdentityOAuth2Exception when revoking access tokens fails - */ - @Generated(message = "Excluding from code coverage since it requires service calls") - public void revokeAccessTokensByClientId(@Nullable final String clientId) throws IdentityOAuth2Exception { - - if (StringUtils.isEmpty(clientId)) { - return; - } - - Set activeTokens = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO() - .getActiveTokensByConsumerKey(clientId); - if (!activeTokens.isEmpty()) { - OAuthClientAuthnContext oAuthClientAuthnContext = new OAuthClientAuthnContext(); - oAuthClientAuthnContext.setAuthenticated(true); - oAuthClientAuthnContext.setClientId(clientId); - - OAuthRevocationRequestDTO revocationRequestDTO = new OAuthRevocationRequestDTO(); - revocationRequestDTO.setOauthClientAuthnContext(oAuthClientAuthnContext); - revocationRequestDTO.setConsumerKey(clientId); - revocationRequestDTO.setTokenType(GrantType.REFRESH_TOKEN.toString()); - - for (String accessToken : activeTokens) { - revocationRequestDTO.setToken(accessToken); - OAuthRevocationResponseDTO oAuthRevocationResponseDTO = IdentityExtensionsDataHolder.getInstance() - .getOAuth2Service().revokeTokenByOAuthClient(revocationRequestDTO); - - if (oAuthRevocationResponseDTO.isError()) { - throw new IdentityOAuth2Exception( - String.format("Error occurred while revoking access tokens for clientId: %s. Caused by, %s", - clientId, oAuthRevocationResponseDTO.getErrorMsg())); - } - } - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonUtil.java deleted file mode 100644 index 69bf3fa3..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/java/com/wso2/openbanking/accelerator/identity/util/IdentityCommonUtil.java +++ /dev/null @@ -1,436 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.util; - -import com.google.common.base.Charsets; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.identity.cache.IdentityCache; -import com.wso2.openbanking.accelerator.identity.cache.IdentityCacheKey; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.wso2.carbon.core.util.KeyStoreManager; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletRequest; - -/** - * Utility Class for Identity Open Banking. - */ -public class IdentityCommonUtil { - - private static final Log log = LogFactory.getLog(IdentityCommonUtil.class); - private static IdentityCache identityCache; - - /** - * Get the configured certificate header name. - * - * @return value of the cert header name configuration - */ - public static String getMTLSAuthHeader() { - - return Optional.ofNullable(IdentityUtil.getProperty(IdentityCommonConstants.MTLS_AUTH_HEADER)) - .orElse("CONFIG_NOT_FOUND"); - } - - /** - * Remove the internal scopes from the space delimited list of authorized scopes. - * - * @param scopes Authorized scopes of the token - * @return scopes by removing the internal scopes - */ - public static String[] removeInternalScopes(String[] scopes) { - - String consentIdClaim = IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .get(IdentityCommonConstants.CONSENT_ID_CLAIM_NAME).toString(); - - if (scopes != null && scopes.length > 0) { - List scopesList = new LinkedList<>(Arrays.asList(scopes)); - scopesList.removeIf(s -> s.startsWith(consentIdClaim)); - scopesList.removeIf(s -> s.startsWith(IdentityCommonConstants.OB_PREFIX)); - scopesList.removeIf(s -> s.startsWith(IdentityCommonConstants.TIME_PREFIX)); - scopesList.removeIf(s -> s.startsWith(IdentityCommonConstants.CERT_PREFIX)); - return scopesList.toArray(new String[scopesList.size()]); - } - return scopes; - } - - /** - * Cache regulatory property if exists. - * - * @param clientId clientId ClientId of the application - * @return the regulatory property from cache if exists or from sp metadata - * @throws OpenBankingException - */ - @Generated(message = "Excluding from code coverage since it requires a cache initialization/service call") - public static synchronized boolean getRegulatoryFromSPMetaData(String clientId) throws OpenBankingException { - - if (StringUtils.isNotEmpty(clientId)) { - // Skip My account and Console service providers with non opaque clientIds - if (clientId.equalsIgnoreCase("CONSOLE") || - clientId.equalsIgnoreCase("MY_ACCOUNT")) { - return false; - } - - if (identityCache == null) { - log.debug("Creating new Identity cache"); - identityCache = new IdentityCache(); - } - - IdentityCacheKey identityCacheKey = IdentityCacheKey.of(clientId - .concat("_").concat(OpenBankingConstants.REGULATORY)); - Object regulatoryProperty = null; - - regulatoryProperty = identityCache.getFromCacheOrRetrieve(identityCacheKey, - () -> new IdentityCommonHelper().getAppPropertyFromSPMetaData(clientId, - IdentityCommonConstants.REGULATORY_COMPLIANCE)); - - if (regulatoryProperty != null) { - return Boolean.parseBoolean(regulatoryProperty.toString()); - } else { - throw new OpenBankingException("Unable to retrieve regulatory property from sp metadata"); - } - } else { - throw new OpenBankingException(IdentityCommonConstants.CLIENT_ID_ERROR); - } - } - - public static ServiceProviderProperty getServiceProviderProperty(String spPropertyName, String spPropertyValue) { - - ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty(); - serviceProviderProperty.setValue(spPropertyValue); - serviceProviderProperty.setName(spPropertyName); - serviceProviderProperty.setDisplayName(spPropertyName); - return serviceProviderProperty; - } - - /** - * Sign a string body using the carbon default key pair. - * Skipped in unit tests since @KeystoreManager cannot be mocked - * - * @param body the body that needs to be signed as a string - * @return string value of the signed JWT - * @throws Exception error if the tenant is invalid - */ - public static String signJWTWithDefaultKey(String body) throws Exception { - KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(-1234); - Key privateKey = keyStoreManager.getDefaultPrivateKey(); - return generateJWT(body, privateKey); - } - - /** - * Validate a JWT signature by providing the alias in the client truststore. - * Skipped in unit tests since @KeystoreManager cannot be mocked - * - * @param jwtString string value of the JWT to be validated - * @param alias alias in the trust store - * @return boolean value depicting whether the signature is valid - * @throws OpenBankingException error with message mentioning the cause - */ - public static boolean validateJWTSignatureWithPublicKey(String jwtString, String alias) - throws OpenBankingException { - - Certificate certificate; - try { - KeyStore trustStore = getTrustStore(); - certificate = trustStore.getCertificate(alias); - } catch (Exception e) { - throw new OpenBankingException("Error while retrieving certificate from truststore"); - } - - if (certificate == null) { - throw new OpenBankingException("Certificate not found for provided alias"); - } - PublicKey publicKey = certificate.getPublicKey(); - - try { - JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) publicKey); - return SignedJWT.parse(jwtString).verify(verifier); - } catch (JOSEException | ParseException e) { - throw new OpenBankingException("Error occurred while validating JWT signature"); - } - - } - - /** - * Util method to get the configured trust store by carbon config or cached instance. - * - * @return Keystore instance of the truststore - * @throws Exception Error when loading truststore or carbon truststore config unavailable - */ - public static KeyStore getTrustStore() throws Exception { - if (IdentityExtensionsDataHolder.getInstance().getTrustStore() == null) { - String trustStoreLocation = System.getProperty("javax.net.ssl.trustStore"); - String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); - String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType"); - - if (trustStoreLocation == null || trustStorePassword == null || trustStoreType == null) { - throw new Exception("Trust store config not available"); - } - - try (InputStream keyStoreStream = new FileInputStream(trustStoreLocation)) { - KeyStore keyStore = KeyStore.getInstance(trustStoreType); // or "PKCS12" - keyStore.load(keyStoreStream, trustStorePassword.toCharArray()); - IdentityExtensionsDataHolder.getInstance().setTrustStore(keyStore); - } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException e) { - throw new Exception("Error while loading truststore.", e); - } - } - return IdentityExtensionsDataHolder.getInstance().getTrustStore(); - } - - /** - * Util method to generate JWT using a payload and a private key. RS256 is the algorithm used - * - * @param payload The payload body to be signed - * @param privateKey The private key for the JWT to be signed with - * @return String signed JWT - */ - public static String generateJWT(String payload, Key privateKey) { - - if (privateKey == null || payload == null) { - log.debug("Null value passed for payload or key. Cannot generate JWT"); - throw new OpenBankingRuntimeException("Payload and key cannot be null"); - } - - if (!(privateKey instanceof RSAPrivateKey)) { - throw new OpenBankingRuntimeException("Private key should be an instance of RSAPrivateKey"); - } - - JWSSigner signer = new RSASSASigner((RSAPrivateKey) privateKey); - JWSHeader.Builder headerBuilder = new JWSHeader.Builder(JWSAlgorithm.RS256); - - SignedJWT signedJWT = null; - try { - signedJWT = new SignedJWT(headerBuilder.build(), JWTClaimsSet.parse(payload)); - signedJWT.sign(signer); - } catch (ParseException | JOSEException e) { - throw new OpenBankingRuntimeException("Error occurred while signing JWT"); - } - return signedJWT.serialize(); - } - - /** - * Util method to generate SP meta data using service provider. - * - * @param serviceProvider The service provider - * @return SP meta data as a Map - */ - public static Map getSpMetaData(ServiceProvider serviceProvider) { - - Map originalData = Arrays.stream(serviceProvider.getSpProperties()) - .collect(Collectors.toMap(ServiceProviderProperty::getName, ServiceProviderProperty::getValue)); - - Map spMetaDataMap = new HashMap<>(); - - for (Map.Entry data : originalData.entrySet()) { - - if (data.getValue().contains(DCRCommonConstants.ARRAY_ELEMENT_SEPERATOR)) { - ArrayList dataList = new ArrayList<>(Arrays.asList(data.getValue() - .split(DCRCommonConstants.ARRAY_ELEMENT_SEPERATOR))); - spMetaDataMap.put(data.getKey(), dataList); - } else { - spMetaDataMap.put(data.getKey(), data.getValue()); - } - } - return spMetaDataMap; - } - - /** - * Method to obtain Hash Value for a given String, default algorithm SHA256withRSA. - * - * @param value String value that required to be Hashed - * @return Hashed String - * @throws IdentityOAuth2Exception - */ - public static String getHashValue(String value, String digestAlgorithm) throws IdentityOAuth2Exception { - - if (digestAlgorithm == null) { - JWSAlgorithm digAlg = OAuth2Util.mapSignatureAlgorithmForJWSAlgorithm( - OAuthServerConfiguration.getInstance().getIdTokenSignatureAlgorithm()); - digestAlgorithm = OAuth2Util.mapDigestAlgorithm(digAlg); - } - MessageDigest md; - try { - md = MessageDigest.getInstance(digestAlgorithm); - } catch (NoSuchAlgorithmException e) { - throw new IdentityOAuth2Exception("Error creating the hash value. Invalid Digest Algorithm: " + - digestAlgorithm); - } - //generating hash value - md.update(value.getBytes(Charsets.UTF_8)); - byte[] digest = md.digest(); - int leftHalfBytes = digest.length / 2; - byte[] leftmost = new byte[leftHalfBytes]; - System.arraycopy(digest, 0, leftmost, 0, leftHalfBytes); - - return Base64.getUrlEncoder().withoutPadding().encodeToString(leftmost) - .replace("\n", "").replace("\r", ""); - } - - /** - * This method returns the configuration value on whether the JWT payload validation needs to be performed in the - * consent validation endpoint. - * @return config value - */ - public static boolean getConsentJWTPayloadValidatorConfigEnabled() { - return Boolean.parseBoolean(String.valueOf(IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .getOrDefault(IdentityCommonConstants.CONSENT_JWT_PAYLOAD_VALIDATION, true))); - } - - /** - * This method returns the configured JWK URI value of the transport certificate. - * @return - */ - public static String getJWKURITransportCert() { - return String.valueOf(IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .getOrDefault(IdentityCommonConstants.TLS_CERT_JWKS, IdentityCommonConstants.DEFAULT_JWKS_URI)); - } - - /** - * This method will return the configured DCR scope. - * @return - */ - public static String getDCRScope() { - return String.valueOf(IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .getOrDefault(IdentityCommonConstants.DCR_SCOPE, IdentityCommonConstants.DCR_INTERNAL_SCOPE)); - } - - public static Boolean getDCRModifyResponseConfig() { - return Boolean.parseBoolean(String.valueOf(IdentityExtensionsDataHolder.getInstance().getConfigurationMap() - .getOrDefault(IdentityCommonConstants.DCR_MODIFY_RESPONSE, "false"))); - } - - /** - * Retrieve certificate from servlet request attribute. - * @param certObject certificate Object. - * @return X509Certificate certificate. - */ - public static X509Certificate getCertificateFromAttribute(Object certObject) { - - if (certObject instanceof X509Certificate[]) { - X509Certificate[] cert = (X509Certificate[]) certObject; - return cert[0]; - } else if (certObject instanceof X509Certificate) { - return (X509Certificate) certObject; - } - return null; - } - - /** - * Method to decode request object and retrieve values. - * - * @param request HTTP Servlet request. - * @param key key to retrieve. - * @return value. - */ - public static String decodeRequestObjectAndGetKey(HttpServletRequest request, String key) - throws OAuthProblemException { - - if (request.getParameterMap().containsKey(IdentityCommonConstants.REQUEST_URI) && - request.getParameter(IdentityCommonConstants.REQUEST_URI) != null) { - - // Consider as PAR request - String[] requestUri = request.getParameter(IdentityCommonConstants.REQUEST_URI).split(":"); - String requestUriRef = requestUri[requestUri.length - 1]; - SessionDataCacheEntry valueFromCache = SessionDataCache.getInstance() - .getValueFromCache(new SessionDataCacheKey(requestUriRef)); - if (valueFromCache != null) { - String essentialClaims = valueFromCache.getoAuth2Parameters().getEssentialClaims(); - if (essentialClaims != null) { - String[] essentialClaimsWithExpireTime = essentialClaims.split(":"); - essentialClaims = essentialClaimsWithExpireTime[0]; - essentialClaims = essentialClaims.split("\\.")[1]; - byte[] requestObject; - try { - requestObject = Base64.getDecoder().decode(essentialClaims); - } catch (IllegalArgumentException e) { - - // Decode if the requestObject is base64-url encoded. - requestObject = Base64.getUrlDecoder().decode(essentialClaims); - } - org.json.JSONObject - requestObjectVal = - new org.json.JSONObject(new String(requestObject, StandardCharsets.UTF_8)); - return requestObjectVal.has(key) ? requestObjectVal.getString(key) : null; - } - } else { - throw OAuthProblemException.error("invalid_request_uri") - .description("Provided request URI is not valid"); - } - } - return null; - - } - - public static OAuthProblemException handleOAuthProblemException(String errorCode, String message, String state) { - - return OAuthProblemException.error(errorCode).description(message).state(state); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index c4f8e532..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/resources/findbugs-include.xml deleted file mode 100644 index 649d044e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/HTTPClientUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/HTTPClientUtilsTest.java deleted file mode 100644 index fda5597c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/HTTPClientUtilsTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.HTTPClientUtils; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.io.File; - -/** - * Test for HTTP client utils. - */ -public class HTTPClientUtilsTest { - - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - - @Test - public void testLoadKeystore() throws OpenBankingException { - - Assert.assertNotNull(HTTPClientUtils.loadKeyStore(absolutePathForTestResources + "/wso2carbon.jks", - "wso2carbon")); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testLoadInvalidKeystore() throws OpenBankingException { - - HTTPClientUtils.loadKeyStore(absolutePathForTestResources + "/wso2carbon2.jks", - "wso2carbon"); - } - - @Test - public void testHostNameVerifier() throws OpenBankingException { - - Assert.assertEquals(HTTPClientUtils.getX509HostnameVerifier(), - SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - System.setProperty(HTTPClientUtils.HOST_NAME_VERIFIER, - String.valueOf(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)); - - Assert.assertEquals(HTTPClientUtils.getX509HostnameVerifier(), - SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - System.setProperty(HTTPClientUtils.HOST_NAME_VERIFIER, - String.valueOf(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER)); - - Assert.assertEquals(HTTPClientUtils.getX509HostnameVerifier(), - SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthUtilsTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthUtilsTest.java deleted file mode 100644 index f3b1b2dd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthUtilsTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.app2app.utils.App2AppAuthUtils; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerClientException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerServerException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.impl.DeviceHandlerImpl; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.model.Device; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; - -import java.util.ArrayList; -import java.util.List; - -/** - * Test class for Unit Testing App2AppAuthUtils. - */ -@PrepareForTest({AuthenticatedUser.class, IdentityTenantUtil.class, IdentityExtensionsDataHolder.class}) -@PowerMockIgnore({"javax.net.ssl.*", "jdk.internal.reflect.*"}) -public class App2AppAuthUtilsTest { - - @Test - public void testGetAuthenticatedUserFromSubjectIdentifier() { - - PowerMockito.mockStatic(AuthenticatedUser.class); - // Prepare test data - String subjectIdentifier = "admin@wso2.com"; - // Mock the AuthenticatedUser class - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - // Mock the behavior of AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier() - Mockito.when(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(subjectIdentifier)) - .thenReturn(authenticatedUserMock); - // Call the method under test - AuthenticatedUser user = App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(subjectIdentifier); - // Verify the result - Assert.assertNotNull(user, "Authenticated user should not be null"); - Assert.assertEquals(user, authenticatedUserMock, "Returned user should match the mocked user"); - } - - @Test - public void testGetUserRealm() throws UserStoreException { - - // Mock the AuthenticatedUser - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - Mockito.when(authenticatedUserMock.getTenantDomain()).thenReturn("testTenantDomain"); - // Mock IdentityTenantUtil - PowerMockito.mockStatic(IdentityTenantUtil.class); - Mockito.when(IdentityTenantUtil.getTenantId(Mockito.anyString())).thenReturn(1234); - // Mock RealmService and UserRealm - RealmService realmServiceMock = Mockito.mock(RealmService.class); - UserRealm userRealmMock = Mockito.mock(UserRealm.class); - Mockito.when(realmServiceMock.getTenantUserRealm(1234)).thenReturn(userRealmMock); - // Mock IdentityExtensionsDataHolder - IdentityExtensionsDataHolder dataHolderMock = Mockito.mock(IdentityExtensionsDataHolder.class); - Mockito.when(dataHolderMock.getRealmService()).thenReturn(realmServiceMock); - PowerMockito.mockStatic(IdentityExtensionsDataHolder.class); - Mockito.when(IdentityExtensionsDataHolder.getInstance()).thenReturn(dataHolderMock); - // Call the method under test - UserRealm userRealm = App2AppAuthUtils.getUserRealm(authenticatedUserMock); - // Verify the result - Assert.assertEquals(userRealm, userRealmMock, "UserRealm should match the mocked UserRealm"); - } - - @Test - public void testGetUserRealmWhenUserIsNull() throws UserStoreException { - - // Call the method under test - UserRealm userRealm = App2AppAuthUtils.getUserRealm(null); - // Verify the result - Assert.assertNull(userRealm, "UserRealm should be null when the input is null."); - } - - @Test - public void testGetUserIdFromUsername() throws UserStoreException, OpenBankingException { - - // Prepare test data - String username = "admin@wso2.com"; - String userIDMock = "354cd9f4-ae85-4ce9-8c42-dc1111ac8acf"; - // Mock the UserRealm - UserRealm userRealmMock = Mockito.mock(UserRealm.class); - // Mock the AbstractUserStoreManager - AbstractUserStoreManager userStoreManagerMock = Mockito.mock(AbstractUserStoreManager.class); - Mockito.when(userStoreManagerMock.getUserIDFromUserName(username)).thenReturn(userIDMock); - // Mock the RealmService - Mockito.when(userRealmMock.getUserStoreManager()).thenReturn(userStoreManagerMock); - // Call the method under test - String userId = App2AppAuthUtils.getUserIdFromUsername(username, userRealmMock); - // Verify the result - Assert.assertNotNull(userId, "User ID should not be null"); - Assert.assertEquals(userId, userIDMock , - "User ID should match the expected value"); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testGetUserIdFromUsernameWhenRealmNull() throws UserStoreException, OpenBankingException { - - // Prepare test data - String username = "admin@wso2.com"; - // Mock the UserRealm - UserRealm userRealmMock = null; - // Call the method under test - String userId = App2AppAuthUtils.getUserIdFromUsername(username, userRealmMock); - } - - @Test - public void testGetPublicKey() throws PushDeviceHandlerServerException, PushDeviceHandlerClientException, - OpenBankingException { - - // Prepare test data - String deviceID = "testDeviceID"; - String invalidDeviceId = "invalidDeviceID"; - String userID = "testUserID"; - String publicKey = "testPublicKey"; - // Mock DeviceHandlerImpl and Device - DeviceHandlerImpl deviceHandlerMock = Mockito.mock(DeviceHandlerImpl.class); - Device deviceMockI = Mockito.mock(Device.class); - Device deviceMockII = Mockito.mock(Device.class); - Mockito.when(deviceMockI.getPublicKey()).thenReturn(publicKey); - Mockito.when(deviceMockI.getDeviceId()).thenReturn(deviceID); - Mockito.when(deviceMockII.getPublicKey()).thenReturn(publicKey); - Mockito.when(deviceMockII.getDeviceId()).thenReturn(invalidDeviceId); - // Mock DeviceHandlerImpl.listDevices() to return a list with the mock device - List deviceList = new ArrayList<>(); - deviceList.add(deviceMockI); - deviceList.add(deviceMockII); - Mockito.when(deviceHandlerMock.listDevices(userID)).thenReturn(deviceList); - Mockito.when(deviceHandlerMock.getPublicKey(deviceID)).thenReturn(publicKey); - // Call the method under test - String result = App2AppAuthUtils.getPublicKey(deviceID, userID, deviceHandlerMock); - // Verify the result - Assert.assertEquals(result, publicKey, "Public key should match"); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void testGetPublicKeyInvalidDeviceID() throws PushDeviceHandlerServerException, - PushDeviceHandlerClientException, OpenBankingException { - - // Prepare test data - String deviceID = "testDeviceID"; - String invalidDeviceId = "invalidDeviceID"; - String userID = "testUserID"; - String publicKey = "testPublicKey"; - // Mock DeviceHandlerImpl and Device - DeviceHandlerImpl deviceHandlerMock = Mockito.mock(DeviceHandlerImpl.class); - Device deviceMock = Mockito.mock(Device.class); - Mockito.when(deviceMock.getPublicKey()).thenReturn(publicKey); - Mockito.when(deviceMock.getDeviceId()).thenReturn(invalidDeviceId); - // Mock DeviceHandlerImpl.listDevices() to return a list with the mock device - List deviceList = new ArrayList<>(); - deviceList.add(deviceMock); - Mockito.when(deviceHandlerMock.listDevices(userID)).thenReturn(deviceList); - Mockito.when(deviceHandlerMock.getPublicKey(userID)).thenReturn(publicKey); - // Call the method under test - String result = App2AppAuthUtils.getPublicKey(deviceID, userID, deviceHandlerMock); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthValidationTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthValidationTest.java deleted file mode 100644 index 36e24abd..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthValidationTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.app2app.cache.JTICache; -import com.wso2.openbanking.accelerator.identity.app2app.exception.JWTValidationException; -import com.wso2.openbanking.accelerator.identity.app2app.model.DeviceVerificationToken; -import com.wso2.openbanking.accelerator.identity.app2app.testutils.App2AppUtilsTestJWTDataProvider; -import com.wso2.openbanking.accelerator.identity.app2app.utils.App2AppAuthUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.IObjectFactory; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; -import java.text.ParseException; -import java.util.Date; - -/** - * Test class for unit testing App2AppAuthValidations. - */ -@PrepareForTest({JTICache.class, JWTUtils.class}) -@PowerMockIgnore({"javax.net.ssl.*", "jdk.internal.reflect.*"}) -public class App2AppAuthValidationTest { - - @Test(dataProviderClass = App2AppUtilsTestJWTDataProvider.class, - dataProvider = "ValidJWTProvider") - public void validationTest(String jwtString, String publicKey, String requestObject) throws ParseException, - OpenBankingException, JOSEException, NoSuchAlgorithmException, InvalidKeySpecException { - - //Mocking JTICache and JWTUtils - PowerMockito.mockStatic(JTICache.class); - PowerMockito.mockStatic(JWTUtils.class); - Mockito.when(JTICache.getJtiDataFromCache(Mockito.anyString())).thenReturn(null); - Mockito.when(JWTUtils.isValidSignature(Mockito.any(SignedJWT.class), Mockito.anyString())) - .thenReturn(true); - Mockito.when(JWTUtils.isValidExpiryTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - Mockito.when(JWTUtils.isValidNotValidBeforeTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - //Creating a new device verification token using signed jwt - SignedJWT signedJWT = SignedJWT.parse(jwtString); - DeviceVerificationToken deviceVerificationToken = new DeviceVerificationToken(signedJWT); - deviceVerificationToken.setPublicKey(publicKey); - deviceVerificationToken.setRequestObject(requestObject); - // Call the method under test - App2AppAuthUtils.validateToken(deviceVerificationToken); - } - - @Test(expectedExceptions = JWTValidationException.class, - dataProviderClass = App2AppUtilsTestJWTDataProvider.class, - dataProvider = "ValidJWTProvider") - public void validationTestJTIReplayed(String jwtString, String publicKey, String requestObject) throws - ParseException, OpenBankingException, JOSEException, NoSuchAlgorithmException, InvalidKeySpecException { - - //Mocking JTICache and JWTUtils - PowerMockito.mockStatic(JTICache.class); - PowerMockito.mockStatic(JWTUtils.class); - Mockito.when(JTICache.getJtiDataFromCache(Mockito.anyString())).thenReturn("NotNullJTI"); - Mockito.when(JWTUtils.isValidSignature(Mockito.any(SignedJWT.class), Mockito.anyString())) - .thenReturn(true); - Mockito.when(JWTUtils.isValidExpiryTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - Mockito.when(JWTUtils.isValidNotValidBeforeTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - //Creating a new device verification token using signed jwt - SignedJWT signedJWT = SignedJWT.parse(jwtString); - DeviceVerificationToken deviceVerificationToken = new DeviceVerificationToken(signedJWT); - deviceVerificationToken.setPublicKey(publicKey); - deviceVerificationToken.setRequestObject(requestObject); - // Call the method under test - App2AppAuthUtils.validateToken(deviceVerificationToken); - } - - @Test(expectedExceptions = JWTValidationException.class, - dataProviderClass = App2AppUtilsTestJWTDataProvider.class, - dataProvider = "ValidJWTProvider") - public void validationTestJWTExpired(String jwtString, String publicKey, String requestObject) throws - ParseException, OpenBankingException, JOSEException, NoSuchAlgorithmException, InvalidKeySpecException { - - //Mocking JTICache and JWTUtils - PowerMockito.mockStatic(JTICache.class); - PowerMockito.mockStatic(JWTUtils.class); - Mockito.when(JTICache.getJtiDataFromCache(Mockito.anyString())).thenReturn(null); - Mockito.when(JWTUtils.isValidSignature(Mockito.any(SignedJWT.class), Mockito.anyString())) - .thenReturn(true); - Mockito.when(JWTUtils.isValidExpiryTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(false); - Mockito.when(JWTUtils.isValidNotValidBeforeTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - //Creating a new device verification token using signed jwt - SignedJWT signedJWT = SignedJWT.parse(jwtString); - DeviceVerificationToken deviceVerificationToken = new DeviceVerificationToken(signedJWT); - deviceVerificationToken.setPublicKey(publicKey); - deviceVerificationToken.setRequestObject(requestObject); - // Call the method under test - App2AppAuthUtils.validateToken(deviceVerificationToken); - } - - @Test(expectedExceptions = JWTValidationException.class, - dataProviderClass = App2AppUtilsTestJWTDataProvider.class, - dataProvider = "ValidJWTProvider") - public void validationTestJWTNotActive(String jwtString, String publicKey, String requestObject) throws - ParseException, OpenBankingException, JOSEException, NoSuchAlgorithmException, InvalidKeySpecException { - - //Mocking JTICache and JWTUtils - PowerMockito.mockStatic(JTICache.class); - PowerMockito.mockStatic(JWTUtils.class); - Mockito.when(JTICache.getJtiDataFromCache(Mockito.anyString())).thenReturn(null); - Mockito.when(JWTUtils.isValidSignature(Mockito.any(SignedJWT.class), Mockito.anyString())). - thenReturn(true); - Mockito.when(JWTUtils.isValidExpiryTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - Mockito.when(JWTUtils.isValidNotValidBeforeTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(false); - //Creating a new device verification token using signed jwt - SignedJWT signedJWT = SignedJWT.parse(jwtString); - DeviceVerificationToken deviceVerificationToken = new DeviceVerificationToken(signedJWT); - deviceVerificationToken.setPublicKey(publicKey); - deviceVerificationToken.setRequestObject(requestObject); - // Call the method under test - App2AppAuthUtils.validateToken(deviceVerificationToken); - } - - @Test(expectedExceptions = JWTValidationException.class, - dataProviderClass = App2AppUtilsTestJWTDataProvider.class, - dataProvider = "invalidDigestProvider") - public void validationTestInvalidDigest(String jwtString, String publicKey, String requestObject) throws - ParseException, OpenBankingException, JOSEException, NoSuchAlgorithmException, InvalidKeySpecException { - - //Mocking JTICache and JWTUtils - PowerMockito.mockStatic(JTICache.class); - PowerMockito.mockStatic(JWTUtils.class); - Mockito.when(JTICache.getJtiDataFromCache(Mockito.anyString())).thenReturn(null); - Mockito.when(JWTUtils.isValidSignature(Mockito.any(SignedJWT.class), Mockito.anyString())). - thenReturn(true); - Mockito.when(JWTUtils.isValidExpiryTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - Mockito.when(JWTUtils.isValidNotValidBeforeTime(Mockito.any(Date.class), Mockito.any(long.class))) - .thenReturn(true); - //Creating a new device verification token using signed jwt - SignedJWT signedJWT = SignedJWT.parse(jwtString); - DeviceVerificationToken deviceVerificationToken = new DeviceVerificationToken(signedJWT); - deviceVerificationToken.setPublicKey(publicKey); - deviceVerificationToken.setRequestObject(requestObject); - // Call the method under test - App2AppAuthUtils.validateToken(deviceVerificationToken); - } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticatorTest.java deleted file mode 100644 index 812b4e08..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/App2AppAuthenticatorTest.java +++ /dev/null @@ -1,281 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.app2app.testutils.App2AppAuthenticatorTestDataProvider; -import com.wso2.openbanking.accelerator.identity.app2app.utils.App2AppAuthUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerClientException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerServerException; -import org.wso2.carbon.user.api.UserStoreException; - -import java.text.ParseException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static org.testng.Assert.assertEquals; - -/** - * Test class for unit testing App2AppAuthenticator. - */ -@PrepareForTest({App2AppAuthUtils.class, JWTUtils.class}) -@PowerMockIgnore({"javax.net.ssl.*", "jdk.internal.reflect.*"}) -public class App2AppAuthenticatorTest { - - private HttpServletRequest mockRequest; - private HttpServletResponse mockResponse; - - private AuthenticationContext mockAuthenticationContext; - private App2AppAuthenticator app2AppAuthenticator; - - @BeforeTest - public void setup() { - - // setting the authenticator for testing - app2AppAuthenticator = new App2AppAuthenticator(); - //Mocking the behaviour of request, response and authenticationContext - mockRequest = Mockito.mock(HttpServletRequest.class); - mockResponse = Mockito.mock(HttpServletResponse.class); - mockAuthenticationContext = Mockito.mock(AuthenticationContext.class); - } - - @Test - public void testGetName() { - - String expectedName = App2AppAuthenticatorConstants.AUTHENTICATOR_NAME; - String actualName = app2AppAuthenticator.getName(); - // Invoke the method under test - assertEquals(actualName, expectedName, "Expected and actual names should match."); - } - - @Test - public void testGetFriendlyName() { - - String expectedFriendlyName = App2AppAuthenticatorConstants.AUTHENTICATOR_FRIENDLY_NAME; - String actualFriendlyName = app2AppAuthenticator.getFriendlyName(); - // Invoke the method under test - assertEquals(actualFriendlyName, expectedFriendlyName, - "Expected and actual friendly names should match"); - } - - @Test(dataProviderClass = App2AppAuthenticatorTestDataProvider.class , - dataProvider = "app_auth_identifier_provider") - public void canHandleTestCase(String secret, String expected) { - - // Set up mock behavior for HttpServletRequest - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(secret); - // Invoke the method under test - assertEquals(Boolean.valueOf(expected).booleanValue(), app2AppAuthenticator.canHandle(mockRequest), - "Invalid can handle response for the request."); - } - - @Test(expectedExceptions = AuthenticationFailedException.class) - public void initiateAuthenticationRequest() throws AuthenticationFailedException { - - // Invoke the method under test - app2AppAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthenticationContext); - } - - @Test(dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "sessionDataKeyProvider") - public void getContextIdentifierTest(String sessionDataKey) { - - // Set up mock behavior for HttpServletRequest - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.SESSION_DATA_KEY)) - .thenReturn(sessionDataKey); - // Invoke the method under test - String output = app2AppAuthenticator.getContextIdentifier(mockRequest); - assertEquals(sessionDataKey, output); - } - - @Test(dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider") - public void testProcessAuthenticationResponse_success(String jwtString) { - - PowerMockito.mockStatic(App2AppAuthUtils.class); - // Set up mock behavior for HttpServletRequest - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock the authenticated user - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - // Mock the behavior of App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier() to return a mocked user - Mockito.when(App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())) - .thenReturn(authenticatedUserMock); - - try { - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - // Verify that the authentication context subject is set (or any other verification) - Mockito.verify(mockAuthenticationContext).setSubject(authenticatedUserMock); - } catch (Exception e) { - // If any unexpected exception occurs, fail the test - Assert.fail("Unexpected exception occurred: " + e.getMessage()); - } - } - @Test(expectedExceptions = AuthenticationFailedException.class, - dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider" - ) - public void testProcessAuthenticationResponse_IllegalArgumentException(String jwtString) - throws AuthenticationFailedException { - - PowerMockito.mockStatic(App2AppAuthUtils.class); - // Mock the behavior of HttpServletRequest to return a value for login hint - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier to throw IllegalArgumentException - Mockito.when(App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())) - .thenThrow(new IllegalArgumentException("Failed to create Local Authenticated User from the given " + - "subject identifier. Invalid argument. authenticatedSubjectIdentifier : ")); - // Invoke the method under test - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, - dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider" - ) - public void testProcessAuthenticationResponse_ParseException(String jwtString) - throws AuthenticationFailedException, ParseException { - - PowerMockito.mockStatic(JWTUtils.class); - // Mock the behavior of HttpServletRequest to return a value for login hint - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier to throw IllegalArgumentException - Mockito.when(JWTUtils.getSignedJWT(Mockito.anyString())) - .thenThrow(new ParseException("JWT Not parsable.", 1)); - // Invoke the method under test - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, - dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider" - ) - public void testProcessAuthenticationResponse_UserStoreException(String jwtString) - throws AuthenticationFailedException, UserStoreException { - - PowerMockito.mockStatic(App2AppAuthUtils.class); - // Mock the behavior of HttpServletRequest to return a value for login hint - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock the behavior of App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier() to return a mock user - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - Mockito.when(App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())) - .thenReturn(authenticatedUserMock); - // Mock the behavior of getPublicKeyByDeviceID() to throw UserStoreException - Mockito.when(App2AppAuthUtils.getUserRealm(Mockito.any(AuthenticatedUser.class))) - .thenThrow(new UserStoreException(App2AppAuthenticatorConstants.USER_STORE_EXCEPTION_MESSAGE)); - // Invoke the method under test - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, - dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider" - ) - public void testProcessAuthenticationResponse_PushDeviceHandlerServerException(String jwtString) - throws AuthenticationFailedException, OpenBankingException, PushDeviceHandlerServerException, - PushDeviceHandlerClientException { - - PowerMockito.mockStatic(App2AppAuthUtils.class); - // Mock the behavior of HttpServletRequest to return a value for login hint - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock the behavior of App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier() to return a mock user - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - Mockito.when(App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())) - .thenReturn(authenticatedUserMock); - // Mock the behavior of getPublicKeyByDeviceID() to throw UserStoreException - Mockito.when(App2AppAuthUtils.getPublicKey(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenThrow(new PushDeviceHandlerServerException( - App2AppAuthenticatorConstants.PUSH_DEVICE_HANDLER_SERVER_EXCEPTION_MESSAGE)); - // Invoke the method under test - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, - dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider" - ) - public void testProcessAuthenticationResponse_PushDeviceHandlerClientException(String jwtString) - throws AuthenticationFailedException, OpenBankingException, PushDeviceHandlerServerException, - PushDeviceHandlerClientException { - - PowerMockito.mockStatic(App2AppAuthUtils.class); - // Mock the behavior of HttpServletRequest to return a value for login hint - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock the behavior of App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier() to return a mock user - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - Mockito.when(App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())) - .thenReturn(authenticatedUserMock); - // Mock the behavior of getPublicKeyByDeviceID() to throw UserStoreException - Mockito.when(App2AppAuthUtils.getPublicKey(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenThrow(new PushDeviceHandlerClientException( - App2AppAuthenticatorConstants.PUSH_DEVICE_HANDLER_CLIENT_EXCEPTION_MESSAGE)); - // Invoke the method under test - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, - dataProviderClass = App2AppAuthenticatorTestDataProvider.class, - dataProvider = "AppAuthIdentifierProvider" - ) - public void testProcessAuthenticationResponse_OpenBankingException(String jwtString) - throws AuthenticationFailedException, OpenBankingException, PushDeviceHandlerServerException, - PushDeviceHandlerClientException { - - PowerMockito.mockStatic(App2AppAuthUtils.class); - // Mock the behavior of HttpServletRequest to return a value for login hint - Mockito.when(mockRequest.getParameter(App2AppAuthenticatorConstants.DEVICE_VERIFICATION_TOKEN_IDENTIFIER)) - .thenReturn(jwtString); - // Mock the behavior of App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier() to return a mock user - AuthenticatedUser authenticatedUserMock = Mockito.mock(AuthenticatedUser.class); - Mockito.when(App2AppAuthUtils.getAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())) - .thenReturn(authenticatedUserMock); - // Mock the behavior of getPublicKeyByDeviceID() to throw UserStoreException - Mockito.when(App2AppAuthUtils.getPublicKey(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenThrow(new OpenBankingException( - App2AppAuthenticatorConstants.OPEN_BANKING_EXCEPTION_MESSAGE)); - // Invoke the method under test - app2AppAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthenticationContext); - } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/testutils/App2AppAuthenticatorTestDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/testutils/App2AppAuthenticatorTestDataProvider.java deleted file mode 100644 index ac39da2e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/testutils/App2AppAuthenticatorTestDataProvider.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.testutils; - -import org.testng.annotations.DataProvider; - -/** - * Data Provider class for testing App2AppAuthenticator. - */ -public class App2AppAuthenticatorTestDataProvider { - private static final String validAppAuthIdentifier = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaWQiOiI1NTBmNDQ1My05NTQ3LTRlNGYtYmUwNi04ZGIyZWVkNTYzYjMiLCJsb" + - "2dpbl9oaW50IjoiYWRtaW5Ad3NvMi5jb20iLCJpYXQiOjE3MTYyNjQ5NTUsImp0aSI6IjA1NDU1Zjc1LTkwMmUtNDFhNi04ZDg4LWV" + - "jZTUwZDM2OTc2NSIsImRpZ2VzdCI6IlNIQS0yNTY9RWtIOGZQZ1oyVFkyWEduczhjNVZ2Y2U4aDNEQjgzVit3NDd6SGl5WWZpUT0iL" + - "CJleHAiOjE3MTYyNjY3NTUsIm5iZiI6MTcxNjI2NDk1NX0.C0OGMkkaosP2FSLFtqmCgRhrCG7nCJCDLsikkbFWwc5NdzxCFyYUQVI" + - "Zx4HIRQdabg5K8Ox-WYeqwdhajaKs5Uk63tz5UjlPzX0IKsklXgnWUxdMwfrYsu-znTce0Tc-Ph0h8a8jXF2CKTOfWxwuQvgevSqJe" + - "-K6zrbJmO8imu4"; - @DataProvider(name = "app_auth_identifier_provider") - public Object[][] getAppAuthIdentifier() { - - return new String[][]{ - {validAppAuthIdentifier, "true"}, - {null, "false"}, - {"", "false"}, - }; - } - - @DataProvider(name = "sessionDataKeyProvider") - public Object[][] getSessionDataKey() { - - return new String[][]{ - {null}, - {""}, - {"550e8400-e29b-41d4-a716-446655440000"}, - {"aaaaaaa-bbbb-Cccc-dddd-eeeeeeeeeeeee"} - }; - } - - @DataProvider(name = "AppAuthIdentifierProvider") - public Object[][] getJWT() { - return new String[][]{ - {validAppAuthIdentifier}, - }; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/testutils/App2AppUtilsTestJWTDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/testutils/App2AppUtilsTestJWTDataProvider.java deleted file mode 100644 index ffbc0f39..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/app2app/testutils/App2AppUtilsTestJWTDataProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.app2app.testutils; - -import org.testng.annotations.DataProvider; - -/** - * JWT Data provider for App2AppAuthValidation Testing. - */ -public class App2AppUtilsTestJWTDataProvider { - - private final String validPublicKey = - "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLyl7YvRhy57IbxuhV4n7OZw0mmnnXNsDJmL4YQNXy2bRCs59pJb+TYO" + - "HsR1xCsq3WH7bX1Ik/EI3weQd2zcxNbtDAUSXSy7jRBuFm1Sk52lASBbmdeOstiqlsg9ptIp/o7u1366cRjn32cXhhsR0y" + - "/spUGy8IiXz9rJfP5bEgHQIDAQ"; - private final String validAppAuthIdentifier = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaWQiOiI1NTBmNDQ1My05NTQ3LTRlNGYtYmUwNi04ZGIyZWVkNTYzYjMiLCJsb" + - "2dpbl9oaW50IjoiYWRtaW5Ad3NvMi5jb20iLCJpYXQiOjE3MTYyNjQ5NTUsImp0aSI6IjA1NDU1Zjc1LTkwMmUtNDFhNi04ZDg4LWV" + - "jZTUwZDM2OTc2NSIsImRpZ2VzdCI6IlNIQS0yNTY9RWtIOGZQZ1oyVFkyWEduczhjNVZ2Y2U4aDNEQjgzVit3NDd6SGl5WWZpUT0iL" + - "CJleHAiOjE3MTYyNjY3NTUsIm5iZiI6MTcxNjI2NDk1NX0.C0OGMkkaosP2FSLFtqmCgRhrCG7nCJCDLsikkbFWwc5NdzxCFyYUQVI" + - "Zx4HIRQdabg5K8Ox-WYeqwdhajaKs5Uk63tz5UjlPzX0IKsklXgnWUxdMwfrYsu-znTce0Tc-Ph0h8a8jXF2CKTOfWxwuQvgevSqJe" + - "-K6zrbJmO8imu4"; - private final String appAuthIdentifierMissingDigest = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaWQiOiI1NTBmNDQ1My05NTQ3LTRlNGYtYmUwNi04ZGIyZWVkNTYzYjMiLCJsb" + - "2dpbl9oaW50IjoiYWRtaW5Ad3NvMi5jb20iLCJpYXQiOjE3MTYyNjcyMDMsImp0aSI6ImZkNDhmOWMzLTYyZDMtNDUzZS04MWY2LTF" + - "kMGE4ZDIzM2YzZiIsImV4cCI6MTcxNjI2OTAwMywibmJmIjoxNzE2MjY3MjAzfQ.C_G5-_McCMTz6D01XpPVfrdGlPLaKli9cqWL5K" + - "nd5ntlDq5ww7J769EJdCGt-S5sfgg5hrPRhyIWK2MJwavGTMzsp1vGdUQXQkT7z68_20k82Lms67tQLIM1VUCDc9rqz5Pule5bVqbY" + - "oZFmFlHU0Hcmvy166J6c9HlySyMC994"; - private final String appAuthIdentifierInvalidDigest = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaWQiOiI1NTBmNDQ1My05NTQ3LTRlNGYtYmUwNi04ZGIyZWVkNTYzYjMiLCJsb" + - "2dpbl9oaW50IjoiYWRtaW5Ad3NvMi5jb20iLCJpYXQiOjE3MTYyNjc0MjYsImp0aSI6IjYyM2ZhZDY3LTc0ZDMtNDk4OS04YTc1LTE" + - "2OWYxNDQzOGUwZiIsImRpZ2VzdCI6IlNIQS0yNTY9WUJlc3lUWnhIMWtBVitMTTNKMzZDdzQrVXlQYWlKS0VydVhsdGxsbS9DRT0iL" + - "CJleHAiOjE3MTYyNjkyMjYsIm5iZiI6MTcxNjI2NzQyNn0.hsuj0osE-o_hyOif7eUvVFIfJpmzF2bDqeINj2Qq2XMQ1Lbnf7LgYMG" + - "POzmtMi1Jp9Ivwl_3Wt35PcCVko2LI2TIoG-JB8MMeWc1okwwdWGP8Rz5TWCnaXiPGeeFw4PjuV3JMbWeTFafqUFtJUX7pU-8q_hiQ" + - "zxK1mGjRTjDXRA"; - private final String validRequestObject = - "eyJraWQiOiI3ZUo4U19aZ3ZsWXhGQUZTZ2hWOXhNSlJPdmsiLCJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJtYXhfYWdlIjo4N" + - "jQwMCwiYXVkIjoiaHR0cHM6Ly8xOTIuMTY4LjQzLjQ5Ojk0NDYvb2F1dGgyL3Rva2VuIiwic2NvcGUiOiJhY2NvdW50cyBvcGVuaWQ" + - "iLCJpc3MiOiI2RWZaSTVOUnByTm9tZlFQWElQZjFSN0ZsNUVhIiwiY2xhaW1zIjp7ImlkX3Rva2VuIjp7ImFjciI6eyJ2YWx1ZXMiO" + - "lsidXJuOm9wZW5iYW5raW5nOnBzZDI6c2NhIiwidXJuOm9wZW5iYW5raW5nOnBzZDI6Y2EiXSwiZXNzZW50aWFsIjp0cnVlfSwib3B" + - "lbmJhbmtpbmdfaW50ZW50X2lkIjp7InZhbHVlIjoiZTkyNmE2MzItYzlkMy00MmEwLWEyM2YtMWEwMWZhNDAwOWU3IiwiZXNzZW50a" + - "WFsIjp0cnVlfX0sInVzZXJpbmZvIjp7Im9wZW5iYW5raW5nX2ludGVudF9pZCI6eyJ2YWx1ZSI6ImU5MjZhNjMyLWM5ZDMtNDJhMC1" + - "hMjNmLTFhMDFmYTQwMDllNyIsImVzc2VudGlhbCI6dHJ1ZX19fSwicmVzcG9uc2VfdHlwZSI6ImNvZGUgaWRfdG9rZW4iLCJyZWRpc" + - "mVjdF91cmkiOiJodHRwczovL3d3dy5tb2NrY29tcGFueS5jb20vcmVkaXJlY3RzL3JlZGlyZWN0MSIsInN0YXRlIjoiWVdsemNEb3p" + - "NVFE0IiwiZXhwIjoxODA3MjMzNDc4LCJub25jZSI6Im4tMFM2X1d6QTJNbCIsImNsaWVudF9pZCI6IjZFZlpJNU5ScHJOb21mUVBYS" + - "VBmMVI3Rmw1RWEifQ.nKapNc1N5AHxil-xbVpSXrDRsGYkn1YHe1jURxZMVRluDWnyRmjVce9AJ5lCl338Jg0EsU4CNmLwOSu7zmtl" + - "DCFz4fCIHLj1Q8A-C5I9cWE-nAlV1HnCR_3V7cTU4YE13ZIH7bMCqOPfBX_fpDkJeDXoSnRHQtipMPqIwNfmv7Kf4SjPpZ7kT5zmDn" + - "cHsUqotpPVoPka_-Nal0KL_-PknC31pKECcxakOFNTeAeiODZN5JIyKGFtq10jQaJi7YvDKsGg1l3rv1gUdJ4s5eXqmnxJUu4J6ocY" + - "h26Nz3l_Xc1p7XIm2HPhvSW3DpbNpE8Ej0kJkI9FgWz77QACkiO4Hg"; - - @DataProvider(name = "ValidJWTProvider") - public Object[][] getDigest() { - return new String[][]{ - {validAppAuthIdentifier, validPublicKey, null}, - {validAppAuthIdentifier, validPublicKey, validRequestObject} - }; - } - - @DataProvider(name = "invalidDigestProvider") - public Object[][] getInvalidDigest() { - return new String[][]{ - {appAuthIdentifierMissingDigest, validPublicKey, validRequestObject}, - {appAuthIdentifierInvalidDigest, validPublicKey, validRequestObject} - }; - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/application/listener/ApplicationManagementListenerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/application/listener/ApplicationManagementListenerTest.java deleted file mode 100644 index b041f815..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/application/listener/ApplicationManagementListenerTest.java +++ /dev/null @@ -1,302 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.application.listener; - -import com.wso2.openbanking.accelerator.common.config.TextFileReader; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.listener.application.ApplicationUpdaterImpl; -import com.wso2.openbanking.accelerator.identity.listener.application.OBApplicationManagementListener; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.IdentityProvider; -import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; -import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; -import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test for application management listener. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@WithCarbonHome -@PrepareForTest({CarbonContext.class}) -public class ApplicationManagementListenerTest extends PowerMockTestCase { - - private static final Log log = LogFactory.getLog(ApplicationManagementListenerTest.class); - - ServiceProvider serviceProvider; - - IdentityExtensionsDataHolder identityExtensionsDataHolder; - - OAuthAdminServiceImpl oAuthAdminService; - - ApplicationManagementService applicationManagementService; - - ApplicationUpdaterImpl applicationUpdater; - - @InjectMocks - OBApplicationManagementListener applicationManagementListener = new OBApplicationManagementListener(); - - @InjectMocks - ApplicationUpdaterImpl applicationUpdaterImpl = new ApplicationUpdaterImpl(); - - - @BeforeClass - public void beforeClass() { - - identityExtensionsDataHolder = Mockito.mock(IdentityExtensionsDataHolder.class); - oAuthAdminService = Mockito.mock(OAuthAdminServiceImpl.class);; - applicationManagementService = Mockito.mock(ApplicationManagementService.class);; - applicationUpdater = Mockito.mock(ApplicationUpdaterImpl.class);; - - Map confMap = new HashMap<>(); - List regulatoryIssuers = new ArrayList<>(); - regulatoryIssuers.add("OpenBanking Ltd"); - regulatoryIssuers.add("CDR"); - confMap.put(IdentityCommonConstants.PRIMARY_AUTHENTICATOR_DISPLAYNAME, "Basic"); - confMap.put(IdentityCommonConstants.PRIMARY_AUTHENTICATOR_NAME, "BasicAuthenticator"); - confMap.put(IdentityCommonConstants.IDENTITY_PROVIDER_NAME, "SMSAuthentication"); - confMap.put(IdentityCommonConstants.IDENTITY_PROVIDER_STEP, "2"); - confMap.put(DCRCommonConstants.REGULATORY_ISSUERS, regulatoryIssuers); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(confMap); - IdentityExtensionsDataHolder.getInstance().setApplicationManagementService(applicationManagementService); - IdentityExtensionsDataHolder.getInstance().setOauthAdminService(oAuthAdminService); - serviceProvider = new ServiceProvider(); - ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty(); - serviceProviderProperty.setDisplayName(DCRCommonConstants.SOFTWARE_STATEMENT); - serviceProviderProperty.setName(DCRCommonConstants.SOFTWARE_STATEMENT); - serviceProviderProperty.setValue("dfdfdfd"); - ServiceProviderProperty[] spPropertyArray = new ServiceProviderProperty[1]; - spPropertyArray[0] = serviceProviderProperty; - serviceProvider.setSpProperties(spPropertyArray); - serviceProvider.setApplicationName("testApp"); - - TextFileReader textFileReader = TextFileReader.getInstance(); - textFileReader.setDirectoryPath("src/test/resources"); - } - - @Test - public void testPostApplicationCreation() throws IdentityApplicationManagementException, - IdentityOAuthAdminException { - - when(identityExtensionsDataHolder.getOauthAdminService()).thenReturn(oAuthAdminService); - when(identityExtensionsDataHolder.getApplicationManagementService()). - thenReturn(applicationManagementService); - - when(oAuthAdminService.getOAuthApplicationDataByAppName(anyString())) - .thenReturn(new OAuthConsumerAppDTO()); - - when(identityExtensionsDataHolder.getAbstractApplicationUpdater()) - .thenReturn(applicationUpdater); - - boolean isSuccess = applicationManagementListener.doPostCreateApplication(serviceProvider, - "carbon@super", "admin"); - Assert.assertTrue(isSuccess); - - } - - @Test - public void testPreUpdateApplicationCreation() throws IdentityOAuthAdminException, - IdentityApplicationManagementException { - - OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); - oAuthConsumerAppDTO.setApplicationName("testApp"); - OAuthConsumerAppDTO[] oAuthConsumerAppDTOS = new OAuthConsumerAppDTO[1]; - oAuthConsumerAppDTOS[0] = oAuthConsumerAppDTO; - - Map confMap = new HashMap<>(); - List regulatoryIssuers = new ArrayList<>(); - regulatoryIssuers.add("OpenBanking Ltd"); - regulatoryIssuers.add("CDR"); - confMap.put(DCRCommonConstants.REGULATORY_ISSUERS, regulatoryIssuers); - - when(identityExtensionsDataHolder.getOauthAdminService()).thenReturn(oAuthAdminService); - when(identityExtensionsDataHolder.getConfigurationMap()).thenReturn(confMap); - when(oAuthAdminService.getAllOAuthApplicationData()).thenReturn(oAuthConsumerAppDTOS); - applicationManagementListener.doPreUpdateApplication(serviceProvider, "carbon@super", - "admin"); - } - - @Test - public void testPostGetApplicationCreation() throws IdentityApplicationManagementException { - - applicationManagementListener.doPostGetServiceProvider(serviceProvider, "appName", - "carbon@super"); - - } - - @Test - public void testPreDeleteApplicationCreation() throws IdentityApplicationManagementException { - - applicationManagementListener.doPreDeleteApplication("appName", "carbon@super", - "admin"); - - } - - @Test - public void testSetAuthenticators() throws OpenBankingException, IdentityApplicationManagementException { - - IdentityProvider[] federatedIdPs = new IdentityProvider[1]; - IdentityProvider identityProvider = new IdentityProvider(); - identityProvider.setIdentityProviderName("SMSAuthentication"); - federatedIdPs[0] = identityProvider; - - Map confMap = IdentityExtensionsDataHolder.getInstance().getConfigurationMap(); - confMap.put(IdentityCommonConstants.IDENTITY_PROVIDER_STEP, "2"); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(confMap); - - Mockito.when(identityExtensionsDataHolder.getApplicationManagementService()). - thenReturn(applicationManagementService); - - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = - new LocalAndOutboundAuthenticationConfig(); - - Mockito.when(applicationManagementService.getAllIdentityProviders(anyString())). - thenReturn(federatedIdPs); - applicationUpdaterImpl.setAuthenticators(true, "carbon@super", serviceProvider, - localAndOutboundAuthenticationConfig); - Assert.assertNotNull(localAndOutboundAuthenticationConfig.getAuthenticationSteps()); - - } - - @Test - public void testSetAuthenticatorsWithFederatedIdp() throws OpenBankingException, - IdentityApplicationManagementException { - - IdentityProvider[] federatedIdPs = new IdentityProvider[1]; - IdentityProvider identityProvider = new IdentityProvider(); - identityProvider.setIdentityProviderName("SMSAuthentication"); - federatedIdPs[0] = identityProvider; - - Map confMap = IdentityExtensionsDataHolder.getInstance().getConfigurationMap(); - confMap.put(IdentityCommonConstants.IDENTITY_PROVIDER_STEP, "1"); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(confMap); - - Mockito.when(identityExtensionsDataHolder.getApplicationManagementService()). - thenReturn(applicationManagementService); - - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = - new LocalAndOutboundAuthenticationConfig(); - - Mockito.when(applicationManagementService.getAllIdentityProviders(anyString())). - thenReturn(federatedIdPs); - applicationUpdaterImpl.setAuthenticators(true, "carbon@super", serviceProvider, - localAndOutboundAuthenticationConfig); - Assert.assertNotNull(localAndOutboundAuthenticationConfig.getAuthenticationSteps()); - - } - - @Test - public void testSetConditionalAuthScript() throws OpenBankingException { - - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = - new LocalAndOutboundAuthenticationConfig(); - - applicationUpdaterImpl.setConditionalAuthScript(true, serviceProvider, - localAndOutboundAuthenticationConfig); - - Assert.assertNotNull(localAndOutboundAuthenticationConfig.getAuthenticationScriptConfig()); - - } - - @Test - public void testDoPreUpdateApplicationOnAppUpdate() throws OpenBankingException, IdentityOAuthAdminException, - IdentityApplicationManagementException { - - System.setProperty("carbon.home", "/"); - mockStatic(CarbonContext.class); - CarbonContext carbonContext = mock(CarbonContext.class); - when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext); - when(CarbonContext.getThreadLocalCarbonContext().getUsername()).thenReturn("admin"); - - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = - new LocalAndOutboundAuthenticationConfig(); - when(identityExtensionsDataHolder.getOauthAdminService()).thenReturn(oAuthAdminService); - when(identityExtensionsDataHolder.getApplicationManagementService()). - thenReturn(applicationManagementService); - OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); - Mockito.doNothing().when(oAuthAdminService).updateConsumerApplication(anyObject()); - List spProperties = new ArrayList<>(Arrays.asList - (serviceProvider.getSpProperties())); - serviceProvider.setSpProperties(spProperties.toArray(new ServiceProviderProperty[0])); - serviceProvider.setRequestPathAuthenticatorConfigs(new RequestPathAuthenticatorConfig[0]); - Mockito.when(applicationManagementService.getServiceProvider(serviceProvider.getApplicationID())) - .thenReturn(serviceProvider); - applicationUpdaterImpl.doPreUpdateApplication(true, oAuthConsumerAppDTO, serviceProvider, - localAndOutboundAuthenticationConfig, "carbon@super", "admin"); - } - - @Test - public void testDoPreUpdateApplicationOnAppCreate() throws OpenBankingException, IdentityOAuthAdminException { - - System.setProperty("carbon.home", "/"); - mockStatic(CarbonContext.class); - CarbonContext carbonContext = mock(CarbonContext.class); - when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext); - when(CarbonContext.getThreadLocalCarbonContext().getUsername()).thenReturn("admin"); - - LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = - new LocalAndOutboundAuthenticationConfig(); - when(identityExtensionsDataHolder.getOauthAdminService()).thenReturn(oAuthAdminService); - when(identityExtensionsDataHolder.getApplicationManagementService()). - thenReturn(applicationManagementService); - OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); - Mockito.doNothing().when(oAuthAdminService).updateConsumerApplication(anyObject()); - List spProperties = new ArrayList<>(Arrays.asList - (serviceProvider.getSpProperties())); - spProperties.add(IdentityCommonUtil.getServiceProviderProperty("AppCreateRequest", - "true")); - serviceProvider.setSpProperties(spProperties.toArray(new ServiceProviderProperty[0])); - serviceProvider.setRequestPathAuthenticatorConfigs(new RequestPathAuthenticatorConfig[0]); - applicationUpdaterImpl.doPreUpdateApplication(true, oAuthConsumerAppDTO, serviceProvider, - localAndOutboundAuthenticationConfig, "carbon@super", "admin"); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunctionImplTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunctionImplTest.java deleted file mode 100644 index 3dd58d42..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/adaptive/function/OpenBankingAuthenticationWorkerFunctionImplTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.adaptive.function; - -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.json.JSONObject; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; - -import java.util.HashMap; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -/** - * Unit test class for OpenBankingAuthenticationWorkerFunctionImpl class. - */ -public class OpenBankingAuthenticationWorkerFunctionImplTest { - - private JSONObject customJSON; - private OpenBankingAuthenticationWorkerFunction workerFunction; - private AuthenticationContext authenticationContext; - private JsAuthenticationContext jsAuthenticationContext; - - @BeforeTest - void beforeClass() { - - customJSON = new JSONObject(); - customJSON.put("custom", "object"); - IdentityExtensionsDataHolder.getInstance().addWorker((context, properties) -> - customJSON, "customHandlerName"); - workerFunction = new OpenBankingAuthenticationWorkerFunctionImpl(); - authenticationContext = new AuthenticationContext(); - jsAuthenticationContext = new JsAuthenticationContext(authenticationContext); - } - - @Test - public void testHandleInvokeWithExistingWorker() { - - assertEquals(workerFunction.handleRequest(jsAuthenticationContext, - new HashMap<>(), "customHandlerName"), customJSON); - } - - @Test - public void testHandleInvokeWithInvalidWorker() { - - JSONObject jsonObject = workerFunction.handleRequest(jsAuthenticationContext, - new HashMap<>(), "invalidHandlerName"); - assertTrue(jsonObject.has("Error")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/authz/request/OBOAuthAuthzRequestTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/authz/request/OBOAuthAuthzRequestTest.java deleted file mode 100644 index 01864c22..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/authz/request/OBOAuthAuthzRequestTest.java +++ /dev/null @@ -1,328 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.authz.request; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.oltu.oauth2.as.validator.CodeValidator; -import org.apache.oltu.oauth2.common.OAuth; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; -import org.apache.oltu.oauth2.common.validators.OAuthValidator; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth.common.CodeTokenResponseValidator; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; - -/** - * Test for OB authorization request for request_uri support. - */ -@PrepareForTest({IdentityCommonUtil.class, OAuthServerConfiguration.class}) -@PowerMockIgnore("jdk.internal.reflect.*") -public class OBOAuthAuthzRequestTest extends PowerMockTestCase { - - private OBOAuthAuthzRequest obOAuthAuthzRequest; - private HttpServletRequest mockRequest; - private static final String STATE = "abc"; - private static final String SAMPLE_REQUEST_URI = "urn:ietf:params:oauth:request_uri:abc"; - - @BeforeMethod - public void beforeMethod() throws OAuthProblemException { - - // Mock HttpServletRequest - mockRequest = mock(HttpServletRequest.class); - when(mockRequest.getMethod()).thenReturn("POST"); - when(mockRequest.getParameter(IdentityCommonConstants.CLIENT_ID)).thenReturn("1234567"); - - // Mock IdentityCommonUtil - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.handleOAuthProblemException(any(), any(), any())) - .thenReturn(OAuthProblemException.error("invalid_request").description("Error message").state(STATE)); - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_STATE)) - .thenReturn(STATE); - - // Mock OAuthServerConfiguration - OAuthServerConfiguration oAuthServerConfigurationMock = PowerMockito.mock(OAuthServerConfiguration.class); - PowerMockito.mockStatic(OAuthServerConfiguration.class); - PowerMockito.when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfigurationMock); - - // Mock supported response type validators - Map>> - supportedResponseTypeValidators = new Hashtable<>(); - supportedResponseTypeValidators.put("code", CodeValidator.class); - supportedResponseTypeValidators.put("code id_token", CodeTokenResponseValidator.class); - - PowerMockito.when(oAuthServerConfigurationMock.getSupportedResponseTypeValidators()) - .thenReturn(supportedResponseTypeValidators); - } - - @Test - public void testInitValidatorForCodeResponseType() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code"); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_RESPONSE_TYPE)) - .thenReturn("code"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.initValidator().getClass(), CodeValidator.class); - } - - @Test - public void testInitValidatorForHybridResponseType() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_RESPONSE_TYPE)) - .thenReturn("code id_token"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.initValidator().getClass(), CodeTokenResponseValidator.class); - } - - @Test(expectedExceptions = OAuthProblemException.class) - public void testInitValidatorWithoutResponseTypeParam() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_RESPONSE_TYPE)) - .thenReturn(null); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - } - - @Test(expectedExceptions = OAuthProblemException.class) - public void testInitValidatorWithUnsupportedResponseTypeParam() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_RESPONSE_TYPE)) - .thenReturn("unsupported"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - } - - @Test - public void testValidGetScopesFromRequestURI() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - when(mockRequest.getParameter(IdentityCommonConstants.REQUEST_URI)).thenReturn(SAMPLE_REQUEST_URI); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_SCOPE)) - .thenReturn("openid"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.getScopes(), new HashSet<>(Collections.singletonList("openid"))); - } - - @Test - public void testValidGetScopesFromRequest() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.getScopes(), new HashSet<>(Collections.singletonList("openid"))); - } - - @Test - public void testValidGetResponseTypeFromRequestURI() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - when(mockRequest.getParameter(IdentityCommonConstants.REQUEST_URI)).thenReturn(SAMPLE_REQUEST_URI); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_RESPONSE_TYPE)) - .thenReturn("code id_token"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.getResponseType(), "code id_token"); - } - - @Test - public void testValidGetResponseTypeFromRequest() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.getResponseType(), "code id_token"); - } - - @Test - public void testValidGetStateFromRequestURI() throws OAuthProblemException, OAuthSystemException { - - // Mock - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - when(mockRequest.getParameter(IdentityCommonConstants.REQUEST_URI)).thenReturn(SAMPLE_REQUEST_URI); - - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_STATE)) - .thenReturn("abc"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - // Assertion - assertEquals(obOAuthAuthzRequest.getState(), "abc"); - } - - @Test - public void testInvalidGetStateFromRequestURI() throws OAuthProblemException, OAuthSystemException { - - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST_URI, - new String[]{SAMPLE_REQUEST_URI}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - when(mockRequest.getParameter(IdentityCommonConstants.REQUEST_URI)).thenReturn(SAMPLE_REQUEST_URI); - - // Simulate an exception being thrown when decoding the state - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(mockRequest, OAuth.OAUTH_STATE)) - .thenThrow(OAuthProblemException.error("invalid_request").description("Invalid state").state("abc")); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - assertEquals(obOAuthAuthzRequest.getState(), null); - } - - @Test - public void testValidGetScopesFromRequest_WhenRequestURIIsAbsent() throws OAuthProblemException, - OAuthSystemException { - - Map mockParameterMap = new HashMap<>(); - mockParameterMap.put(IdentityCommonConstants.RESPONSE_TYPE, new String[]{"code id_token"}); - mockParameterMap.put(IdentityCommonConstants.SCOPE, new String[]{"openid"}); - mockParameterMap.put(IdentityCommonConstants.REQUEST, - new String[]{Base64.getEncoder().encodeToString( - "{\"scope\": \"openid\", \"redirect_uri\": \"http://example.com\"}".getBytes( - StandardCharsets.UTF_8))}); - mockParameterMap.put(IdentityCommonConstants.REDIRECT_URI, new String[]{"http://example.com"}); - - when(mockRequest.getParameterMap()).thenReturn(mockParameterMap); - when(mockRequest.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(mockRequest.getParameter(IdentityCommonConstants.SCOPE)).thenReturn("openid"); - when(mockRequest.getParameter(IdentityCommonConstants.REQUEST)).thenReturn( - Base64.getEncoder().encodeToString( - "{\"scope\": \"openid\", \"redirect_uri\": \"http://example.com\"}".getBytes( - StandardCharsets.UTF_8))); - when(mockRequest.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("http://example.com"); - - obOAuthAuthzRequest = new OBOAuthAuthzRequest(mockRequest); - - assertEquals(obOAuthAuthzRequest.getScopes(), new HashSet<>(Collections.singletonList("openid"))); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/DefaultOBRequestObjectValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/DefaultOBRequestObjectValidatorTest.java deleted file mode 100644 index 477c3cba..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/DefaultOBRequestObjectValidatorTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator; - -import com.nimbusds.jose.JOSEObject; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jwt.PlainJWT; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.validator.OpenBankingValidator; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.OBRequestObject; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.ValidationResponse; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import java.text.ParseException; -import java.util.Collections; - -import static org.mockito.Mockito.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -/** - * Test for Default Open Banking object validator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingValidator.class, IdentityExtensionsDataHolder.class}) -public class DefaultOBRequestObjectValidatorTest extends PowerMockTestCase { - - private static final String CLIENT_ID_1 = "2X0n9WSNmPiq3XTB8dtC0Shs5r8a"; - private static final String CLIENT_ID_2 = "owjqxsPTQ7zJIFeZRib5b03ufxsa"; - private static ConsentCoreServiceImpl consentCoreServiceMock; - - @BeforeClass - public void initTest() { - - consentCoreServiceMock = PowerMockito.mock(ConsentCoreServiceImpl.class); - } - - @BeforeMethod - private void mockStaticClasses() throws ConsentManagementException { - - PowerMockito.mockStatic(IdentityExtensionsDataHolder.class); - IdentityExtensionsDataHolder mock = PowerMockito.mock(IdentityExtensionsDataHolder.class); - PowerMockito.when(IdentityExtensionsDataHolder.getInstance()).thenReturn(mock); - PowerMockito.when(IdentityExtensionsDataHolder.getInstance().getConsentCoreService()) - .thenReturn(consentCoreServiceMock); - } - - @Test - public void testValidateOBConstraintsWithValidRequestObject() throws Exception { - // mock - DetailedConsentResource consentResourceMock = mock(DetailedConsentResource.class); - doReturn(CLIENT_ID_1).when(consentResourceMock).getClientID(); - - doReturn(consentResourceMock).when(consentCoreServiceMock).getDetailedConsent(anyString()); - - OpenBankingValidator openBankingValidatorMock = mock(OpenBankingValidator.class); - doReturn("").when(openBankingValidatorMock).getFirstViolation(Mockito.anyObject()); - - PowerMockito.mockStatic(OpenBankingValidator.class); - PowerMockito.when(OpenBankingValidator.getInstance()).thenReturn(openBankingValidatorMock); - - // act - DefaultOBRequestObjectValidator uut = new DefaultOBRequestObjectValidator(); - - OBRequestObject obRequestObject = getObRequestObject(ReqObjectTestDataProvider.VALID_REQUEST); - ValidationResponse validationResponse = uut.validateOBConstraints(obRequestObject, Collections.emptyMap()); - - // assert - Assert.assertTrue(validationResponse.isValid()); - } - - @Test - public void testValidateOBConstraintsWhenNoClientId() throws Exception { - // mock - DetailedConsentResource consentResourceMock = mock(DetailedConsentResource.class); - doReturn(null).when(consentResourceMock).getClientID(); - - ConsentCoreServiceImpl consentCoreServiceMock = mock(ConsentCoreServiceImpl.class); - doReturn(consentResourceMock).when(consentCoreServiceMock).getDetailedConsent(anyString()); - - OpenBankingValidator openBankingValidatorMock = mock(OpenBankingValidator.class); - doReturn("").when(openBankingValidatorMock).getFirstViolation(Mockito.anyObject()); - - PowerMockito.mockStatic(OpenBankingValidator.class); - PowerMockito.when(OpenBankingValidator.getInstance()).thenReturn(openBankingValidatorMock); - - // act - DefaultOBRequestObjectValidator uut = new DefaultOBRequestObjectValidator(); - - OBRequestObject obRequestObject = getObRequestObject(ReqObjectTestDataProvider.NO_CLIENT_ID_REQUEST); - ValidationResponse validationResponse = uut.validateOBConstraints(obRequestObject, Collections.emptyMap()); - - // assert - Assert.assertFalse(validationResponse.isValid()); - Assert.assertEquals(validationResponse.getViolationMessage(), - "Client id or scope cannot be empty"); - } - - @Test - public void testValidateOBConstraintsWhenOBRequestObjectHasErrors() throws Exception { - // mock - OpenBankingValidator openBankingValidatorMock = mock(OpenBankingValidator.class); - doReturn("dummy-error").when(openBankingValidatorMock).getFirstViolation(Mockito.anyObject()); - - PowerMockito.mockStatic(OpenBankingValidator.class); - PowerMockito.when(OpenBankingValidator.getInstance()).thenReturn(openBankingValidatorMock); - - // act - DefaultOBRequestObjectValidator uut = new DefaultOBRequestObjectValidator(); - - OBRequestObject obRequestObject = getObRequestObject(ReqObjectTestDataProvider.REQUEST_STRING); - ValidationResponse validationResponse = uut.validateOBConstraints(obRequestObject, Collections.emptyMap()); - - // assert - Assert.assertFalse(validationResponse.isValid()); - Assert.assertEquals(validationResponse.getViolationMessage(), "dummy-error"); - } - - private OBRequestObject getObRequestObject(String request) throws ParseException, RequestObjectException { - - RequestObject requestObject = new RequestObject(); - JOSEObject jwt = JOSEObject.parse(request); - if (jwt.getHeader().getAlgorithm() == null || jwt.getHeader().getAlgorithm().equals(JWSAlgorithm.NONE)) { - requestObject.setPlainJWT(PlainJWT.parse(request)); - } else { - requestObject.setSignedJWT(SignedJWT.parse(request)); - } - return new OBRequestObject<>(requestObject); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/ReqObjectTestDataProvider.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/ReqObjectTestDataProvider.java deleted file mode 100644 index 3ca3c069..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/ReqObjectTestDataProvider.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator; - -import com.nimbusds.jose.JOSEObject; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jwt.PlainJWT; -import com.nimbusds.jwt.SignedJWT; -import org.testng.annotations.DataProvider; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import java.text.ParseException; - -/** - * Request object test data provider. - */ -public class ReqObjectTestDataProvider { - - public static final String VALID_REQUEST = "eyJraWQiOiJEd01LZFdNbWo3UFdpbnZvcWZReVhWenlaNlEiLCJ0eXAiOiJKV1" + - "QiLCJhbGciOiJQUzI1NiJ9.eyJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo5NDQ2L29hdXRoMi90b2tlbiIsIm1heF9hZ2UiOjg2NDAw" + - "LCJjcml0IjpbImI2NCIsImh0dHA6Ly9vcGVuYmFua2luZy5vcmcudWsvaWF0IiwiaHR0cDovL29wZW5iYW5raW5nLm9yZy51ay9pc3M" + - "iLCJodHRwOi8vb3BlbmJhbmtpbmcub3JnLnVrL3RhbiJdLCJzY29wZSI6ImFjY291bnRzIG9wZW5pZCIsImV4cCI6MTk1NDcwODcxMC" + - "wiY2xhaW1zIjp7ImlkX3Rva2VuIjp7ImFjciI6eyJ2YWx1ZXMiOlsidXJuOm9wZW5iYW5raW5nOnBzZDI6Y2EiLCJ1cm46b3BlbmJhb" + - "mtpbmc6cHNkMjpzY2EiXSwiZXNzZW50aWFsIjp0cnVlfSwib3BlbmJhbmtpbmdfaW50ZW50X2lkIjp7InZhbHVlIjoiOTRmODU3M2Mt" + - "NjA4MC00MDI1LThkOWItMDhlM2U5MjAwZGU3IiwiZXNzZW50aWFsIjp0cnVlfX0sInVzZXJpbmZvIjp7Im9wZW5iYW5raW5nX2ludGV" + - "udF9pZCI6eyJ2YWx1ZSI6Ijk0Zjg1NzNjLTYwODAtNDAyNS04ZDliLTA4ZTNlOTIwMGRlNyIsImVzc2VudGlhbCI6dHJ1ZX19fSwiaX" + - "NzIjoiMlgwbjlXU05tUGlxM1hUQjhkdEMwU2hzNXI4YSIsInJlc3BvbnNlX3R5cGUiOiJjb2RlIGlkX3Rva2VuIiwicmVkaXJlY3Rfd" + - "XJpIjoiaHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS9yZWRpcmVjdHMvcmVkaXJlY3QxIiwic3RhdGUiOiIwcE4wTkJUSGN2Iiwibm9uY2Ui" + - "OiJqQlhoT21PS0NCIiwiY2xpZW50X2lkIjoiMlgwbjlXU05tUGlxM1hUQjhkdEMwU2hzNXI4YSJ9.BjQIMnlqevJgj1zL25hmfKA9Ab" + - "7qm2GvrkZAkxbTMNOxkxtKxQSt9QkLfycITEeM9YdGV5rh2FMdXxyex-WtO_H0G9zlKtsDyrsUw3_HWaBDd-61Hz6n65Few_f6bwtIg" + - "HtW8oDeKpylUu01OsYtB_s4nnDw42ZCKv7zGzkTDkyoxoM2_b_AUqh-F3PNY9Arru5m1-FGDYi_zl4iQ3d3um_NYnhPhmC2wz2R9yms" + - "flXBn9bd-d6nPKl_ftGnqmiBua7oKMd-3CMCFW9Uxig82PHbwHcuy1hYqa_7JoE58Zkr6baGur3YtgJ2381_8t5v19DJvjqhaodabfe" + - "uNWR3GA"; - - public static final String SCOPES_INVALID_REQ = "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkR3TUtkV01tajdQ" + - "V2ludm9xZlF5WFZ6eVo2USJ9.eyJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo4MjQzL3Rva2VuIiwicmVzcG9uc2VfdHlwZSI6ImNvZG" + - "UgaWRfdG9rZW4iLCJjbGllbnRfaWQiOiJpVEtPZnVxejQ2WTFIVlkyQkYwWjdKTTE4QXdhIiwicmVkaXJlY3RfdXJpIjoiaHR0cHM6L" + - "y8xMC4xMTAuNS4yMzI6ODAwMC90ZXN0L2EvYXBwMS9jYWxsYmFjayIsInNjb3BlIjoib3BlbmlkIGJhbms6YWNjb3VudHMuYmFzaWM6" + - "cmVhZCBiYW5rOmFjY291bnRzLmRldGFpbDpyZWFkIGJhbms6dHJhbnNhY3Rpb25zOnJlYWQiLCJzdGF0ZSI6ImFmMGlmanNsZGtqIiw" + - "ibm9uY2UiOiJuLTBTNl9XekEyTWoiLCJjbGFpbXMiOnsic2hhcmluZ19kdXJhdGlvbiI6IjcyMDAiLCJpZF90b2tlbiI6eyJhY3IiOn" + - "siZXNzZW50aWFsIjp0cnVlLCJ2YWx1ZXMiOlsidXJuOmNkcy5hdTpjZHI6MyJdfSwib3BlbmJhbmtpbmdfaW50ZW50X2lkIjp7InZhb" + - "HVlIjoiZDMwMmI4ODgtNzM3Zi00YzQ5LTk4ZmUtNmVkZGU4OTk2ZDZlIiwiZXNzZW50aWFsIjp0cnVlfX0sInVzZXJpbmZvIjp7Imdp" + - "dmVuX25hbWUiOm51bGwsImZhbWlseV9uYW1lIjpudWxsfX19.dmkbejbZLg22Pe81rgt9-TS_7ynT4f1HGpUNugryL7K0-xWSwroqQL" + - "mqLyx442nahZP1nd_1r5LScfer5-lslKid7WTh_gV-v9GvBe6U5xDIKxxgHXBepz7nAUZnOkmyZF9As6JrKxfVa36F-iKN-ZUyIfv0F" + - "bVs5rejAWXqNQzYOlkSwMlOZWDjeCpozKwMYR4FyyecJ-l6gRF11hbRTxo-Uj8U40x3hHH7R7vDVLT6eK5VTwbmFYROXHy4iBQJNIcL" + - "sOBF9lJnSvw8_rJEUteFBqtrlDpWVdQ8fZcHj_9mYMSCZlTKFMvh22ILXJ13EoxrhqPpuFxZMMx7oEPNjA"; - - public static final String REQUEST_STRING = "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkR3TUtkV01tajdQV2ludm9x" + - "ZlF5WFZ6eVo2USJ9.eyJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo4MjQzL3Rva2VuIiwicmVzcG9uc2VfdHlwZSI6ImNvZGUgaWR" + - "fdG9rZW4iLCJjbGllbnRfaWQiOiJpVEtPZnVxejQ2WTFIVlkyQkYwWjdKTTE4QXdhIiwicmVkaXJlY3RfdXJpIjoiaHR0cHM6Ly8" + - "xMC4xMTAuNS4yMzI6ODAwMC90ZXN0L2EvYXBwMS9jYWxsYmFjayIsInNjb3BlIjoib3BlbmlkIGJhbms6YWNjb3VudHMuYmFzaWM6" + - "cmVhZCBiYW5rOmFjY291bnRzLmRldGFpbDpyZWFkIGJhbms6dHJhbnNhY3Rpb25zOnJlYWQiLCJzdGF0ZSI6ImFmMGlmanNsZGtqIi" + - "wibm9uY2UiOiJuLTBTNl9XekEyTWoiLCJjbGFpbXMiOnsic2hhcmluZ19kdXJhdGlvbiI6IjcyMDAiLCJpZF90b2tlbiI6eyJhY3Ii" + - "OnsiZXNzZW50aWFsIjp0cnVlLCJ2YWx1ZXMiOlsidXJuOmNkcy5hdTpjZHI6MyJdfX0sInVzZXJpbmZvIjp7ImdpdmVuX25hbWUiOm" + - "51bGwsImZhbWlseV9uYW1lIjpudWxsfX19.cnKvzjgiDWJ2JeRGL8ncTKB_pCxEynNHn6kzHSPBBXYRJ5e-WvPocTkvaDnwu1qSr" + - "5lsJnFCNgYuNickzoIaTl9wUvl0rnK15iGVe0rSOCWIJ53eVphaV9uYtRfVHTN4HL4ecgdsREHhu6MyjYcqdgAeuv4g0robZGf" + - "DDVCLr2Xb77f8yAr42xc6fBccAFnvZX33zVOHtFaY3S3j9RbQqRZjUxLycIgdVXGypRc2ESVKqJ9WgGxKG6fCUt2rDgqsobVj" + - "8ekRAMyP2fGmYLoRAyycJ8JwU9uoRhGL6nqM6_uOYNG5a6xOsSs8i1Yvn4s7G6FUKQ_bmm4Gx2aJptzVA"; - - public static final String NO_CLIENT_ID_REQUEST = "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkR3TUtkV01tajdQV" + - "2ludm9xZlF5WFZ6eVo2USJ9.eyJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo4MjQzL3Rva2VuIiwicmVzcG9uc2VfdHlwZSI6ImNvZGU" + - "gaWRfdG9rZW4iLCJjbGllbnRfaWQiOiIiLCJyZWRpcmVjdF91cmkiOiJodHRwczovLzEwLjExMC41LjIzMjo4MDAwL3Rlc3QvYS9hcH" + - "AxL2NhbGxiYWNrIiwic2NvcGUiOiJvcGVuaWQgYmFuazphY2NvdW50cy5iYXNpYzpyZWFkIGJhbms6YWNjb3VudHMuZGV0YWlsOnJlY" + - "WQgYmFuazp0cmFuc2FjdGlvbnM6cmVhZCIsInN0YXRlIjoiYWYwaWZqc2xka2oiLCJub25jZSI6Im4tMFM2X1d6QTJNaiIsImNsYWlt" + - "cyI6eyJzaGFyaW5nX2R1cmF0aW9uIjoiNzIwMCIsImlkX3Rva2VuIjp7ImFjciI6eyJlc3NlbnRpYWwiOnRydWUsInZhbHVlcyI6WyJ" + - "1cm46Y2RzLmF1OmNkcjozIl19fSwidXNlcmluZm8iOnsiZ2l2ZW5fbmFtZSI6bnVsbCwiZmFtaWx5X25hbWUiOm51bGx9fX0.BE444R" + - "orL9NH6THQkpr6HzylwqoxGod_OD8aIWLUgOJnS9FFQAQh6RAE-k4cXbriPS40EKC4pNIkA0CuDr3zmaZQsTrcn09W_gL9aWxIQ50cI" + - "2RPkqXzl3W5EEtA-LBOpiqyToVvZfvfsVqZqWF8nNQW85_rToR6yiB-LWWMvlshkF0XDP6qRiFuQhsRDAa6Ro1r3hdnHBBMeoBSGRTe" + - "0LE6jCVq_P6YrJvIbpZnMHL1wsgkJQzXoeu8HLN7kgwaYuUQesWIAWrFR26Ca7kcmRCmVqtj4Z2arhF2QQWtKUurrDYKcSxrQwZHRsQ" + - "Zh76z6dULjhUfz7JQ5JIvtqooAA"; - - - @DataProvider(name = "dp-checkValidRequestObject") - public Object[][] dpCheckValidRequestObject() throws ParseException, RequestObjectException { - - RequestObject requestObject = new RequestObject(); - JOSEObject jwt = JOSEObject.parse(REQUEST_STRING); - if (jwt.getHeader().getAlgorithm() == null || jwt.getHeader().getAlgorithm().equals(JWSAlgorithm.NONE)) { - requestObject.setPlainJWT(PlainJWT.parse(REQUEST_STRING)); - } else { - requestObject.setSignedJWT(SignedJWT.parse(REQUEST_STRING)); - } - - return new Object[][]{ - {requestObject, new OAuth2Parameters()}, - {requestObject, null}, - }; - } - - @DataProvider(name = "dp-checkIncorrectRequestObject") - public Object[][] dpCheckIncorrectRequestObject() throws ParseException, RequestObjectException { - - RequestObject requestObject = new RequestObject(); - JOSEObject jwt = JOSEObject.parse(REQUEST_STRING); - if (jwt.getHeader().getAlgorithm() == null || jwt.getHeader().getAlgorithm().equals(JWSAlgorithm.NONE)) { - requestObject.setPlainJWT(PlainJWT.parse(REQUEST_STRING)); - } else { - requestObject.setSignedJWT(SignedJWT.parse(REQUEST_STRING)); - } - - return new Object[][]{ - {new RequestObject(), new OAuth2Parameters()}, - }; - } - - @DataProvider(name = "dp-checkInValidRequestObject") - public Object[][] dpCheckInValidRequestObject() { - - return new Object[][]{ - {null, new OAuth2Parameters()}, - {null, null}, - }; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/RequestObjectValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/RequestObjectValidatorTest.java deleted file mode 100644 index 8e908510..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/request/validator/RequestObjectValidatorTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator; - -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.OBRequestObject; -import com.wso2.openbanking.accelerator.identity.auth.extensions.request.validator.models.ValidationResponse; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; - -/** - * Test for request object validator. - */ -public class RequestObjectValidatorTest { - - @Test(dataProvider = "dp-checkValidRequestObject", dataProviderClass = ReqObjectTestDataProvider.class) - public void checkValidRequestObject(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws Exception { - - // Mock - OBRequestObjectValidator obRequestObjectValidator = mock(OBRequestObjectValidator.class); - when(obRequestObjectValidator.validateOBConstraints(anyObject(), anyMap())) - .thenReturn(new ValidationResponse(true)); - - OBRequestObjectValidationExtension uut = spy(new OBRequestObjectValidationExtension()); - doReturn(true).when(uut).isRegulatory(anyObject()); - doReturn(true).when(uut).validateIAMConstraints(anyObject(), anyObject()); - doReturn("accounts payments").when(uut).getAllowedScopes(anyObject()); - - // Assign - OBRequestObjectValidationExtension.obDefaultRequestObjectValidator = obRequestObjectValidator; - - // Act - boolean result = uut.validateRequestObject(requestObject, oAuth2Parameters); - - // Assert - assertTrue("Valid request object should pass", result); - } - - - @Test(dataProvider = "dp-checkIncorrectRequestObject", dataProviderClass = ReqObjectTestDataProvider.class, - expectedExceptions = org.wso2.carbon.identity.oauth2.RequestObjectException.class) - public void checkIncorrectRequestObject(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws Exception { - - // Mock - // OBRequestObjectValidator obRequestObjectValidator = mock(OBRequestObjectValidator.class); - //when(obRequestObjectValidator.validateOBConstraints(anyObject())).thenReturn(new ValidationResponse(true)); - - OBRequestObjectValidationExtension uut = spy(new OBRequestObjectValidationExtension()); - doReturn(true).when(uut).validateIAMConstraints(anyObject(), anyObject()); - - // Assign - OBRequestObjectValidationExtension.obDefaultRequestObjectValidator = new OBRequestObjectValidator(); - - // Act - boolean result = uut.validateRequestObject(requestObject, oAuth2Parameters); - - // Assert - assertTrue("InValid request object should throw exception", result); - } - - - @Test(dataProvider = "dp-checkInValidRequestObject", dataProviderClass = ReqObjectTestDataProvider.class, - expectedExceptions = org.wso2.carbon.identity.oauth2.RequestObjectException.class) - public void checkInValidRequestObject(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws Exception { - - // Mock - OBRequestObjectValidator obRequestObjectValidator = mock(OBRequestObjectValidator.class); - when(obRequestObjectValidator.validateOBConstraints(anyObject(), anyMap())) - .thenReturn(new ValidationResponse(true)); - - OBRequestObjectValidationExtension uut = spy(new OBRequestObjectValidationExtension()); - doReturn(true).when(uut).isRegulatory(anyObject()); - doReturn(true).when(uut).validateIAMConstraints(anyObject(), anyObject()); - doReturn("accounts payments").when(uut).getAllowedScopes(anyObject()); - - // Assign - OBRequestObjectValidationExtension.obDefaultRequestObjectValidator = obRequestObjectValidator; - - // Act - boolean result = uut.validateRequestObject(requestObject, oAuth2Parameters); - - // Assert - assertTrue("InValid request object should throw exception", result); - } - - @Test(dataProvider = "dp-checkValidRequestObject", dataProviderClass = ReqObjectTestDataProvider.class) - public void checkChildClassCreation(RequestObject requestObject, - OAuth2Parameters oAuth2Parameters) throws RequestObjectException { - - class UKRequestObject extends OBRequestObject { - public UKRequestObject(OBRequestObject childObject) { - super(childObject); - } - } - - OBRequestObject obRequestObject = new OBRequestObject(requestObject); - UKRequestObject ukRequestObject = new UKRequestObject(obRequestObject); - - // Assert - assertEquals("Inheritance should be preserved in toolkit child classes", - 8, ukRequestObject.getClaimsSet().getClaims().size()); - - // Assert - assertEquals(3, ukRequestObject.getRequestedClaims().size()); - - // Assert - assertEquals("code id_token", ukRequestObject.getClaim("response_type")); - - // Assert - assertEquals("code id_token", ukRequestObject.getClaimValue("response_type")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/ResponseTypeHandlerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/ResponseTypeHandlerTest.java deleted file mode 100644 index a6df365f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/handler/ResponseTypeHandlerTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.auth.extensions.response.handler.impl.OBDefaultResponseTypeHandlerImpl; -import org.mockito.ArgumentCaptor; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.testng.Assert.fail; -import static org.testng.AssertJUnit.assertEquals; - -/** - * test for response type handler. - */ -public class ResponseTypeHandlerTest { - - @Test - public void checkValidHybridResponseTypeHandling() throws IdentityOAuth2Exception, OpenBankingException { - - // Mock - OBResponseTypeHandler obResponseTypeHandler = mock(OBDefaultResponseTypeHandlerImpl.class); - when(obResponseTypeHandler.updateRefreshTokenValidityPeriod(anyObject())).thenReturn(999L); - when(obResponseTypeHandler.updateApprovedScopes(anyObject())).thenReturn(new String[]{"Asd", "addd"}); - - OBHybridResponseTypeHandlerExtension uut = spy(new OBHybridResponseTypeHandlerExtension()); - doReturn(null).when(uut).issueCode(anyObject()); - doReturn(true).when(uut).isRegulatory(anyObject()); - - ArgumentCaptor argument = - ArgumentCaptor.forClass(OAuthAuthzReqMessageContext.class); - - // Assign - OBHybridResponseTypeHandlerExtension.obResponseTypeHandler = obResponseTypeHandler; - - // Act - uut.issue(new OAuthAuthzReqMessageContext(new OAuth2AuthorizeReqDTO())); - - // Assert - verify(uut).issueCode(argument.capture()); - assertEquals(999L, argument.getValue().getRefreshTokenvalidityPeriod()); - assertEquals(2, argument.getValue().getApprovedScope().length); - - } - - @Test - public void checkValidCodeResponseTypeHandling() throws IdentityOAuth2Exception, OpenBankingException { - - // Mock - OBResponseTypeHandler obResponseTypeHandler = mock(OBDefaultResponseTypeHandlerImpl.class); - when(obResponseTypeHandler.updateRefreshTokenValidityPeriod(anyObject())).thenReturn(109L); - when(obResponseTypeHandler.updateApprovedScopes(anyObject())).thenReturn(new String[]{"Asd", "addd", "rr"}); - - OBCodeResponseTypeHandlerExtension uut = spy(new OBCodeResponseTypeHandlerExtension()); - doReturn(null).when(uut).issueCode(anyObject()); - doReturn(true).when(uut).isRegulatory(anyObject()); - - ArgumentCaptor argument = - ArgumentCaptor.forClass(OAuthAuthzReqMessageContext.class); - - // Assign - OBCodeResponseTypeHandlerExtension.obResponseTypeHandler = obResponseTypeHandler; - - // Act - uut.issue(new OAuthAuthzReqMessageContext(new OAuth2AuthorizeReqDTO())); - - // Assert - verify(uut).issueCode(argument.capture()); - assertEquals(109L, argument.getValue().getRefreshTokenvalidityPeriod()); - assertEquals(3, argument.getValue().getApprovedScope().length); - - } - - @Test - public void checkHandlerLogic() { - - OAuthAuthzReqMessageContext mock = mock(OAuthAuthzReqMessageContext.class); - when(mock.getRefreshTokenvalidityPeriod()).thenReturn(6666L); - when(mock.getApprovedScope()).thenReturn(new String[]{"1"}); - - OBResponseTypeHandler uut = new OBDefaultResponseTypeHandlerImpl(); - - assertEquals(6666L, uut.updateRefreshTokenValidityPeriod(mock)); - - } - - @Test - public void checkExceptionHandling_WhenIsRegulatoryThrowsOpenBankingException() throws Exception { - - OAuthAuthzReqMessageContext mockAuthzReqMsgCtx = mock(OAuthAuthzReqMessageContext.class); - OAuth2AuthorizeReqDTO mockAuthorizeReqDTO = mock(OAuth2AuthorizeReqDTO.class); - when(mockAuthzReqMsgCtx.getAuthorizationReqDTO()).thenReturn(mockAuthorizeReqDTO); - when(mockAuthorizeReqDTO.getConsumerKey()).thenReturn("dummyClientId"); - OBCodeResponseTypeHandlerExtension uut = spy(new OBCodeResponseTypeHandlerExtension()); - doThrow(new OpenBankingException("Simulated isRegulatory exception")) - .when(uut).isRegulatory("dummyClientId"); - - try { - uut.issue(mockAuthzReqMsgCtx); - fail("Expected IdentityOAuth2Exception was not thrown."); - } catch (IdentityOAuth2Exception e) { - // Verify that the IdentityOAuth2Exception is thrown with the expected message - assertEquals("Error while reading regulatory property", e.getMessage()); - } - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBCodeResponseTypeValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBCodeResponseTypeValidatorTest.java deleted file mode 100644 index 2c8e2804..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBCodeResponseTypeValidatorTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.validator; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.Test; - - -import javax.servlet.http.HttpServletRequest; - -import static org.mockito.Mockito.spy; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * OBCodeResponseTypeValidator Test class. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class}) -public class OBCodeResponseTypeValidatorTest extends PowerMockTestCase { - - @Test - public void checkValidCodeResponseTypeValidation() throws OAuthProblemException, OpenBankingException { - - // Mock - HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class); - when(httpServletRequestMock.getParameter("response_type")).thenReturn("code"); - when(httpServletRequestMock.getParameter("client_id")).thenReturn("1234567654321"); - - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - - OBCodeResponseTypeValidator uut = spy(new OBCodeResponseTypeValidator()); - - // Act - uut.validateRequiredParameters(httpServletRequestMock); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBHybridResponseTypeValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBHybridResponseTypeValidatorTest.java deleted file mode 100644 index cf9c667f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/auth/extensions/response/validator/OBHybridResponseTypeValidatorTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.auth.extensions.response.validator; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.oltu.oauth2.common.OAuth; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.Test; - -import javax.servlet.http.HttpServletRequest; - -import static org.mockito.Mockito.spy; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * OBHybridResponseTypeValidator Test class. - */ -@PrepareForTest({IdentityCommonUtil.class}) -@PowerMockIgnore("jdk.internal.reflect.*") -public class OBHybridResponseTypeValidatorTest extends PowerMockTestCase { - - @Test - public void checkValidHybridResponseTypeValidationWithRequestURI() throws OAuthProblemException { - - // Mock - HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class); - when(httpServletRequestMock.getParameter(IdentityCommonConstants.REQUEST_URI)).thenReturn("test"); - when(httpServletRequestMock.getParameter(IdentityCommonConstants.CLIENT_ID)).thenReturn("1234567"); - - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.decodeRequestObjectAndGetKey(httpServletRequestMock, OAuth.OAUTH_SCOPE)) - .thenReturn("openid"); - - OBHybridResponseTypeValidator uut = spy(new OBHybridResponseTypeValidator()); - - // Act - uut.validateRequiredParameters(httpServletRequestMock); - } - - @Test - public void checkValidHybridResponseTypeValidationWithoutRequestURI() throws OAuthProblemException { - - // Mock - HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class); - when(httpServletRequestMock.getParameter(OAuth.OAUTH_SCOPE)).thenReturn("openid"); - when(httpServletRequestMock.getParameter(IdentityCommonConstants.CLIENT_ID)).thenReturn("1234567"); - when(httpServletRequestMock.getParameter(IdentityCommonConstants.RESPONSE_TYPE)).thenReturn("code id_token"); - when(httpServletRequestMock.getParameter(IdentityCommonConstants.REDIRECT_URI)).thenReturn("abc.com"); - - OBHybridResponseTypeValidator uut = spy(new OBHybridResponseTypeValidator()); - - // Act - uut.validateRequiredParameters(httpServletRequestMock); - } - - @Test - public void testValidateMethod() throws OAuthProblemException { - - // Mock - HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class); - when(httpServletRequestMock.getMethod()).thenReturn("POST"); - - OBHybridResponseTypeValidator uut = spy(new OBHybridResponseTypeValidator()); - - // Act - uut.validateMethod(httpServletRequestMock); - } - - @Test(expectedExceptions = OAuthProblemException.class) - public void testInvalidMethodScenario() throws OAuthProblemException { - - // Mock - HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class); - when(httpServletRequestMock.getMethod()).thenReturn("PUT"); - - OBHybridResponseTypeValidator uut = spy(new OBHybridResponseTypeValidator()); - - // Act - uut.validateMethod(httpServletRequestMock); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/authenticator/OBIdentifierAuthenticatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/authenticator/OBIdentifierAuthenticatorTest.java deleted file mode 100644 index 22e30e43..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/authenticator/OBIdentifierAuthenticatorTest.java +++ /dev/null @@ -1,1226 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.authenticator; - -import com.wso2.openbanking.accelerator.common.exception.OBThrottlerException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.authenticator.util.OBIdentifierAuthenticatorTestData; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.throttler.service.OBThrottleService; -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus; -import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade; -import org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder; -import org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig; -import org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig; -import org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException; -import org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.basicauth.BasicAuthenticator; -import org.wso2.carbon.identity.application.authenticator.basicauth.BasicAuthenticatorConstants; -import org.wso2.carbon.identity.core.model.IdentityErrorMsgContext; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.core.UserStoreException; -import org.wso2.carbon.user.core.UserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.doAnswer; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -/** - * Unit test cases for the OB Identifier Authenticator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({FileBasedConfigurationBuilder.class, IdentityUtil.class, IdentityExtensionsDataHolder.class, - IdentityTenantUtil.class, MultitenantUtils.class, - AuthenticatedUser.class, HTTPClientUtils.class}) -public class OBIdentifierAuthenticatorTest { - - private HttpServletRequest mockRequest; - private HttpServletResponse mockResponse; - private AuthenticationContext mockAuthnCtxt; - private Map dummyIdpData = new HashMap<>(); - private ArrayList dummyAuthenticatorList = new ArrayList<>(); - private AuthenticatorConfig mockAuthConfig; - private BasicAuthenticator mockBasiAuthenticator; - private AuthenticatedIdPData mockAuthIdpData; - private Map dummyAuthParams = new HashMap<>(); - private FileBasedConfigurationBuilder mockFileBasedConfigurationBuilder; - private IdentityErrorMsgContext mockIdentityErrorMsgContext; - private IdentityExtensionsDataHolder identityExtensionsDataHolder; - private OBThrottleService obThrottleService; - private SequenceConfig mockSequenceConfig; - private ApplicationConfig mockApplicationConfig; - private RealmService mockRealmService; - private UserRealm mockUserRealm; - private org.wso2.carbon.user.core.UserRealm mockUserCoreRealm; - private UserStoreManager mockUserStoreManager; - private AuthenticatedUser authenticatedUser; - private Boolean isUserTenantDomainMismatch = true; - private String redirect; - private String dummyUserName = "dummyUserName"; - private String dummyQueryParam = "dummyQueryParams"; - private String dummyLoginPage = "dummyLoginPageurl"; - private String dummyString = "dummyString"; - private int dummyTenantId = -1234; - private String dummyVal = "dummyVal"; - private String dummySessionDataKey = "dummySessionDataKey"; - private OBIdentifierAuthenticator obIdentifierAuthenticator; - - @BeforeTest - public void setup() { - - obIdentifierAuthenticator = new OBIdentifierAuthenticator(); - mockBasiAuthenticator = new BasicAuthenticator(); - obThrottleService = mock(OBThrottleService.class); - identityExtensionsDataHolder = mock(IdentityExtensionsDataHolder.class); - } - - @DataProvider(name = "UsernameAndPasswordProvider") - public Object[][] getWrongUsernameAndPassword() { - - return new String[][]{ - {"admin@wso2.com", null, "true"}, - {null, "continue", "true"}, - {null, null, "false"}, - {"admin@wso2.com", "reset", "true"}, - {"", "", "true"} - }; - } - - @Test(dataProvider = "UsernameAndPasswordProvider") - public void canHandleTestCase(String userName, String identifierConsent, String expected) { - - mockRequest = mock(HttpServletRequest.class); - when(mockRequest.getParameter(BasicAuthenticatorConstants.USER_NAME)).thenReturn(userName); - when(mockRequest.getParameter("identifier_consent")).thenReturn(identifierConsent); - assertEquals(Boolean.valueOf(expected).booleanValue(), obIdentifierAuthenticator.canHandle(mockRequest), - "Invalid can handle response for the request."); - } - - @Test - public void processSuccessTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - when(mockAuthnCtxt.isLogoutRequest()).thenReturn(true); - assertEquals(obIdentifierAuthenticator.process(mockRequest, mockResponse, mockAuthnCtxt), - AuthenticatorFlowStatus.SUCCESS_COMPLETED); - } - - @Test - public void processSeamlessPromptFalseTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - dummyIdpData.put("LOCAL", OBIdentifierAuthenticatorTestData.getSampleAuthenticatedIdPData()); - dummyAuthenticatorList.add(new AuthenticatorConfig()); - dummyAuthParams.put("promptConfirmationWindow", "false"); - - when(mockAuthnCtxt.isLogoutRequest()).thenReturn(false); - when(mockAuthnCtxt.getPreviousAuthenticatedIdPs()).thenReturn(dummyIdpData); - when(mockAuthnCtxt.getAuthenticatorParams(obIdentifierAuthenticator.getName())).thenReturn(dummyAuthParams); - assertEquals(obIdentifierAuthenticator.process(mockRequest, mockResponse, mockAuthnCtxt), - AuthenticatorFlowStatus.SUCCESS_COMPLETED); - } - - @Test - public void processSeamlessPromptTrueWithConsentContinueTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - dummyIdpData.put("LOCAL", OBIdentifierAuthenticatorTestData.getSampleAuthenticatedIdPData()); - dummyAuthenticatorList.add(new AuthenticatorConfig()); - dummyAuthParams.put("promptConfirmationWindow", "true"); - - when(mockAuthnCtxt.isLogoutRequest()).thenReturn(false); - when(mockAuthnCtxt.getPreviousAuthenticatedIdPs()).thenReturn(dummyIdpData); - when(mockAuthnCtxt.getAuthenticatorParams(obIdentifierAuthenticator.getName())).thenReturn(dummyAuthParams); - when(mockRequest.getParameter(Mockito.anyString())).thenReturn("continue"); - assertEquals(obIdentifierAuthenticator.process(mockRequest, mockResponse, mockAuthnCtxt), - AuthenticatorFlowStatus.SUCCESS_COMPLETED); - } - - @Test - public void processSeamlessPromptTrueWithConsentNullTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - dummyIdpData.put("LOCAL", OBIdentifierAuthenticatorTestData.getSampleAuthenticatedIdPData()); - dummyAuthenticatorList.add(new AuthenticatorConfig()); - dummyAuthParams.put("promptConfirmationWindow", "true"); - - when(mockAuthnCtxt.isLogoutRequest()).thenReturn(false); - when(mockAuthnCtxt.getPreviousAuthenticatedIdPs()).thenReturn(dummyIdpData); - when(mockAuthnCtxt.getAuthenticatorParams(obIdentifierAuthenticator.getName())).thenReturn(dummyAuthParams); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(FileBasedConfigurationBuilder.getInstance().getAuthenticatorBean(anyString())).thenReturn(null); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - assertEquals(obIdentifierAuthenticator.process(mockRequest, mockResponse, mockAuthnCtxt), - AuthenticatorFlowStatus.INCOMPLETE); - } - - @Test(expectedExceptions = AuthenticationFailedException.class) - public void processSeamlessPromptTrueWithExceptionTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - dummyIdpData.put("LOCAL", OBIdentifierAuthenticatorTestData.getSampleAuthenticatedIdPData()); - dummyAuthenticatorList.add(new AuthenticatorConfig()); - dummyAuthParams.put("promptConfirmationWindow", "true"); - - when(mockAuthnCtxt.isLogoutRequest()).thenReturn(false); - when(mockAuthnCtxt.getPreviousAuthenticatedIdPs()).thenReturn(dummyIdpData); - when(mockAuthnCtxt.getAuthenticatorParams(obIdentifierAuthenticator.getName())).thenReturn(dummyAuthParams); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(FileBasedConfigurationBuilder.getInstance().getAuthenticatorBean(anyString())).thenReturn(null); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - Mockito.doThrow(IOException.class).when(mockResponse).sendRedirect(anyString()); - - obIdentifierAuthenticator.process(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestGeneralTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("dummyErrorCode"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestIsThrottledFalseTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - when(mockAuthnCtxt.getProperty("InvalidEmailUsername")).thenReturn(true); - - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(false); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("dummyErrorCode"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestAuthFailureFalseTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "false"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("dummyErrorCode"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestNullErrorContextTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "false"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test(expectedExceptions = AuthenticationFailedException.class) - public void initiateAuthenticationRequestThrottlerExceptionTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "false"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doThrow(OBThrottlerException.class).when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestAccountNotConfirmedErrorCodeTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "false"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - Map mockedThreadLocalMap = new HashMap<>(); - mockedThreadLocalMap.put("user-domain-recaptcha", dummyVal); - IdentityUtil.threadLocalProperties.set(mockedThreadLocalMap); - when(IdentityUtil.addDomainToName(Mockito.anyString(), Mockito.anyString())).thenReturn(dummyUserName); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("17005"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestInvalidClientErrorCodeTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("17002"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestLockedUserWithNullReasonTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("17003"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestLockedUserWithReasonTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("17003:reason"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestLockedUserWithRetryAttemptsAndNullReasonTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("17003"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - when(mockIdentityErrorMsgContext.getMaximumLoginAttempts()).thenReturn(4); - when(mockIdentityErrorMsgContext.getFailedLoginAttempts()).thenReturn(2); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void initiateAuthenticationRequestLockedUserWithRetryAttemptsAndReasonTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("throttleLimit", "3"); - paramMap.put("throttleTimePeriod", "180"); - paramMap.put("showAuthFailureReason", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - isUserTenantDomainMismatch = (Boolean) invocation.getArguments()[1]; - return null; - } - }).when(mockAuthnCtxt).setProperty(anyString(), anyBoolean()); - - when(ConfigurationFacade.getInstance().getAuthenticationEndpointURL()).thenReturn(dummyLoginPage); - when(mockAuthnCtxt.getContextIdIncludedQueryParams()).thenReturn(dummyQueryParam); - when(mockAuthnCtxt.isRetrying()).thenReturn(true); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - mockIdentityErrorMsgContext = mock(IdentityErrorMsgContext.class); - when(mockIdentityErrorMsgContext.getErrorCode()).thenReturn("17003:reason"); - when(IdentityUtil.getIdentityErrorMsg()).thenReturn(mockIdentityErrorMsgContext); - - when(mockIdentityErrorMsgContext.getMaximumLoginAttempts()).thenReturn(4); - when(mockIdentityErrorMsgContext.getFailedLoginAttempts()).thenReturn(2); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.doNothing().when(obThrottleService) - .updateThrottleData(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - redirect = (String) invocation.getArguments()[0]; - return null; - } - }).when(mockResponse).sendRedirect(anyString()); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - obIdentifierAuthenticator.initiateAuthenticationRequest(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void processAuthenticationResponseGeneralTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - mockSequenceConfig = mock(SequenceConfig.class); - mockApplicationConfig = mock(ApplicationConfig.class); - mockRealmService = mock(RealmService.class); - mockUserRealm = mock(UserRealm.class); - mockUserStoreManager = mock(UserStoreManager.class); - authenticatedUser = mock(AuthenticatedUser.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("ValidateUsername", "true"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - - when(obThrottleService.isThrottled(Mockito.anyString(), Mockito.anyString())).thenReturn(false); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - when(mockAuthnCtxt.getSequenceConfig()).thenReturn(mockSequenceConfig); - when(mockSequenceConfig.getApplicationConfig()).thenReturn(mockApplicationConfig); - when(mockApplicationConfig.isSaaSApp()).thenReturn(true); - - mockStatic(IdentityTenantUtil.class); - when(IdentityTenantUtil.getTenantId(Mockito.anyString())).thenReturn(dummyTenantId); - - when(identityExtensionsDataHolder.getRealmService()).thenReturn(mockRealmService); - when(mockRealmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(mockUserRealm); - when(mockUserRealm.getUserStoreManager()).thenReturn(mockUserStoreManager); - - mockStatic(MultitenantUtils.class); - when(MultitenantUtils.getTenantAwareUsername(Mockito.anyString())).thenReturn(dummyUserName); - when(mockUserStoreManager.isExistingUser(Mockito.anyString())).thenReturn(true); - - mockStatic(AuthenticatedUser.class); - when(AuthenticatedUser - .createLocalAuthenticatedUserFromSubjectIdentifier(Mockito.anyString())).thenReturn(authenticatedUser); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - authenticatedUser = (AuthenticatedUser) invocation.getArguments()[0]; - return null; - } - }).when(mockAuthnCtxt).setSubject(authenticatedUser); - - obIdentifierAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test(expectedExceptions = InvalidCredentialsException.class, priority = 1) - public void processAuthenticationResponseNotSaasAppAndInvalidTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - mockSequenceConfig = mock(SequenceConfig.class); - mockApplicationConfig = mock(ApplicationConfig.class); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.isEmailUsernameEnabled()).thenReturn(true); - - when(mockAuthnCtxt.getSequenceConfig()).thenReturn(mockSequenceConfig); - when(mockSequenceConfig.getApplicationConfig()).thenReturn(mockApplicationConfig); - when(mockApplicationConfig.isSaaSApp()).thenReturn(false); - - mockStatic(MultitenantUtils.class); - when(MultitenantUtils.getTenantDomain(anyString())).thenReturn("carbon.super"); - when(MultitenantUtils.getTenantAwareUsername(Mockito.anyString())).thenReturn(dummyUserName); - - obIdentifierAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, priority = 1) - public void processAuthenticationResponseEmaiEnabledUsernameWithThrottleExceptionTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - mockSequenceConfig = mock(SequenceConfig.class); - mockApplicationConfig = mock(ApplicationConfig.class); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.isEmailUsernameEnabled()).thenReturn(true); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - when(mockRequest.getParameter("username")).thenReturn("admin@wso2.com"); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - - Mockito.doThrow(OBThrottlerException.class) - .when(obThrottleService).isThrottled(Mockito.anyString(), Mockito.anyString()); - - when(mockAuthnCtxt.getSequenceConfig()).thenReturn(mockSequenceConfig); - when(mockSequenceConfig.getApplicationConfig()).thenReturn(mockApplicationConfig); - when(mockApplicationConfig.isSaaSApp()).thenReturn(false); - - mockStatic(MultitenantUtils.class); - when(MultitenantUtils.getTenantDomain(anyString())).thenReturn("carbon.super"); - when(MultitenantUtils.getTenantAwareUsername(Mockito.anyString())).thenReturn("admin@wso2.com"); - - obIdentifierAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test(expectedExceptions = AuthenticationFailedException.class, priority = 1) - public void processAuthenticationResponseNonEmailUserNameWithThrottleExceptionTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - mockResponse = mock(HttpServletResponse.class); - mockAuthnCtxt = mock(AuthenticationContext.class); - mockSequenceConfig = mock(SequenceConfig.class); - mockApplicationConfig = mock(ApplicationConfig.class); - - mockStatic(IdentityUtil.class); - when(IdentityUtil.isEmailUsernameEnabled()).thenReturn(false); - when(IdentityUtil.getClientIpAddress(mockRequest)).thenReturn("127.0.0.1"); - when(mockRequest.getParameter("username")).thenReturn(dummyUserName); - - mockStatic(IdentityExtensionsDataHolder.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getOBThrottleService()).thenReturn(obThrottleService); - - Mockito.doThrow(OBThrottlerException.class) - .when(obThrottleService).isThrottled(Mockito.anyString(), Mockito.anyString()); - - when(mockAuthnCtxt.getSequenceConfig()).thenReturn(mockSequenceConfig); - when(mockSequenceConfig.getApplicationConfig()).thenReturn(mockApplicationConfig); - when(mockApplicationConfig.isSaaSApp()).thenReturn(false); - - mockStatic(MultitenantUtils.class); - when(MultitenantUtils.getTenantDomain(anyString())).thenReturn("carbon.super"); - when(MultitenantUtils.getTenantAwareUsername(Mockito.anyString())).thenReturn(dummyUserName); - - obIdentifierAuthenticator.processAuthenticationResponse(mockRequest, mockResponse, mockAuthnCtxt); - } - - @Test - public void retryAuthenticationEnabledTestCase() throws Exception { - - assertEquals(obIdentifierAuthenticator.retryAuthenticationEnabled(), true); - } - - @Test - public void getContextIdentifierTestCase() throws Exception { - - mockRequest = mock(HttpServletRequest.class); - when(mockRequest.getParameter(Mockito.anyString())).thenReturn("sessionData"); - - assertNotNull(obIdentifierAuthenticator.getContextIdentifier(mockRequest)); - } - - @Test - public void getFriendlyNameTestCase() throws Exception { - - assertEquals(obIdentifierAuthenticator.getFriendlyName(), "ob-identifier-first"); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void getSessionDataExceptionTestCase() throws Exception { - - mockRealmService = mock(RealmService.class); - mockUserCoreRealm = mock(org.wso2.carbon.user.core.UserRealm.class); - mockUserStoreManager = mock(UserStoreManager.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("authRequestURL", "someURL"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - mockStatic(IdentityExtensionsDataHolder.class); - RealmConfiguration mockRealmConfiguration = mock(RealmConfiguration.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getRealmService()).thenReturn(mockRealmService); - when(mockRealmService.getBootstrapRealm()).thenReturn(mockUserCoreRealm); - when(mockUserCoreRealm.getUserStoreManager()).thenReturn(mockUserStoreManager); - when(mockUserStoreManager.getRealmConfiguration()).thenReturn(mockRealmConfiguration); - - when(mockRealmConfiguration.getAdminUserName()).thenReturn("adminUserName"); - when(mockRealmConfiguration.getAdminPassword()).thenReturn("adminPassword"); - - mockStatic(HTTPClientUtils.class); - CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class); - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - InputStream inputStream = mock(InputStream.class); - HttpEntity httpEntity = mock(HttpEntity.class); - BufferedReader bufferedReader = mock(BufferedReader.class); - StatusLine statusLine = mock(StatusLine.class); - final HttpGet[] httpGet = {mock(HttpGet.class)}; - when(HTTPClientUtils.getHttpsClient()).thenReturn(closeableHttpClient); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - - httpGet[0] = (HttpGet) invocation.getArguments()[0]; - return closeableHttpResponse; - } - }).when(closeableHttpClient).execute(Mockito.anyObject()); - - when(closeableHttpResponse.getEntity()).thenReturn(httpEntity); - when(httpEntity.getContent()).thenReturn(inputStream); - when(bufferedReader.readLine()).thenReturn("sessionDataValues"); - when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); - when(statusLine.getStatusCode()).thenReturn(200); - - obIdentifierAuthenticator.getSessionData(dummySessionDataKey); - } - - @Test(expectedExceptions = OpenBankingException.class) - public void getSessionDataUserStoreExceptionTestCase() throws Exception { - - mockRealmService = mock(RealmService.class); - mockUserCoreRealm = mock(org.wso2.carbon.user.core.UserRealm.class); - mockUserStoreManager = mock(UserStoreManager.class); - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - Map paramMap = new HashMap<>(); - paramMap.put("authRequestURL", "someURL"); - - authenticatorConfig.setParameterMap(paramMap); - - mockStatic(FileBasedConfigurationBuilder.class); - mockFileBasedConfigurationBuilder = mock(FileBasedConfigurationBuilder.class); - when(FileBasedConfigurationBuilder.getInstance()).thenReturn(mockFileBasedConfigurationBuilder); - when(mockFileBasedConfigurationBuilder.getAuthenticatorBean(anyString())).thenReturn(authenticatorConfig); - - mockStatic(IdentityExtensionsDataHolder.class); - RealmConfiguration mockRealmConfiguration = mock(RealmConfiguration.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolder); - when(identityExtensionsDataHolder.getRealmService()).thenReturn(mockRealmService); - when(mockRealmService.getBootstrapRealm()).thenThrow(UserStoreException.class); - - obIdentifierAuthenticator.getSessionData(dummySessionDataKey); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/authenticator/util/OBIdentifierAuthenticatorTestData.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/authenticator/util/OBIdentifierAuthenticatorTestData.java deleted file mode 100644 index a0bceec6..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/authenticator/util/OBIdentifierAuthenticatorTestData.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.authenticator.util; - -import org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.basicauth.BasicAuthenticator; - -/** - * Test data for Open Banking identifier authentication. - */ -public class OBIdentifierAuthenticatorTestData { - - public static AuthenticatorConfig getAuthenticatorConfig() { - - AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig(); - - authenticatorConfig.setApplicationAuthenticator(new BasicAuthenticator()); - return authenticatorConfig; - } - - public static AuthenticatedIdPData getSampleAuthenticatedIdPData() { - - AuthenticatedIdPData authenticatedIdPData = new AuthenticatedIdPData(); - - authenticatedIdPData.setUser(new AuthenticatedUser()); - authenticatedIdPData.setIdpName("Sample"); - authenticatedIdPData.addAuthenticator(OBIdentifierAuthenticatorTestData.getAuthenticatorConfig()); - return authenticatedIdPData; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/builders/DefaultOBRequestUriRequestObjectBuilderTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/builders/DefaultOBRequestUriRequestObjectBuilderTest.java deleted file mode 100644 index 4bec2e06..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/builders/DefaultOBRequestUriRequestObjectBuilderTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.builders; - -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util.test.jwt.builder.TestJwtBuilder; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; -import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; -import org.wso2.carbon.identity.oauth2.RequestObjectException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; -import org.wso2.carbon.identity.openidconnect.model.RequestObject; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.security.KeyStore; -import java.security.interfaces.RSAPrivateKey; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test for default Open Banking request, uri request builder. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({SessionDataCacheEntry.class, SessionDataCache.class, OAuth2Util.class, OAuthAppDO.class, - OAuthServerConfiguration.class}) -public class DefaultOBRequestUriRequestObjectBuilderTest extends PowerMockTestCase { - - private DefaultOBRequestUriRequestObjectBuilder defaultOBRequestUriRequestObjectBuilder; - - @Test() - public void buildRequestObjectSuccessScenario() throws Exception { - - String requestUri = "urn:ietf:params:oauth:request_uri:XKnDFSbXJWjuf0AY6gOT1EIuvdP8BQLo"; - String requestObjectString = TestJwtBuilder.getValidSignedJWT(); - OAuth2Parameters oAuth2Parameters = new OAuth2Parameters(); - oAuth2Parameters.setEssentialClaims(requestObjectString + ":" + "3600666666"); - - defaultOBRequestUriRequestObjectBuilder = new DefaultOBRequestUriRequestObjectBuilder(); - - SessionDataCache sessionDataCacheMock = mock(SessionDataCache.class); - SessionDataCacheEntry sessionDataCacheEntry = new SessionDataCacheEntry(); - mockStatic(SessionDataCacheEntry.class); - mockStatic(SessionDataCache.class); - when(SessionDataCache.getInstance()).thenReturn(sessionDataCacheMock); - when(sessionDataCacheMock.getValueFromCache(Mockito.anyObject())).thenReturn(sessionDataCacheEntry); - - sessionDataCacheEntry.setoAuth2Parameters(oAuth2Parameters); - - RequestObject result = defaultOBRequestUriRequestObjectBuilder - .buildRequestObject(requestUri, oAuth2Parameters); - - Assert.assertNotNull(result); - } - - @Test(expectedExceptions = RequestObjectException.class) - public void buildRequestObjectExpiredScenario() throws Exception { - - String requestUri = "urn:ietf:params:oauth:request_uri:XKnDFSbXJWjuf0AY6gOT1EIuvdP8BQLo"; - String requestObjectString = TestJwtBuilder.getValidSignedJWT(); - OAuth2Parameters oAuth2Parameters = new OAuth2Parameters(); - oAuth2Parameters.setEssentialClaims(requestObjectString + ":" + "60"); - - defaultOBRequestUriRequestObjectBuilder = new DefaultOBRequestUriRequestObjectBuilder(); - - SessionDataCache sessionDataCacheMock = mock(SessionDataCache.class); - SessionDataCacheEntry sessionDataCacheEntry = new SessionDataCacheEntry(); - mockStatic(SessionDataCacheEntry.class); - mockStatic(SessionDataCache.class); - when(SessionDataCache.getInstance()).thenReturn(sessionDataCacheMock); - when(sessionDataCacheMock.getValueFromCache(Mockito.anyObject())).thenReturn(sessionDataCacheEntry); - - sessionDataCacheEntry.setoAuth2Parameters(oAuth2Parameters); - - defaultOBRequestUriRequestObjectBuilder.buildRequestObject(requestUri, oAuth2Parameters); - } - - @Test(expectedExceptions = RequestObjectException.class) - public void testDecryptEncryptedReqObjFailure() throws Exception { - - defaultOBRequestUriRequestObjectBuilder = new DefaultOBRequestUriRequestObjectBuilder(); - String requestUri = "urn:ietf:params:oauth:request_uri:XKnDFSbXJWjuf0AY6gOT1EIuvdP8BQLo"; - String requestObjectString = TestJwtBuilder.getValidEncryptedJWT(); - OAuth2Parameters oAuth2Parameters = new OAuth2Parameters(); - oAuth2Parameters.setTenantDomain("dummyTenantDomain"); - oAuth2Parameters.setEssentialClaims(requestObjectString + ":" + "3600666666"); - - SessionDataCache sessionDataCacheMock = mock(SessionDataCache.class); - SessionDataCacheEntry sessionDataCacheEntry = new SessionDataCacheEntry(); - mockStatic(SessionDataCacheEntry.class); - mockStatic(SessionDataCache.class); - when(SessionDataCache.getInstance()).thenReturn(sessionDataCacheMock); - when(sessionDataCacheMock.getValueFromCache(Mockito.anyObject())).thenReturn(sessionDataCacheEntry); - - sessionDataCacheEntry.setoAuth2Parameters(oAuth2Parameters); - - OAuthServerConfiguration oAuthServerConfigurationMock = mock(OAuthServerConfiguration.class); - mockStatic(OAuthServerConfiguration.class); - when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfigurationMock); - - mockStatic(OAuth2Util.class); - when(OAuth2Util.getTenantId(Mockito.anyString())).thenReturn(5); - - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - - InputStream keystoreFile = new FileInputStream(absolutePathForTestResources + - "/wso2carbon.jks"); - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(keystoreFile, "wso2carbon".toCharArray()); - - String alias = "wso2carbon"; - - // Get the private key. Password for the key store is 'wso2carbon'. - RSAPrivateKey privateKey = (RSAPrivateKey) keystore.getKey(alias, "wso2carbon".toCharArray()); - - when(OAuth2Util.getPrivateKey(Mockito.anyString(), Mockito.anyInt())).thenReturn(privateKey); - - defaultOBRequestUriRequestObjectBuilder - .buildRequestObject(requestUri, oAuth2Parameters); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultOIDCClaimsCallbackHandlerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultOIDCClaimsCallbackHandlerTest.java deleted file mode 100644 index 8b0e3466..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/claims/OBDefaultOIDCClaimsCallbackHandlerTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.claims; - -import com.nimbusds.jwt.JWTClaimsSet; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.collections.map.SingletonMap; -import org.apache.commons.lang.StringUtils; -import org.mockito.Mockito; -import org.mockito.Spy; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO; -import org.wso2.carbon.identity.oauth2.model.HttpRequestHeader; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; - -import java.io.File; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT; - -/** - * Class which tests OBDefaultOIDCClaimsCallbackHandlerTest. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({FrameworkUtils.class, IdentityCommonUtil.class, JWTClaimsSet.class}) -public class OBDefaultOIDCClaimsCallbackHandlerTest { - - @Spy - private OBDefaultOIDCClaimsCallbackHandler obDefaultOIDCClaimsCallbackHandler; - - @BeforeClass - public void beforeClass() { - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CONSENT_ID_CLAIM_NAME, "consent_id"); - configMap.put(IdentityCommonConstants.REMOVE_TENANT_DOMAIN_FROM_SUBJECT, "true"); - configMap.put(IdentityCommonConstants.REMOVE_USER_STORE_DOMAIN_FROM_SUBJECT, "true"); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - mockStatic(FrameworkUtils.class); - mockStatic(IdentityCommonUtil.class); - when(FrameworkUtils.getMultiAttributeSeparator()).thenReturn(MULTI_ATTRIBUTE_SEPARATOR_DEFAULT); - obDefaultOIDCClaimsCallbackHandler = Mockito.spy(OBDefaultOIDCClaimsCallbackHandler.class); - } - - public static String getFilePath(String fileName) { - - if (StringUtils.isNotBlank(fileName)) { - URL url = OBDefaultOIDCClaimsCallbackHandlerTest.class.getClassLoader().getResource(fileName); - if (url != null) { - try { - File file = new File(url.toURI()); - return file.getAbsolutePath(); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Could not resolve a file with given path: " + - url.toExternalForm()); - } - } - } - throw new IllegalArgumentException("DB Script file name cannot be empty."); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test(description = "Test the best case scenario in handling custom claims") - public void testHandleCustomClaims() throws OpenBankingException, IdentityOAuth2Exception { - - JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder(); - OAuth2AccessTokenReqDTO oauth2AccessTokenReqDTO = new OAuth2AccessTokenReqDTO(); - - HttpRequestHeader[] httpRequestHeaders = new HttpRequestHeader[1]; - httpRequestHeaders[0] = new HttpRequestHeader(IdentityCommonConstants.CERTIFICATE_HEADER, - TestConstants.CERTIFICATE_CONTENT); - oauth2AccessTokenReqDTO.setHttpRequestHeaders(httpRequestHeaders); - - oauth2AccessTokenReqDTO.setGrantType("client_credentials"); - oauth2AccessTokenReqDTO.setClientId("123"); - OAuthTokenReqMessageContext oAuthTokenReqMessageContext = - new OAuthTokenReqMessageContext(oauth2AccessTokenReqDTO); - - String[] scopes = new String[1]; - scopes[0] = "consent_id" + "123"; - oAuthTokenReqMessageContext.setScope(scopes); - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setUserName("aaa@gold.com"); - authenticatedUser.setTenantDomain("carbon.super"); - authenticatedUser.setUserStoreDomain("PRIMARY"); - authenticatedUser.setFederatedIdPName("LOCAL"); - authenticatedUser.setFederatedUser(false); - authenticatedUser.setAuthenticatedSubjectIdentifier("aaa@gold.com@carbon.super"); - oAuthTokenReqMessageContext.setAuthorizedUser(authenticatedUser); - JWTClaimsSet jwtClaimsSetInitial = PowerMockito.mock(JWTClaimsSet.class); - PowerMockito.when(jwtClaimsSetInitial.getClaims()).thenReturn(new SingletonMap("scope", "test")); - Mockito.doReturn(jwtClaimsSetInitial).when(obDefaultOIDCClaimsCallbackHandler) - .getJwtClaimsFromSuperClass(jwtClaimsSetBuilder, oAuthTokenReqMessageContext); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("123")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - JWTClaimsSet jwtClaimsSet = obDefaultOIDCClaimsCallbackHandler.handleCustomClaims(jwtClaimsSetBuilder, - oAuthTokenReqMessageContext); - - - assertEquals("123", jwtClaimsSet.getClaim("consent_id")); - assertEquals("{x5t#S256=807-E8KgUMV6dRHTQi1_QYo5eyPvjmjbxCtunbFixV0}", jwtClaimsSet.getClaim( - "cnf").toString()); - assertEquals("aaa@gold.com", jwtClaimsSet.getClaim("sub")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/claims/RoleClaimProviderImplTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/claims/RoleClaimProviderImplTest.java deleted file mode 100644 index bb964578..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/claims/RoleClaimProviderImplTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.claims; - -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.base.IdentityRuntimeException; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; - -import java.util.Map; - -/** - * Test for role claim provider implementation. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityTenantUtil.class, IdentityExtensionsDataHolder.class}) -public class RoleClaimProviderImplTest extends PowerMockTestCase { - - private static final String USER_MARK = "mark@gold.com"; - private static final String USER_TOM = "tom@gold.com"; - private static final String USER_ANN = "ann@gold.com"; - private static final String CCO_ROLE = "Internal/CustomerCareOfficerRole"; - private static final String CC_OFFICER = "customerCareOfficer"; - private static final String[] SCOPES = new String[]{"openid", "consents:read_all"}; - - private RoleClaimProviderImpl uut; - - @BeforeClass - public void init() { - this.uut = new RoleClaimProviderImpl(); - } - - public void setup(String userName) throws UserStoreException { - PowerMockito.mockStatic(IdentityTenantUtil.class); - if (USER_ANN.equals(userName)) { - PowerMockito.when(IdentityTenantUtil.getTenantIdOfUser(USER_ANN)) - .thenThrow(new IdentityRuntimeException("")); - } else { - PowerMockito.when(IdentityTenantUtil.getTenantIdOfUser(Mockito.anyString())).thenReturn(1234); - } - - UserStoreManager userStoreManagerMock = Mockito.mock(UserStoreManager.class); - if (USER_TOM.equals(userName)) { - Mockito.when(userStoreManagerMock.getRoleListOfUser(USER_TOM)).thenThrow(new UserStoreException()); - } else { - Mockito.when(userStoreManagerMock.getRoleListOfUser(Mockito.anyString())) - .thenReturn(new String[]{CCO_ROLE}); - } - UserRealm userRealmMock = Mockito.mock(UserRealm.class); - Mockito.when(userRealmMock.getUserStoreManager()).thenReturn(userStoreManagerMock); - - RealmService realmServiceMock = Mockito.mock(RealmService.class); - Mockito.when(realmServiceMock.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealmMock); - - IdentityExtensionsDataHolder identityExtensionsDataHolderMock = Mockito - .mock(IdentityExtensionsDataHolder.class); - Mockito.when(identityExtensionsDataHolderMock.getRealmService()).thenReturn(realmServiceMock); - - PowerMockito.mockStatic(IdentityExtensionsDataHolder.class); - PowerMockito.when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolderMock); - } - - @Test(description = "when customer care officer is sending request, return customerCareOfficer role") - public void testGetAdditionalClaimsWithCustomerCareOfficerRole() - throws IdentityOAuth2Exception, UserStoreException { - setup(USER_MARK); - // mock - OAuthTokenReqMessageContext oAuthTokenReqMessageContextMock = Mockito.mock(OAuthTokenReqMessageContext.class); - AuthenticatedUser authorizedUserMock = Mockito.mock(AuthenticatedUser.class); - - // when - Mockito.when(authorizedUserMock.getUserName()).thenReturn(USER_MARK); - - Mockito.when(oAuthTokenReqMessageContextMock.getScope()).thenReturn(SCOPES); - Mockito.when(oAuthTokenReqMessageContextMock.getAuthorizedUser()).thenReturn(authorizedUserMock); - - Map claims = uut.getAdditionalClaims(oAuthTokenReqMessageContextMock, null); - - // assert - Assert.assertEquals(claims.get("user_role"), CC_OFFICER); - } - - @Test(description = "when IdentityRuntimeException occurs, do not return user_role value") - public void testGetAdditionalClaimsThrowIdentityRuntimeException() - throws IdentityOAuth2Exception, UserStoreException { - setup(USER_ANN); - // mock - OAuthTokenReqMessageContext oAuthTokenReqMessageContextMock = Mockito.mock(OAuthTokenReqMessageContext.class); - AuthenticatedUser authorizedUserMock = Mockito.mock(AuthenticatedUser.class); - - // when - Mockito.when(authorizedUserMock.getUserName()).thenReturn(USER_ANN); - - Mockito.when(oAuthTokenReqMessageContextMock.getScope()).thenReturn(SCOPES); - Mockito.when(oAuthTokenReqMessageContextMock.getAuthorizedUser()).thenReturn(authorizedUserMock); - - Map claims = uut.getAdditionalClaims(oAuthTokenReqMessageContextMock, null); - - // assert - Assert.assertFalse(claims.containsKey("user_role")); - } - - @Test(description = "when UserStoreException occurs, do not return user_role value") - public void testGetAdditionalClaimsThrowUserStoreException() - throws IdentityOAuth2Exception, UserStoreException { - setup(USER_TOM); - // mock - OAuthTokenReqMessageContext oAuthTokenReqMessageContextMock = Mockito.mock(OAuthTokenReqMessageContext.class); - AuthenticatedUser authorizedUserMock = Mockito.mock(AuthenticatedUser.class); - - // when - Mockito.when(authorizedUserMock.getUserName()).thenReturn(USER_TOM); - - Mockito.when(oAuthTokenReqMessageContextMock.getScope()).thenReturn(SCOPES); - Mockito.when(oAuthTokenReqMessageContextMock.getAuthorizedUser()).thenReturn(authorizedUserMock); - - Map claims = uut.getAdditionalClaims(oAuthTokenReqMessageContextMock, null); - - // assert - Assert.assertFalse(claims.containsKey("user_role")); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/clientauth/OBMutualTLSClientAuthenticatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/clientauth/OBMutualTLSClientAuthenticatorTest.java deleted file mode 100644 index 01c2e95f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/clientauth/OBMutualTLSClientAuthenticatorTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.clientauth; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnException; -import org.wso2.carbon.identity.oauth2.token.handler.clientauth.mutualtls.utils.MutualTLSUtil; - -import java.net.URL; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -/** - * Test for Open Banking mutual TLS client authenticator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class, MutualTLSUtil.class}) -public class OBMutualTLSClientAuthenticatorTest extends PowerMockTestCase { - - MockHttpServletResponse response; - MockHttpServletRequest request; - OAuthClientAuthnContext clientAuthnContext = new OAuthClientAuthnContext(); - - @BeforeClass - public void beforeClass() { - clientAuthnContext.setClientId("test"); - } - - @BeforeMethod - public void beforeMethod() { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - - } - - @Test(description = "Test whether can authenticate is engaged for mtls request") - public void canAuthenticateTest() throws OpenBankingException { - PowerMockito.mockStatic(IdentityCommonUtil.class); - Map bodyParams = new HashMap<>(); - clientAuthnContext.setClientId(""); - bodyParams.put("client_id", Collections.singletonList("test")); - - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - boolean response = authenticator.canAuthenticate(request, bodyParams, clientAuthnContext); - assertTrue(response); - } - - @Test(description = "Test whether can authenticate is not engaged when request does not have a client ID") - public void canAuthenticateNoClientIDTest() throws OpenBankingException { - PowerMockito.mockStatic(IdentityCommonUtil.class); - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - boolean response = authenticator.canAuthenticate(request, null, clientAuthnContext); - assertFalse(response); - } - - @Test(description = "Test whether can authenticate is not engaged when request has invalid certificate") - public void canAuthenticateInvalidCertTest() throws OpenBankingException { - PowerMockito.mockStatic(IdentityCommonUtil.class); - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, "test"); - try { - authenticator.canAuthenticate(request, null, clientAuthnContext); - } catch (Exception e) { - assertEquals(e.getMessage(), "Transport certificate passed through the request not valid"); - } - } - - @Test(description = "Test whether can authenticate is not engaged when request does not have a cert header") - public void canAuthenticateNoCertHeaderTest() throws OpenBankingException { - PowerMockito.mockStatic(IdentityCommonUtil.class); - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - boolean response = authenticator.canAuthenticate(request, null, clientAuthnContext); - assertFalse(response); - } - - @Test(description = "Test whether obtaining JWKS endpoint of the SP is succesful") - public void getJWKSEndpointOfSPTest() throws OAuthClientAuthnException { - PowerMockito.mockStatic(MutualTLSUtil.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.getJWKURITransportCert()).thenReturn("dummy"); - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - String expectedUrl = "https://dummy.com"; - PowerMockito.when(MutualTLSUtil.getPropertyValue(Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(expectedUrl); - URL url = authenticator.getJWKSEndpointOfSP(Mockito.anyObject(), Mockito.anyObject()); - assertEquals(url.getHost(), "dummy.com"); - } - - @Test(description = "Test whether obtaining JWKS endpoint of the SP is failing when empty JWKS URI is given") - public void getJWKSEndpointOfSPEmptyTest() { - PowerMockito.mockStatic(MutualTLSUtil.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.getJWKURITransportCert()).thenReturn(""); - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - String expectedUrl = "https://dummy.com"; - PowerMockito.when(MutualTLSUtil.getPropertyValue(Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(expectedUrl); - try { - authenticator.getJWKSEndpointOfSP(Mockito.anyObject(), Mockito.anyObject()); - } catch (OAuthClientAuthnException e) { - assertEquals(e.getErrorCode(), "server_error"); - } - } - - @Test(description = "Test whether obtaining JWKS endpoint of the SP is failing when malformed URI is given") - public void getJWKSEndpointOfSPMalformedURITest() { - PowerMockito.mockStatic(MutualTLSUtil.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.getJWKURITransportCert()).thenReturn(""); - OBMutualTLSClientAuthenticator authenticator = Mockito.spy(OBMutualTLSClientAuthenticator.class); - String expectedUrl = "dummy"; - PowerMockito.when(MutualTLSUtil.getPropertyValue(Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(expectedUrl); - try { - authenticator.getJWKSEndpointOfSP(Mockito.anyObject(), Mockito.anyObject()); - } catch (OAuthClientAuthnException e) { - assertEquals(e.getErrorCode(), "server_error"); - } - } - - private X509Certificate getCertificate(String certificateContent) { - - if (StringUtils.isNotBlank(certificateContent)) { - // Build the Certificate object from cert content. - try { - return (X509Certificate) IdentityUtil.convertPEMEncodedContentToCertificate(certificateContent); - } catch (CertificateException e) { - //do nothing - } - } - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRExtendedValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRExtendedValidatorTest.java deleted file mode 100644 index 90efe69c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRExtendedValidatorTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr; - -import com.google.gson.Gson; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.model.SoftwareStatementBody; -import com.wso2.openbanking.accelerator.identity.dcr.util.ExtendedSoftwareStatementBody; -import com.wso2.openbanking.accelerator.identity.dcr.util.ExtendedValidatorImpl; -import com.wso2.openbanking.accelerator.identity.dcr.util.RegistrationTestConstants; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Test for DCR extended validator. - */ -public class DCRExtendedValidatorTest { - - private RegistrationRequest registrationRequest; - private ExtendedValidatorImpl extendedValidator = new ExtendedValidatorImpl(); - - private static final Log log = LogFactory.getLog(DCRValidationTest.class); - - @BeforeClass - public void beforeClass() { - - Map confMap = new HashMap<>(); - Map> dcrRegistrationConfMap = new HashMap<>(); - Gson gson = new Gson(); - registrationRequest = gson.fromJson(RegistrationTestConstants.extendedRegistrationRequestJson, - RegistrationRequest.class); - String decodedSSA = null; - try { - decodedSSA = JWTUtils - .decodeRequestJWT(registrationRequest.getSoftwareStatement(), "body").toJSONString(); - } catch (ParseException e) { - log.error("Error while parsing the SSA", e); - } - extendedValidator.setSoftwareStatementPayload(registrationRequest, decodedSSA); - - List validAlgorithms = new ArrayList<>(); - validAlgorithms.add("PS256"); - validAlgorithms.add("ES256"); - confMap.put(OpenBankingConstants.SIGNATURE_ALGORITHMS, validAlgorithms); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(confMap); - IdentityExtensionsDataHolder.getInstance().setDcrRegistrationConfigMap(dcrRegistrationConfMap); - } - - @Test - public void testExtendedValidatorFailure() { - - try { - extendedValidator.validatePost(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Redirect URIs can not be null")); - - } - } - - @Test - public void testExtendedSSAAttributes() { - - SoftwareStatementBody softwareStatementBody = registrationRequest.getSoftwareStatementBody(); - Assert.assertEquals(((ExtendedSoftwareStatementBody) softwareStatementBody).getLogURI(), - "https://wso2.com/wso2.jpg"); - } - - @Test - public void testExtendedRegistrationResponse() { - String additionalAttributes = "\"additional_attribute_1\":\"111111\",\"additional_attribute_2\":\"222222\""; - String registrationResponse = extendedValidator.getRegistrationResponse(new HashMap<>()); - Assert.assertTrue(registrationResponse.contains(additionalAttributes)); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRValidationTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRValidationTest.java deleted file mode 100644 index af5dccf8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRValidationTest.java +++ /dev/null @@ -1,301 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr; - -import com.google.gson.Gson; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.util.RegistrationTestConstants; -import com.wso2.openbanking.accelerator.identity.dcr.utils.ValidatorUtils; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DefaultRegistrationValidatorImpl; -import com.wso2.openbanking.accelerator.identity.dcr.validation.RegistrationValidator; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Test for DCR validation. - */ -public class DCRValidationTest { - - private static final Log log = LogFactory.getLog(DCRValidationTest.class); - - private RegistrationValidator registrationValidator; - private RegistrationRequest registrationRequest; - private static final String NULL = "null"; - - @BeforeClass - public void beforeClass() { - - Map confMap = new HashMap<>(); - Map> dcrRegistrationConfMap = new HashMap<>(); - Map> dcrRegistrationConfMap2 = new HashMap<>(); - List registrationParams = Arrays.asList("Issuer:true:null", - "TokenEndPointAuthentication:true:private_key_jwt", "ResponseTypes:true:code id_token", - "GrantTypes:true:authorization_code,refresh_token", "ApplicationType:false:web", - "IdTokenSignedResponseAlg:true:null", "SoftwareStatement:true:null", "Scope:false:accounts,payments"); - confMap.put(DCRCommonConstants.DCR_VALIDATOR, "com.wso2.openbanking.accelerator.identity.dcr" + - ".validation.DefaultRegistrationValidatorImpl"); - List validAlgorithms = new ArrayList<>(); - validAlgorithms.add("PS256"); - validAlgorithms.add("ES256"); - confMap.put(OpenBankingConstants.SIGNATURE_ALGORITHMS, validAlgorithms); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(confMap); - String dcrValidator = confMap.get(DCRCommonConstants.DCR_VALIDATOR).toString(); - registrationValidator = getDCRValidator(dcrValidator); - registrationRequest = getRegistrationRequestObject(RegistrationTestConstants.registrationRequestJson); - //set registration parameter values for testing - for (String param : registrationParams) { - setParamConfig(param, dcrRegistrationConfMap); - } - IdentityExtensionsDataHolder.getInstance().setDcrRegistrationConfigMap(dcrRegistrationConfMap); - } - - @Test - public void testInvalidAlgorithm() { - - registrationRequest.setIdTokenSignedResponseAlg("RS256"); - - String decodedSSA = null; - try { - decodedSSA = JWTUtils - .decodeRequestJWT(registrationRequest.getSoftwareStatement(), "body").toJSONString(); - } catch (ParseException e) { - log.error("Error while parsing the SSA", e); - } - registrationValidator.setSoftwareStatementPayload(registrationRequest, decodedSSA); - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Invalid signing algorithm sent")); - } - } - - @Test(dependsOnMethods = "testInvalidAlgorithm") - public void testInvalidIssuer() { - - registrationRequest.setIdTokenSignedResponseAlg("PS256"); - registrationRequest.setIssuer("222"); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Invalid issuer")); - } - - } - - @Test(dependsOnMethods = "testInvalidIssuer") - public void testIssuerExists() { - - registrationRequest.setIssuer(null); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Required parameter issuer cannot be null")); - } - - } - - @Test(dependsOnMethods = "testIssuerExists") - public void testTokenEndPointAuthMethodExists() { - - registrationRequest.setIssuer("9b5usDpbNtmxDcTzs7GzKp"); - registrationRequest.setTokenEndPointAuthentication(""); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription() - .contains("Required parameter tokenEndPointAuthentication cannot be empty")); - } - } - - @Test(dependsOnMethods = "testTokenEndPointAuthMethodExists") - public void testResponseTypesExists() { - - registrationRequest.setTokenEndPointAuthentication("private_key_jwt"); - registrationRequest.setResponseTypes(new ArrayList<>()); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription() - .contains("Required parameter responseTypes cannot be empty")); - } - } - - @Test(dependsOnMethods = "testResponseTypesExists") - public void testGrantTypesExists() { - - List responseTypeList = new ArrayList(); - responseTypeList.add("code id_token"); - registrationRequest.setResponseTypes(responseTypeList); - - registrationRequest.setGrantTypes(null); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Required parameter grantTypes cannot be null")); - } - } - - @Test(dependsOnMethods = "testGrantTypesExists") - public void testIdTokenSignedResponseAlgExists() { - - List grantTypeList = new ArrayList(); - grantTypeList.add("authorization_code"); - grantTypeList.add("refresh_token"); - registrationRequest.setGrantTypes(grantTypeList); - - registrationRequest.setIdTokenSignedResponseAlg(null); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (OpenBankingException e) { - Assert.assertTrue(e.getMessage().contains("Required parameter idTokenSignedResponseAlg cannot be null")); - } - } - - @Test(dependsOnMethods = "testIdTokenSignedResponseAlgExists") - public void testValidationViolations() { - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (OpenBankingException e) { - Assert.assertTrue(e.getMessage().contains("Required parameter idTokenSignedResponseAlg cannot be null")); - } - } - - @Test(dependsOnMethods = "testValidationViolations") - public void testDefaultValidator() { - - try { - registrationValidator.validatePost(registrationRequest); - - registrationValidator.validateUpdate(registrationRequest); - - registrationValidator.validateGet("1234"); - - registrationValidator.validateDelete("1234"); - } catch (OpenBankingException e) { - Assert.assertTrue(e.getMessage().contains("Required parameter idTokenSignedResponseAlg cannot be null")); - } - } - - @Test(dependsOnMethods = "testDefaultValidator") - public void testSoftwareStatementExists() { - - registrationRequest.setIdTokenSignedResponseAlg("PS256"); - registrationRequest.setSoftwareStatement(null); - - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (OpenBankingException e) { - Assert.assertTrue(e.getMessage().contains("Required parameter softwareStatement cannot be null")); - } - } - - @Test(dependsOnMethods = "testSoftwareStatementExists") - public void testSSAParsingException() { - - registrationRequest.setSoftwareStatement("effff"); - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (OpenBankingException e) { - Assert.assertTrue(e.getMessage().contains("Invalid issuer")); - } - } - - @Test (dependsOnMethods = "testSSAParsingException") - public void testResponseTypesAllowedValues() { - - List responseTypeList = new ArrayList(); - responseTypeList.add(""); - registrationRequest.setResponseTypes(responseTypeList); - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Invalid responseTypes provided")); - } - } - - @Test (dependsOnMethods = "testResponseTypesAllowedValues") - public void testApplicationTypeAllowedValues() { - - List responseTypeList = new ArrayList(); - responseTypeList.add("code id_token"); - registrationRequest.setResponseTypes(responseTypeList); - registrationRequest.setApplicationType(""); - try { - ValidatorUtils.getValidationViolations(registrationRequest); - } catch (DCRValidationException e) { - Assert.assertTrue(e.getErrorDescription().contains("Invalid applicationType provided")); - } - } - - private static RegistrationRequest getRegistrationRequestObject(String request) { - - Gson gson = new Gson(); - return gson.fromJson(request, RegistrationRequest.class); - } - - public static RegistrationValidator getDCRValidator(String dcrValidator) { - - if (StringUtils.isEmpty(dcrValidator)) { - return new DefaultRegistrationValidatorImpl(); - } - try { - return (RegistrationValidator) Class.forName(dcrValidator).newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - log.error("Error instantiating " + dcrValidator, e); - return new DefaultRegistrationValidatorImpl(); - } catch (ClassNotFoundException e) { - log.error("Cannot find class: " + dcrValidator, e); - return new DefaultRegistrationValidatorImpl(); - } - } - - private void setParamConfig(String configParam, Map> dcrRegistrationConfMap) { - Map parameterValues = new HashMap<>(); - parameterValues.put(DCRCommonConstants.DCR_REGISTRATION_PARAM_REQUIRED, configParam.split(":")[1]); - if (!NULL.equalsIgnoreCase(configParam.split(":")[2])) { - List allowedValues = new ArrayList<>(); - allowedValues.addAll(Arrays.asList(configParam.split(":")[2].split(","))); - parameterValues.put(DCRCommonConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUES, allowedValues); - } - dcrRegistrationConfMap.put(configParam.split(":")[0], parameterValues); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRValidationUtilTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRValidationUtilTest.java deleted file mode 100644 index f71510c0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/DCRValidationUtilTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr; - -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.util.RegistrationTestConstants; -import com.wso2.openbanking.accelerator.identity.dcr.utils.ValidatorUtils; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.util.HashMap; - -/** - * Test for DCR validation util. - */ -public class DCRValidationUtilTest { - - private static final Log log = LogFactory.getLog(DCRValidationTest.class); - - @Test - public void testJWTDecodeHead() { - - try { - JSONObject decodedObject = JWTUtils.decodeRequestJWT(RegistrationTestConstants.SSA, "head"); - Assert.assertEquals(decodedObject.getAsString("alg"), "PS256"); - } catch (ParseException e) { - log.error("Error while parsing the jwt", e); - } - - } - - @Test - public void testJWTDecodeBody() { - - try { - JSONObject decodedObject = JWTUtils.decodeRequestJWT(RegistrationTestConstants.SSA, "body"); - Assert.assertEquals(decodedObject.getAsString("software_environment"), "sandbox"); - } catch (ParseException e) { - log.error("Error while parsing the jwt", e); - } - } - - @Test - public void testGetRegistrationClientURI() { - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(new HashMap<>()); - String registrationClientURI = ValidatorUtils.getRegistrationClientURI(); - Assert.assertEquals(registrationClientURI, "https://localhost:8243/open-banking/0.1/register/"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedRegistrationRequest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedRegistrationRequest.java deleted file mode 100644 index db22db7d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedRegistrationRequest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.util; - -import com.wso2.openbanking.accelerator.identity.common.annotations.validationgroups.MandatoryChecks; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.model.SoftwareStatementBody; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; - -import java.util.List; - -import javax.validation.constraints.NotNull; - -/** - * Extended registration request. - */ -public class ExtendedRegistrationRequest extends RegistrationRequest { - - private RegistrationRequest registrationRequest; - - ExtendedRegistrationRequest(RegistrationRequest registrationRequest) { - - this.registrationRequest = registrationRequest; - } - - @Override - @NotNull(message = "Redirect URIs can not be null:" + DCRCommonConstants.INVALID_META_DATA, - groups = MandatoryChecks.class) - public List getCallbackUris() { - - return registrationRequest.getCallbackUris(); - } - - @Override - public String getIssuer() { - - return registrationRequest.getIssuer(); - } - - @Override - public String getTokenEndPointAuthentication() { - - return registrationRequest.getTokenEndPointAuthentication(); - } - - @Override - public List getGrantTypes() { - - return registrationRequest.getGrantTypes(); - } - - @Override - public String getSoftwareStatement() { - - return registrationRequest.getSoftwareStatement(); - } - - @Override - public String getIdTokenSignedResponseAlg() { - - return registrationRequest.getIdTokenSignedResponseAlg(); - } - - @Override - public SoftwareStatementBody getSoftwareStatementBody() { - - return registrationRequest.getSoftwareStatementBody(); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedRegistrationResponse.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedRegistrationResponse.java deleted file mode 100644 index 58f65184..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedRegistrationResponse.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.util; - -import com.google.gson.annotations.SerializedName; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationResponse; -/** - * Extended class for RegistrationResponse. - */ -public class ExtendedRegistrationResponse extends RegistrationResponse { - - @SerializedName("additional_attribute_1") - protected String additionalAttribute1 = null; - - @SerializedName("additional_attribute_2") - protected String additionalAttribute2 = null; - - public String getAdditionalAttribute1() { - return additionalAttribute1; - } - - public void setAdditionalAttribute1(String additionalAttribute1) { - this.additionalAttribute1 = additionalAttribute1; - } - - public String getAdditionalAttribute2() { - return additionalAttribute2; - } - - public void setAdditionalAttribute2(String additionalAttribute2) { - this.additionalAttribute2 = additionalAttribute2; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedSoftwareStatementBody.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedSoftwareStatementBody.java deleted file mode 100644 index 7055dd16..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedSoftwareStatementBody.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.util; - -import com.google.gson.annotations.SerializedName; -import com.wso2.openbanking.accelerator.identity.dcr.model.SoftwareStatementBody; - -/** - * Extended software statement body. - */ -public class ExtendedSoftwareStatementBody extends SoftwareStatementBody { - - - public String getLogURI() { - - return logURI; - } - - public void setLogURI(String logURI) { - - this.logURI = logURI; - } - - @SerializedName("software_logo_uri") - private String logURI; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedValidatorImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedValidatorImpl.java deleted file mode 100644 index a2515876..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/ExtendedValidatorImpl.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.util; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.model.SoftwareStatementBody; -import com.wso2.openbanking.accelerator.identity.dcr.utils.ValidatorUtils; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DefaultRegistrationValidatorImpl; - -import java.util.Map; - -/** - * Extended validator implementation. - */ -public class ExtendedValidatorImpl extends DefaultRegistrationValidatorImpl { - - @Override - public void validatePost(RegistrationRequest registrationRequest) throws DCRValidationException { - - ExtendedRegistrationRequest request = new ExtendedRegistrationRequest(registrationRequest); - ValidatorUtils.getValidationViolations(request); - } - - @Override - public void validateGet(String clientId) throws DCRValidationException { - - } - - @Override - public void validateDelete(String clientId) throws DCRValidationException { - - } - - @Override - public void validateUpdate(RegistrationRequest registrationRequest) throws DCRValidationException { - - } - - @Override - public String getRegistrationResponse(Map clientMetaData) { - - clientMetaData.put("additional_attribute_1", "111111"); - clientMetaData.put("additional_attribute_2", "222222"); - - Gson gson = new Gson(); - JsonElement jsonElement = gson.toJsonTree(clientMetaData); - ExtendedRegistrationResponse registrationResponse = - gson.fromJson(jsonElement, ExtendedRegistrationResponse.class); - return gson.toJson(registrationResponse); - } - - @Override - public void setSoftwareStatementPayload(RegistrationRequest registrationRequest, String decodedSSA) { - - SoftwareStatementBody softwareStatementPayload = new GsonBuilder().create() - .fromJson(decodedSSA, ExtendedSoftwareStatementBody.class); - registrationRequest.setSoftwareStatementBody(softwareStatementPayload); - - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/RegistrationTestConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/RegistrationTestConstants.java deleted file mode 100644 index 51dc5e76..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/util/RegistrationTestConstants.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.util; - -/** - * Registration test constants. - */ -public class RegistrationTestConstants { - - public static final String SSA = "eyJhbGciOiJQUzI1NiIsImtpZCI6IkR3TUtkV01tajdQV2ludm9xZlF5WFZ6eVo2USIs" + - "InR5cCI6IkpXVCJ9.eyJpc3MiOiJPcGVuQmFua2luZyBMdGQiLCJpYXQiOjE1OTIzNjQ1NjgsImp0aSI6IjNkMWIzNTk1ZWZh" + - "YzRlMzYiLCJzb2Z0d2FyZV9lbnZpcm9ubWVudCI6InNhbmRib3giLCJzb2Z0d2FyZV9tb2RlIjoiVGVzdCIsInNvZnR3YXJlX2" + - "lkIjoiOWI1dXNEcGJOdG14RGNUenM3R3pLcCIsInNvZnR3YXJlX2NsaWVudF9pZCI6IjliNXVzRHBiTnRteERjVHpzN0d6S3AiLC" + - "Jzb2Z0d2FyZV9jbGllbnRfbmFtZSI6IlRlc3QgQVBQIE5ldyIsInNvZnR3YXJlX2NsaWVudF9kZXNjcmlwdGlvbiI6IlRoaXMgVFBQ" + - "IElzIGNyZWF0ZWQgZm9yIHRlc3RpbmcgcHVycG9zZXMuICIsInNvZnR3YXJlX3ZlcnNpb24iOjEuNSwic29mdHdhcmVfY2xpZW50X3V" + - "yaSI6Imh0dHBzOi8vd3NvMi5jb20iLCJzb2Z0d2FyZV9yZWRpcmVjdF91cmlzIjpbImh0dHBzOi8vd3NvMi5jb20iXSwic29mdHdhcmV" + - "fcm9sZXMiOlsiQUlTUCIsIlBJU1AiXSwib3JnYW5pc2F0aW9uX2NvbXBldGVudF9hdXRob3JpdHlfY2xhaW1zIjp7ImF1dGhvcml0eV" + - "9pZCI6Ik9CR0JSIiwicmVnaXN0cmF0aW9uX2lkIjoiVW5rbm93bjAwMTU4MDAwMDFIUVFyWkFBWCIsInN0YXR1cyI6IkFjdGl2ZSIsI" + - "mF1dGhvcmlzYXRpb25zIjpbeyJtZW1iZXJfc3RhdGUiOiJHQiIsInJvbGVzIjpbIkFJU1AiLCJQSVNQIl19LHsibWVtYmVyX3N0YXRl" + - "IjoiSUUiLCJyb2xlcyI6WyJBSVNQIiwiUElTUCJdfSx7Im1lbWJlcl9zdGF0ZSI6Ik5MIiwicm9sZXMiOlsiQUlTUCIsIlBJU1AiXX1" + - "dfSwic29mdHdhcmVfbG9nb191cmkiOiJodHRwczovL3dzbzIuY29tL3dzbzIuanBnIiwib3JnX3N0YXR1cyI6IkFjdGl2ZSIsIm9yZ1" + - "9pZCI6IjAwMTU4MDAwMDFIUVFyWkFBWCIsIm9yZ19uYW1lIjoiV1NPMiAoVUspIExJTUlURUQiLCJvcmdfY29udGFjdHMiOlt7Im5hb" + - "WUiOiJUZWNobmljYWwiLCJlbWFpbCI6InNhY2hpbmlzQHdzbzIuY29tIiwicGhvbmUiOiIrOTQ3NzQyNzQzNzQiLCJ0eXBlIjoiVGVj" + - "aG5pY2FsIn0seyJuYW1lIjoiQnVzaW5lc3MiLCJlbWFpbCI6InNhY2hpbmlzQHdzbzIuY29tIiwicGhvbmUiOiIrOTQ3NzQyNzQzNzQ" + - "iLCJ0eXBlIjoiQnVzaW5lc3MifV0sIm9yZ19qd2tzX2VuZHBvaW50IjoiaHR0cHM6Ly9rZXlzdG9yZS5vcGVuYmFua2luZ3Rlc3Qub3" + - "JnLnVrLzAwMTU4MDAwMDFIUVFyWkFBWC8wMDE1ODAwMDAxSFFRclpBQVguandrcyIsIm9yZ19qd2tzX3Jldm9rZWRfZW5kcG9pbnQiO" + - "iJodHRwczovL2tleXN0b3JlLm9wZW5iYW5raW5ndGVzdC5vcmcudWsvMDAxNTgwMDAwMUhRUXJaQUFYL3Jldm9rZWQvMDAxNTgwMDAw" + - "MUhRUXJaQUFYLmp3a3MiLCJzb2Z0d2FyZV9qd2tzX2VuZHBvaW50IjoiaHR0cHM6Ly9rZXlzdG9yZS5vcGVuYmFua2luZ3Rlc3Qub3J" + - "nLnVrLzAwMTU4MDAwMDFIUVFyWkFBWC85YjV1c0RwYk50bXhEY1R6czdHektwLmp3a3MiLCJzb2Z0d2FyZV9qd2tzX3Jldm9rZWRfZW5" + - "kcG9pbnQiOiJodHRwczovL2tleXN0b3JlLm9wZW5iYW5raW5ndGVzdC5vcmcudWsvMDAxNTgwMDAwMUhRUXJaQUFYL3Jldm9rZWQvOW" + - "I1dXNEcGJOdG14RGNUenM3R3pLcC5qd2tzIiwic29mdHdhcmVfcG9saWN5X3VyaSI6Imh0dHBzOi8vd3NvMi5jb20iLCJzb2Z0d2FyZ" + - "V90b3NfdXJpIjoiaHR0cHM6Ly93c28yLmNvbSIsInNvZnR3YXJlX29uX2JlaGFsZl9vZl9vcmciOiJXU08yIE9wZW4gQmFua2luZyJ9" + - ".mkbNeMGPNPEGqZbm06__7rWG9RWeEZ8MKgdLZGPkF0HMXX6MoPrw3e5ymZ_kxtVe5cRM2IVFThN1VBSuafThMH0PYwwRY2_3NApUWa" + - "f6BExL34Sbq_plmz8Ciq2zXYiYWPq2ReS1aPSJ-67nRF8Dnap5QLhqmowIDcGz1byTe2mukFc6CmBmwTBeDC_px56i4_n5xHXtrVBIf" + - "jFYcv2VewJ7K050JMmdIvdODafGei61JQIDrRUT_w0yU4-8WG9IDBI7G4H_GCPWmckJFApZyCnIWeBaEmfe6l2_GQs9VkQq1U1xJXtd" + - "WAfrzEjbMMnZSvqdoQAISq0y6mQofA0n5g"; - - public static String registrationRequestJson = "{\n" + - " \"iss\": \"9b5usDpbNtmxDcTzs7GzKp\",\n" + - " \"iat\": 1593752054,\n" + - " \"exp\": 1743573565,\n" + - " \"jti\": \"92713892-5514-11e9-8647-d663bd873d93\",\n" + - " \"aud\": \"https://localbank.com\",\n" + - " \"scope\": \"accounts payments\",\n" + - " \"token_endpoint_auth_method\": \"private_key_jwt\",\n" + - " \"grant_types\": [\n" + - " \"authorization_code\",\n" + - " \"refresh_token\"\n" + - " ],\n" + - " \"response_types\": [\n" + - " \"code id_token\"\n" + - " ],\n" + - " \"id_token_signed_response_alg\": \"PS256\",\n" + - " \"request_object_signing_alg\": \"PS256\",\n" + - " \"software_id\": \"9b5usDpbNtmxDcTzs7GzKp\",\n" + - " \"application_type\": \"web\",\n" + - " \"redirect_uris\": [\n" + - " \"https://wso2.com\"\n" + - " ],\n" + - " \"software_statement\" : " + RegistrationTestConstants.SSA + - "}"; - - public static String extendedRegistrationRequestJson = "{\n" + - " \"iss\": \"9b5usDpbNtmxDcTzs7GzKp\",\n" + - " \"iat\": 1593752054,\n" + - " \"exp\": 1743573565,\n" + - " \"jti\": \"92713892-5514-11e9-8647-d663bd873d93\",\n" + - " \"aud\": \"https://localbank.com\",\n" + - " \"scope\": \"accounts payments\",\n" + - " \"token_endpoint_auth_method\": \"private_key_jwt\",\n" + - " \"grant_types\": [\n" + - " \"authorization_code\",\n" + - " \"refresh_token\"\n" + - " ],\n" + - " \"response_types\": [\n" + - " \"code id_token\"\n" + - " ],\n" + - " \"id_token_signed_response_alg\": \"PS256\",\n" + - " \"request_object_signing_alg\": \"PS256\",\n" + - " \"software_id\": \"9b5usDpbNtmxDcTzs7GzKp\",\n" + - " \"application_type\": \"web\",\n" + - " \"software_statement\" : " + RegistrationTestConstants.SSA + - "}"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/AlgorithmValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/AlgorithmValidatorTest.java deleted file mode 100644 index 3e474e73..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/AlgorithmValidatorTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateAlgorithm; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.apache.commons.beanutils.BeanUtils; -import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.validation.ConstraintValidatorContext; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({BeanUtils.class, IdentityExtensionsDataHolder.class}) -public class AlgorithmValidatorTest extends PowerMockTestCase { - - private AlgorithmValidator validator; - - @Mock - private ValidateAlgorithm validateAlgorithm; - - @BeforeMethod - public void setUp() { - validator = new AlgorithmValidator(); - - when(validateAlgorithm.idTokenAlg()).thenReturn("idTokenAlg"); - when(validateAlgorithm.reqObjAlg()).thenReturn("reqObjAlg"); - when(validateAlgorithm.tokenAuthAlg()).thenReturn("tokenAuthAlg"); - - validator.initialize(validateAlgorithm); - } - - @Test - public void testIsValid_ReturnsTrue_WhenAlgorithmsAreAllowed() throws Exception { - Object requestObject = mock(Object.class); - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - - PowerMockito.mockStatic(BeanUtils.class); - PowerMockito.when(BeanUtils.getProperty(requestObject, "idTokenAlg")).thenReturn("RS256"); - PowerMockito.when(BeanUtils.getProperty(requestObject, "reqObjAlg")).thenReturn("RS256"); - PowerMockito.when(BeanUtils.getProperty(requestObject, "tokenAuthAlg")).thenReturn("RS256"); - - List allowedAlgorithms = Arrays.asList("RS256", "HS256"); - - PowerMockito.mockStatic(IdentityExtensionsDataHolder.class); - IdentityExtensionsDataHolder dataHolder = PowerMockito.mock(IdentityExtensionsDataHolder.class); - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.SIGNATURE_ALGORITHMS, allowedAlgorithms); - when(dataHolder.getConfigurationMap()).thenReturn(configMap); - PowerMockito.when(IdentityExtensionsDataHolder.getInstance()).thenReturn(dataHolder); - - boolean result = validator.isValid(requestObject, context); - Assert.assertTrue(result); - } - - @Test - public void testIsValid_ReturnsFalse_WhenAlgorithmsAreNotAllowed() throws Exception { - Object requestObject = mock(Object.class); - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - - PowerMockito.mockStatic(BeanUtils.class); - PowerMockito.when(BeanUtils.getProperty(requestObject, "idTokenAlg")).thenReturn("RS512"); - PowerMockito.when(BeanUtils.getProperty(requestObject, "reqObjAlg")).thenReturn("RS512"); - PowerMockito.when(BeanUtils.getProperty(requestObject, "tokenAuthAlg")).thenReturn("RS512"); - - List allowedAlgorithms = Arrays.asList("RS256", "HS256"); - - PowerMockito.mockStatic(IdentityExtensionsDataHolder.class); - IdentityExtensionsDataHolder dataHolder = PowerMockito.mock(IdentityExtensionsDataHolder.class); - Map configMap = new HashMap<>(); - configMap.put(OpenBankingConstants.SIGNATURE_ALGORITHMS, allowedAlgorithms); - when(dataHolder.getConfigurationMap()).thenReturn(configMap); - PowerMockito.when(IdentityExtensionsDataHolder.getInstance()).thenReturn(dataHolder); - - boolean result = validator.isValid(requestObject, context); - Assert.assertFalse(result); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/IssuerValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/IssuerValidatorTest.java deleted file mode 100644 index a5f30382..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/IssuerValidatorTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateIssuer; -import org.apache.commons.beanutils.BeanUtils; -import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import javax.validation.ConstraintValidatorContext; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({JWTUtils.class, BeanUtils.class}) -public class IssuerValidatorTest extends PowerMockTestCase { - - private IssuerValidator validator; - - @Mock - private ValidateIssuer validateIssuer; - - @BeforeMethod - public void setUp() { - validator = new IssuerValidator(); - - when(validateIssuer.issuerProperty()).thenReturn("issuer"); - when(validateIssuer.ssa()).thenReturn("ssa"); - - validator.initialize(validateIssuer); - } - - @Test - public void testIsValid_ReturnsTrue_WhenIssuerOrSoftwareStatementIsNull() throws Exception { - Object registrationRequest = mock(Object.class); - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - - PowerMockito.mockStatic(BeanUtils.class); - PowerMockito.when(BeanUtils.getProperty(registrationRequest, "issuer")).thenReturn(null); - PowerMockito.when(BeanUtils.getProperty(registrationRequest, "ssa")).thenReturn(null); - - boolean result = validator.isValid(registrationRequest, context); - Assert.assertTrue(result); - } - - @Test - public void testIsValid_ReturnsFalse_OnException() throws Exception { - Object registrationRequest = mock(Object.class); - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - - PowerMockito.mockStatic(BeanUtils.class); - PowerMockito.when(BeanUtils.getProperty(registrationRequest, "issuer")).thenThrow(new NoSuchMethodException()); - PowerMockito.when(BeanUtils.getProperty(registrationRequest, "ssa")).thenReturn("dummy-ssa"); - - boolean result = validator.isValid(registrationRequest, context); - Assert.assertFalse(result); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RequiredParamsValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RequiredParamsValidatorTest.java deleted file mode 100644 index 1c286cbf..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dcr/validation/RequiredParamsValidatorTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.validation; - -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.validation.annotation.ValidateRequiredParams; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl; -import org.hibernate.validator.internal.engine.path.PathImpl; -import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.validation.ConstraintValidatorContext; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityExtensionsDataHolder.class}) -public class RequiredParamsValidatorTest extends PowerMockTestCase { - - private RequiredParamsValidator validator; - - @Mock - private ValidateRequiredParams validateRequiredParams; - - private IdentityExtensionsDataHolder identityExtensionsDataHolderMock; - - @BeforeMethod - public void setUp() { - validator = new RequiredParamsValidator(); - validator.initialize(validateRequiredParams); - - PowerMockito.mockStatic(IdentityExtensionsDataHolder.class); - identityExtensionsDataHolderMock = PowerMockito.mock(IdentityExtensionsDataHolder.class); - PowerMockito.when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolderMock); - - // Mock the DCR registration config map with some test data - Map> configMap = new HashMap<>(); - Map paramConfig = new HashMap<>(); - paramConfig.put(DCRCommonConstants.DCR_REGISTRATION_PARAM_REQUIRED, "true"); - configMap.put("tokenEndPointAuthentication", paramConfig); - - Map scopeAllowedValuesConfig = new HashMap<>(); - scopeAllowedValuesConfig.put(DCRCommonConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUES, Arrays.asList( - "scope1", "scope2")); - configMap.put("scope", scopeAllowedValuesConfig); - - - Map appTypeAllowedValuesConfig = new HashMap<>(); - appTypeAllowedValuesConfig.put(DCRCommonConstants.DCR_REGISTRATION_PARAM_ALLOWED_VALUES, Arrays.asList( - "web", "mobile")); - configMap.put("applicationType", appTypeAllowedValuesConfig); - - PowerMockito.when(identityExtensionsDataHolderMock.getDcrRegistrationConfigMap()).thenReturn(configMap); - } - - @Test - public void testIsValid_ReturnsTrue_WhenAllRequestObjectIsEmpty() { - PowerMockito.when(identityExtensionsDataHolderMock.getDcrRegistrationConfigMap()).thenReturn(new HashMap<>()); - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - doReturn(getConstraintViolationBuilder()).when(context).buildConstraintViolationWithTemplate(anyString()); - RegistrationRequest request = new RegistrationRequest(); - boolean result = validator.isValid(request, context); - Assert.assertTrue(result); - } - - @Test - public void testIsValid_ReturnsTrue_WhenRequiredParametersArePresent() { - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - doReturn(getConstraintViolationBuilder()).when(context).buildConstraintViolationWithTemplate(anyString()); - RegistrationRequest request = getSampleRegistrationRequestWithRequiredParams(); - boolean result = validator.isValid(request, context); - Assert.assertTrue(result); - } - - @Test - public void testIsValid_ReturnsFalse_WhenRequiredParameterIsBlank() { - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - doReturn(getConstraintViolationBuilder()).when(context).buildConstraintViolationWithTemplate(anyString()); - RegistrationRequest request = getSampleRegistrationRequestWithBlankRequiredParams(); - boolean result = validator.isValid(request, context); - Assert.assertFalse(result); - } - - @Test - public void testIsValid_ReturnsFalse_WhenScopeNotAllowed() { - ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); - doReturn(getConstraintViolationBuilder()).when(context).buildConstraintViolationWithTemplate(anyString()); - RegistrationRequest request = getSampleRegistrationRequestWithScope(); - boolean result = validator.isValid(request, context); - Assert.assertFalse(result); - } - - private ConstraintValidatorContext.ConstraintViolationBuilder getConstraintViolationBuilder() { - - PathImpl propertyPath = PathImpl.createPathFromString("example.path"); - ConstraintValidatorContextImpl context = new ConstraintValidatorContextImpl( - null, - null, - propertyPath, - null, - null - ); - return context.buildConstraintViolationWithTemplate("message"); - } - - private RegistrationRequest getSampleRegistrationRequestWithRequiredParams() { - - RegistrationRequest registrationRequest = new RegistrationRequest(); - registrationRequest.setApplicationType("web"); - registrationRequest.setTokenEndPointAuthentication("auth_method"); - registrationRequest.setScope("scope1 scope2"); - return registrationRequest; - } - - private RegistrationRequest getSampleRegistrationRequestWithBlankRequiredParams() { - - RegistrationRequest registrationRequest = new RegistrationRequest(); - registrationRequest.setApplicationType("web"); - registrationRequest.setTokenEndPointAuthentication(""); - registrationRequest.setScope("scope1 scope2"); - return registrationRequest; - } - - private RegistrationRequest getSampleRegistrationRequestWithScope() { - - RegistrationRequest registrationRequest = new RegistrationRequest(); - registrationRequest.setTokenEndPointAuthentication("auth_method"); - registrationRequest.setScope("scope1 scope3"); - return registrationRequest; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dispute/resolution/DisputeResolutionFilterTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dispute/resolution/DisputeResolutionFilterTest.java deleted file mode 100644 index fec44953..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/dispute/resolution/DisputeResolutionFilterTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dispute.resolution; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import com.wso2.openbanking.accelerator.data.publisher.common.util.OBDataPublisherUtil; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.api.APIManagementException; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.FilterChain; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test for dispute resolution filter. - */ -@PrepareForTest({OpenBankingConfigParser.class, OBDataPublisherUtil.class, APIManagementException.class, - ServiceProviderUtils.class}) -@PowerMockIgnore("jdk.internal.reflect.*") -public class DisputeResolutionFilterTest extends PowerMockTestCase { - MockHttpServletRequest request; - MockHttpServletResponse response; - FilterChain filterChain; - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - Map sampleRequestParams = new HashMap<>(); - - Map sampleHeaderMap = new HashMap<>(); - - @BeforeMethod - public void beforeMethod() { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - openBankingConfigParser = PowerMockito.mock(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - } - - public DisputeResolutionFilterTest() { - sampleRequestParams.put("jsonRequest", ""); - sampleHeaderMap.put("Accept", "application/json"); - sampleHeaderMap.put("Postman-Token", "5c04e832-1a05-4d9a-974b-9e01d4c978f0"); - sampleHeaderMap.put("Host", "api.example.com"); - sampleHeaderMap.put("Accept-Encoding", "gzip, deflate, br"); - sampleHeaderMap.put("Connection", "keep-alive"); - sampleHeaderMap.put("Content-Type", "application/json"); - sampleHeaderMap.put("X-WSO2-Mutual-Auth-Cert", "MIIDczCCAlugAwIBAgIINeDHEkE4dGowDQYJKoZIhvcNAQELBQ" + - "AwJDEiMCAGA1UEAxMZcG9ydGFsLXByb2R1Y3Rpb24tc2lnbmVy"); - } - - @Test - public void capturingRequestResponseDataTest() throws Exception { - - when(openBankingConfigParser.isDisputeResolutionEnabled()).thenReturn(true); - when(openBankingConfigParser.isNonErrorDisputeDataPublishingEnabled()).thenReturn(true); - - DisputeResolutionFilter filter = Mockito.spy(DisputeResolutionFilter.class); - - request.setMethod("GET"); - request.setRequestURI("/register"); - request.setCharacterEncoding("UTF-8"); - request.setParameters(sampleRequestParams); - response.setStatus(200); - response.setCharacterEncoding("UTF-8"); - - Enumeration enumeration = Collections.enumeration(sampleHeaderMap.keySet()); - - PowerMockito.mockStatic(OBDataPublisherUtil.class); - PowerMockito.doNothing().when(OBDataPublisherUtil.class, "publishData", Mockito.anyString(), - Mockito.anyString(), Mockito.anyObject()); - - filter.doFilter(request, response, filterChain); - verify(filter, times(1)); - - } -} - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/idtoken/OBIDTokenBuilderTests.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/idtoken/OBIDTokenBuilderTests.java deleted file mode 100644 index 9347bf22..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/idtoken/OBIDTokenBuilderTests.java +++ /dev/null @@ -1,259 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.idtoken; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; -import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; - -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test for Open banking token builder. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OAuthServerConfiguration.class, IdentityCommonUtil.class}) -public class OBIDTokenBuilderTests extends PowerMockTestCase { - - private OBIDTokenBuilder obidTokenBuilder; - private OAuthServerConfiguration oAuthServerConfigurationMock; - private OBIDTokenBuilderForSectorId obidTokenBuilderForSecId; - OBIDTokenBuilderForCallBackUri obidTokenBuilderForCallBackUri; - private AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - private static final String USER = "admin@wso2.com"; - private static final String USER2 = "aaa@gold.com"; - private static final String CLIENT_ID = "DummyClientId"; - private static final String TENANT_DOMAIN = "DummyTenantDomain"; - private static final String SCOPES = "accounts basic:read openid"; - - @BeforeClass - public void setup() throws Exception { - - oAuthServerConfigurationMock = mock(OAuthServerConfiguration.class); - mockStatic(OAuthServerConfiguration.class); - when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfigurationMock); - when(oAuthServerConfigurationMock.getIdTokenSignatureAlgorithm()).thenReturn("SHA256withRSA"); - - authenticatedUser.setUserName("aaa@gold.com"); - authenticatedUser.setTenantDomain("carbon.super"); - authenticatedUser.setUserStoreDomain("PRIMARY"); - authenticatedUser.setFederatedIdPName("LOCAL"); - authenticatedUser.setFederatedUser(false); - authenticatedUser.setAuthenticatedSubjectIdentifier("aaa@gold.com@carbon.super"); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.ENABLE_SUBJECT_AS_PPID, true); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - obidTokenBuilder = new OBIDTokenBuilder(); - obidTokenBuilderForSecId = new OBIDTokenBuilderForSectorId(); - obidTokenBuilderForCallBackUri = new OBIDTokenBuilderForCallBackUri(); - } - - @Test - public void getSubjectClaimAuthFlowFromSectorIdentifierSuccess() throws Exception { - - OAuthAuthzReqMessageContext oAuthAuthzReqMessageContextMock = mock(OAuthAuthzReqMessageContext.class); - OAuth2AuthorizeReqDTO oAuth2AuthorizeReqDTOMock = mock(OAuth2AuthorizeReqDTO.class); - Mockito.doReturn(oAuth2AuthorizeReqDTOMock).when(oAuthAuthzReqMessageContextMock).getAuthorizationReqDTO(); - Mockito.doReturn("https://www.google.com/redirects/redirect1").when(oAuth2AuthorizeReqDTOMock) - .getCallbackUrl(); - - AuthenticatedUser authenticatedUserMock = mock(AuthenticatedUser.class); - Mockito.doReturn(authenticatedUserMock).when(oAuth2AuthorizeReqDTOMock).getUser(); - Mockito.doReturn(USER).when(authenticatedUserMock) - .getUsernameAsSubjectIdentifier(Mockito.anyBoolean(), Mockito.anyBoolean()); - - OAuth2AuthorizeRespDTO oAuth2AuthorizeRespDTOMock = mock(OAuth2AuthorizeRespDTO.class); - - mockStatic(IdentityCommonUtil.class); - when(IdentityCommonUtil.getRegulatoryFromSPMetaData(Mockito.anyString())).thenReturn(true); - - String subject = obidTokenBuilderForSecId.getSubjectClaim(oAuthAuthzReqMessageContextMock, - oAuth2AuthorizeRespDTOMock, CLIENT_ID, TENANT_DOMAIN, authenticatedUserMock); - Assert.assertNotNull(subject); - } - - @Test - public void getSubjectClaimTokenFlowFromSectorIdentifierSuccess() throws Exception { - - OAuthTokenReqMessageContext oAuthTokenReqMessageContextMock = mock(OAuthTokenReqMessageContext.class); - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTOMock = mock(OAuth2AccessTokenRespDTO.class); - Mockito.doReturn("https://www.google.com/redirects/redirect1").when(oAuth2AccessTokenRespDTOMock) - .getCallbackURI(); - - Mockito.doReturn(SCOPES).when(oAuth2AccessTokenRespDTOMock) - .getAuthorizedScopes(); - - AuthenticatedUser authenticatedUserMock = mock(AuthenticatedUser.class); - Mockito.doReturn(authenticatedUserMock).when(oAuthTokenReqMessageContextMock).getAuthorizedUser(); - Mockito.doReturn(USER).when(authenticatedUserMock) - .getUsernameAsSubjectIdentifier(Mockito.anyBoolean(), Mockito.anyBoolean()); - - mockStatic(IdentityCommonUtil.class); - when(IdentityCommonUtil.getRegulatoryFromSPMetaData(Mockito.anyString())).thenReturn(true); - - String subject = obidTokenBuilderForSecId.getSubjectClaim(oAuthTokenReqMessageContextMock, - oAuth2AccessTokenRespDTOMock, CLIENT_ID, TENANT_DOMAIN, authenticatedUserMock); - Assert.assertNotNull(subject); - } - - @Test - public void getSubjectClaimAuthFlowFromCallBackUriSuccess() throws Exception { - - OAuthAuthzReqMessageContext oAuthAuthzReqMessageContextMock = mock(OAuthAuthzReqMessageContext.class); - OAuth2AuthorizeReqDTO oAuth2AuthorizeReqDTOMock = mock(OAuth2AuthorizeReqDTO.class); - Mockito.doReturn(oAuth2AuthorizeReqDTOMock).when(oAuthAuthzReqMessageContextMock).getAuthorizationReqDTO(); - Mockito.doReturn("https://www.google.com/redirects/redirect1").when(oAuth2AuthorizeReqDTOMock) - .getCallbackUrl(); - - AuthenticatedUser authenticatedUserMock = mock(AuthenticatedUser.class); - Mockito.doReturn(authenticatedUserMock).when(oAuth2AuthorizeReqDTOMock).getUser(); - Mockito.doReturn(USER).when(authenticatedUserMock) - .getUsernameAsSubjectIdentifier(Mockito.anyBoolean(), Mockito.anyBoolean()); - - OAuth2AuthorizeRespDTO oAuth2AuthorizeRespDTOMock = mock(OAuth2AuthorizeRespDTO.class); - - mockStatic(IdentityCommonUtil.class); - when(IdentityCommonUtil.getRegulatoryFromSPMetaData(Mockito.anyString())).thenReturn(true); - - String subject = obidTokenBuilderForCallBackUri.getSubjectClaim(oAuthAuthzReqMessageContextMock, - oAuth2AuthorizeRespDTOMock, CLIENT_ID, TENANT_DOMAIN, authenticatedUserMock); - Assert.assertNotNull(subject); - } - - @Test - public void getSubjectClaimTokenFlowFromCallBackUriSuccess() throws Exception { - - OAuthTokenReqMessageContext oAuthTokenReqMessageContextMock = mock(OAuthTokenReqMessageContext.class); - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTOMock = mock(OAuth2AccessTokenRespDTO.class); - Mockito.doReturn("regexp=(https://www.google.com/redirects/redirect1|" + - "https://www.google.com/redirects/redirect2)").when(oAuth2AccessTokenRespDTOMock) - .getCallbackURI(); - - Mockito.doReturn(SCOPES).when(oAuth2AccessTokenRespDTOMock) - .getAuthorizedScopes(); - - AuthenticatedUser authenticatedUserMock = mock(AuthenticatedUser.class); - Mockito.doReturn(authenticatedUserMock).when(oAuthTokenReqMessageContextMock).getAuthorizedUser(); - Mockito.doReturn(USER).when(authenticatedUserMock) - .getUsernameAsSubjectIdentifier(Mockito.anyBoolean(), Mockito.anyBoolean()); - - mockStatic(IdentityCommonUtil.class); - when(IdentityCommonUtil.getRegulatoryFromSPMetaData(Mockito.anyString())).thenReturn(true); - - String subject = obidTokenBuilderForCallBackUri.getSubjectClaim(oAuthTokenReqMessageContextMock, - oAuth2AccessTokenRespDTOMock, CLIENT_ID, TENANT_DOMAIN, authenticatedUserMock); - Assert.assertNotNull(subject); - } - - @Test - public void getNonPPIDSubjectClaimWithoutTenantAndUserDomainSuccess() throws Exception { - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.REMOVE_USER_STORE_DOMAIN_FROM_SUBJECT, true); - configMap.put(IdentityCommonConstants.REMOVE_TENANT_DOMAIN_FROM_SUBJECT, true); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - OBIDTokenBuilderForCallBackUri obidTokenBuilderForCallBackUri = new OBIDTokenBuilderForCallBackUri(); - - OAuthAuthzReqMessageContext oAuthAuthzReqMessageContextMock = mock(OAuthAuthzReqMessageContext.class); - OAuth2AuthorizeReqDTO oAuth2AuthorizeReqDTOMock = mock(OAuth2AuthorizeReqDTO.class); - Mockito.doReturn(oAuth2AuthorizeReqDTOMock).when(oAuthAuthzReqMessageContextMock).getAuthorizationReqDTO(); - Mockito.doReturn("https://www.google.com/redirects/redirect1").when(oAuth2AuthorizeReqDTOMock) - .getCallbackUrl(); - - oAuth2AuthorizeReqDTOMock.setUser(authenticatedUser); - Mockito.doReturn(authenticatedUser).when(oAuth2AuthorizeReqDTOMock).getUser(); - - OAuth2AuthorizeRespDTO oAuth2AuthorizeRespDTOMock = mock(OAuth2AuthorizeRespDTO.class); - - mockStatic(IdentityCommonUtil.class); - when(IdentityCommonUtil.getRegulatoryFromSPMetaData(Mockito.anyString())).thenReturn(true); - - String subject = obidTokenBuilderForCallBackUri.getSubjectClaim(oAuthAuthzReqMessageContextMock, - oAuth2AuthorizeRespDTOMock, CLIENT_ID, TENANT_DOMAIN, authenticatedUser); - Assert.assertNotNull(subject); - Assert.assertEquals(subject, USER2); - - OAuthTokenReqMessageContext oAuthTokenReqMessageContextMock = mock(OAuthTokenReqMessageContext.class); - OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTOMock = mock(OAuth2AccessTokenRespDTO.class); - Mockito.doReturn("https://www.google.com/redirects/redirect1").when(oAuth2AccessTokenRespDTOMock) - .getCallbackURI(); - - Mockito.doReturn(SCOPES).when(oAuth2AccessTokenRespDTOMock) - .getAuthorizedScopes(); - - oAuthTokenReqMessageContextMock.setAuthorizedUser(authenticatedUser); - Mockito.doReturn(authenticatedUser).when(oAuthTokenReqMessageContextMock).getAuthorizedUser(); - - mockStatic(IdentityCommonUtil.class); - when(IdentityCommonUtil.getRegulatoryFromSPMetaData(Mockito.anyString())).thenReturn(true); - - String subjectTokenFlow = obidTokenBuilderForCallBackUri.getSubjectClaim(oAuthTokenReqMessageContextMock, - oAuth2AccessTokenRespDTOMock, CLIENT_ID, TENANT_DOMAIN, authenticatedUser); - Assert.assertNotNull(subjectTokenFlow); - Assert.assertEquals(subjectTokenFlow, USER2); - } - -} - -class OBIDTokenBuilderForSectorId extends OBIDTokenBuilder { - - public OBIDTokenBuilderForSectorId() throws IdentityOAuth2Exception { - } - - @Override - protected String getSectorIdentifierUri(String clientId) throws OpenBankingException { - - return "https://wso2.com/"; - } -} - -class OBIDTokenBuilderForCallBackUri extends OBIDTokenBuilder { - - public OBIDTokenBuilderForCallBackUri() throws IdentityOAuth2Exception { - } - - @Override - protected String getSectorIdentifierUri(String clientId) throws OpenBankingException { - - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/listener/TokenRevocationListenerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/listener/TokenRevocationListenerTest.java deleted file mode 100644 index f744fbbc..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/listener/TokenRevocationListenerTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.listener; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import org.junit.Assert; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Map; -/** - * Test class for TokenRevocationListener. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class}) -public class TokenRevocationListenerTest extends PowerMockTestCase { - - OpenBankingConfigParser openBankingConfigParserMock; - private Map configMap = new HashMap<>(); - - @BeforeClass - public void init() { - mockOpenBankingConfigParser(); - configMap.put("Identity.ConsentIDClaimName", "consent_id"); - } - - @Test - public void testGetConsentIdFromScopes() { - String[] scopes = {"dummy-scope1", "dummy-scope2", "consent_idConsentId", "dummy-scope3"}; - TokenRevocationListener tokenRevocationListener = new TokenRevocationListener(); - String consentId = tokenRevocationListener.getConsentIdFromScopes(scopes); - Assert.assertEquals("ConsentId", consentId); - } - - private void mockOpenBankingConfigParser() { - openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.when(openBankingConfigParserMock.getConfiguration()) - .thenReturn(configMap); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/PushAuthRequestValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/PushAuthRequestValidatorTest.java deleted file mode 100644 index b21e6c1f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/PushAuthRequestValidatorTest.java +++ /dev/null @@ -1,421 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.constants.PushAuthRequestConstants; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.exception.PushAuthRequestValidatorException; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.model.PushAuthErrorResponse; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util.test.jwt.builder.TestJwtBuilder; -import net.minidev.json.JSONObject; -import org.junit.Assert; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; -import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.security.KeyStore; -import java.security.interfaces.RSAPrivateKey; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test for push authorization request validator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityExtensionsDataHolder.class, OAuth2Util.class, OAuthServerConfiguration.class, - IdentityUtil.class, ServiceProviderUtils.class}) -public class PushAuthRequestValidatorTest extends PowerMockTestCase { - - private Map> parameterMap; - private Map configMap; - private PushAuthRequestValidator pushAuthRequestValidator; - private HttpServletRequest httpServletRequestMock; - private ServiceProviderProperty[] spProperties; - private ServiceProvider serviceProviderMock; - - @BeforeClass - public void setup() throws Exception { - - parameterMap = new HashMap<>(); - configMap = new HashMap<>(); - parameterMap.put("request", Arrays.asList(TestJwtBuilder.getValidSignedJWT())); - configMap.put("SignatureValidation.AllowedAlgorithms.Algorithm", - new ArrayList<>(Arrays.asList("PS256 ES256".split(" ")))); - httpServletRequestMock = mock(HttpServletRequest.class); - pushAuthRequestValidator = new PushAuthRequestValidator(); - - serviceProviderMock = new ServiceProvider(); - - ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty(); - serviceProviderProperty.setName("scope"); - serviceProviderProperty.setValue("accounts payments"); - spProperties = new ServiceProviderProperty[1]; - spProperties[0] = serviceProviderProperty; - serviceProviderMock.setSpProperties(spProperties); - } - - @BeforeMethod - public void initMethods() throws OpenBankingException, IdentityApplicationManagementException { - - IdentityExtensionsDataHolder identityExtensionsDataHolderMock = mock(IdentityExtensionsDataHolder.class); - ApplicationManagementService applicationManagementServiceMock = mock(ApplicationManagementService.class); - - mockStatic(IdentityExtensionsDataHolder.class); - mockStatic(ServiceProviderUtils.class); - when(IdentityExtensionsDataHolder.getInstance()).thenReturn(identityExtensionsDataHolderMock); - when(identityExtensionsDataHolderMock.getConfigurationMap()).thenReturn(configMap); - when(identityExtensionsDataHolderMock.getApplicationManagementService()) - .thenReturn(applicationManagementServiceMock); - when(ServiceProviderUtils.getSpTenantDomain(Mockito.anyString())).thenReturn("dummyTenantDomain"); - when(applicationManagementServiceMock.getServiceProviderByClientId(Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())).thenReturn(serviceProviderMock); - - OAuthServerConfiguration oAuthServerConfigurationMock = mock(OAuthServerConfiguration.class); - mockStatic(OAuthServerConfiguration.class); - when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfigurationMock); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class) - public void validateRepeatedParametersInRequest() throws Exception { - - parameterMap.put("client_assertion", Arrays.asList("firstParam,secondRepeatedParam".split(","))); - pushAuthRequestValidator.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateRepeatedParametersInRequest") - public void validateRequestUriParamInRequest() throws Exception { - - // remove previous invalid parameters - parameterMap.remove("client_assertion"); - // add new parameters to be tested - parameterMap.put("request_uri", Arrays.asList("dummyValue")); - pushAuthRequestValidator.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateRequestUriParamInRequest") - public void validateFormBodyParamsInRequest() throws Exception { - - // remove previous invalid parameters - parameterMap.remove("request_uri"); - // add new parameters to be tested - parameterMap.put("scope", Arrays.asList("dummyScope")); - pushAuthRequestValidator.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateRequestUriParamInRequest") - public void validateRequestObject() throws Exception { - - // remove previous invalid parameters - parameterMap.remove("scope"); - // add new parameters to be tested - parameterMap.put("request", Arrays.asList("invalidReqObj")); - pushAuthRequestValidator.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateRequestObject") - public void validateClientIdInRequest() throws Exception { - - // add parameters to be tested - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getValidSignedJWT())); - PushAuthRequestValidatorInvalidClientMock pushAuthRequestValidatorInvalidClientMock = - new PushAuthRequestValidatorInvalidClientMock(); - pushAuthRequestValidatorInvalidClientMock.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateClientIdInRequest") - public void validateSignatureAlgInRequestObject() throws Exception { - - // add parameters to be tested - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithUnsupportedAlgorithm())); - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateSignatureAlgInRequestObject") - public void validateNonceInRequestObject() throws Exception { - - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithUnsupportedNonce())); - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateNonceInRequestObject") - public void validateScopeParameter() throws Exception { - - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getValidSignedJWT())); - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateNonceInRequestObject") - public void validateUnsupportedClaimsInSignedJWT() throws Exception { - - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithUnsupportedClaims())); - - ServiceProviderProperty[] serviceProviderProperties = serviceProviderMock.getSpProperties(); - serviceProviderProperties[0].setValue("bank:accounts.basic:read bank:accounts.detail:read " + - "bank:transactions:read bank:payees:read bank:regular_payments:read common:customer.basic:read " + - "common:customer.detail:read cdr:registration openid"); - - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(dependsOnMethods = "validateUnsupportedClaimsInSignedJWT") - public void successfulParameterValidationFlowForSignedJWT() throws Exception { - - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getValidSignedJWT())); - - ServiceProviderProperty[] serviceProviderProperties = serviceProviderMock.getSpProperties(); - serviceProviderProperties[0].setValue("bank:accounts.basic:read bank:accounts.detail:read " + - "bank:transactions:read bank:payees:read bank:regular_payments:read common:customer.basic:read " + - "common:customer.detail:read cdr:registration openid"); - - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - Map result = pushAuthRequestValidatorMockClass - .validateParams(httpServletRequestMock, parameterMap); - - Assert.assertNotNull(result); - } - - @Test(priority = 1) - public void testErrorResponseCreation() { - - PushAuthErrorResponse result = pushAuthRequestValidator.createErrorResponse(400, - PushAuthRequestConstants.INVALID_REQUEST, "Bad Request"); - - Assert.assertEquals("Bad Request", result.getPayload().get("error_description").toString()); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateScopeParameter") - public void validateMissingExpClaimInSignedJWT() throws Exception { - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithoutExpClaim())); - - ServiceProviderProperty[] serviceProviderProperties = serviceProviderMock.getSpProperties(); - serviceProviderProperties[0].setValue("bank:accounts.basic:read bank:accounts.detail:read " + - "bank:transactions:read bank:payees:read bank:regular_payments:read common:customer.basic:read " + - "common:customer.detail:read cdr:registration openid"); - - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateMissingExpClaimInSignedJWT") - public void validateExpClaimOver60MinInSignedJWT() throws Exception { - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithExpClaimOver60Min())); - - ServiceProviderProperty[] serviceProviderProperties = serviceProviderMock.getSpProperties(); - serviceProviderProperties[0].setValue("bank:accounts.basic:read bank:accounts.detail:read " + - "bank:transactions:read bank:payees:read bank:regular_payments:read common:customer.basic:read " + - "common:customer.detail:read cdr:registration openid"); - - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateExpClaimOver60MinInSignedJWT") - public void validateMissingNbfClaimInSignedJWT() throws Exception { - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithoutNbfClaim())); - - ServiceProviderProperty[] serviceProviderProperties = serviceProviderMock.getSpProperties(); - serviceProviderProperties[0].setValue("bank:accounts.basic:read bank:accounts.detail:read " + - "bank:transactions:read bank:payees:read bank:regular_payments:read common:customer.basic:read " + - "common:customer.detail:read cdr:registration openid"); - - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateMissingNbfClaimInSignedJWT") - public void validateNbfClaimOver60MinInSignedJWT() throws Exception { - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithNbfClaimOver60Min())); - - ServiceProviderProperty[] serviceProviderProperties = serviceProviderMock.getSpProperties(); - serviceProviderProperties[0].setValue("bank:accounts.basic:read bank:accounts.detail:read " + - "bank:transactions:read bank:payees:read bank:regular_payments:read common:customer.basic:read " + - "common:customer.detail:read cdr:registration openid"); - - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateMissingNbfClaimInSignedJWT") - public void validateMissingCodeChallengeInSignedJWT() throws Exception { - - // add parameters to be tested - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithoutCodeChallenge())); - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateMissingCodeChallengeInSignedJWT") - public void validateMissingCodeChallengeMethodInSignedJWT() throws Exception { - - // add parameters to be tested - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithoutCodeChallengeMethod())); - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(expectedExceptions = PushAuthRequestValidatorException.class, - dependsOnMethods = "validateMissingCodeChallengeMethodInSignedJWT") - public void validateMissingResponseTypeInSignedJWT() throws Exception { - - // add parameters to be tested - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getInvalidJWTWithoutResponseType())); - PushAuthRequestValidatorMockClass pushAuthRequestValidatorMockClass = new PushAuthRequestValidatorMockClass(); - - pushAuthRequestValidatorMockClass.validateParams(httpServletRequestMock, parameterMap); - } - - @Test(priority = 2, expectedExceptions = PushAuthRequestValidatorException.class) - public void testDecryptEncryptedReqObjFailure() throws Exception { - - parameterMap.put("request", - Arrays.asList(TestJwtBuilder.getValidEncryptedJWT())); - - OAuthServerConfiguration oAuthServerConfigurationMock = mock(OAuthServerConfiguration.class); - mockStatic(OAuthServerConfiguration.class); - when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfigurationMock); - - mockStatic(OAuth2Util.class); - OAuthAppDO oAuthAppDOMock = mock(OAuthAppDO.class); - when(OAuth2Util.getAppInformationByClientId(Mockito.anyString())).thenReturn(oAuthAppDOMock); - when(OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDOMock)).thenReturn("dummyTenantDomain"); - - String path = "src/test/resources"; - File file = new File(path); - String absolutePathForTestResources = file.getAbsolutePath(); - String absolutePathForKeyStore = absolutePathForTestResources + "/wso2carbon.jks"; - String[] pathParts = absolutePathForKeyStore.split("/"); - String platformAbsolutePathForKeyStore = String.join(File.separator, pathParts); - - InputStream keystoreFile = new FileInputStream(platformAbsolutePathForKeyStore); - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(keystoreFile, "wso2carbon".toCharArray()); - - String alias = "wso2carbon"; - - // Get the private key. Password for the key store is 'wso2carbon'. - RSAPrivateKey privateKey = (RSAPrivateKey) keystore.getKey(alias, "wso2carbon".toCharArray()); - - when(OAuth2Util.getPrivateKey(Mockito.anyString(), Mockito.anyInt())).thenReturn(privateKey); - - pushAuthRequestValidator.validateParams(httpServletRequestMock, parameterMap); - } -} - -class PushAuthRequestValidatorMockClass extends PushAuthRequestValidator { - - @Override - protected OAuth2ClientValidationResponseDTO getClientValidationInfo(JSONObject requestBodyJson) { - - OAuth2ClientValidationResponseDTO oAuth2ClientValidationResponseDTO = new OAuth2ClientValidationResponseDTO(); - oAuth2ClientValidationResponseDTO.setValidClient(true); - return oAuth2ClientValidationResponseDTO; - } - - @Override - protected void validateSignature(String requestObjectString, JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - } - - @Override - protected void validateAudience(JSONObject requestBodyJson) - throws PushAuthRequestValidatorException { - - } -} - -class PushAuthRequestValidatorInvalidClientMock extends PushAuthRequestValidator { - - @Override - protected OAuth2ClientValidationResponseDTO getClientValidationInfo(JSONObject requestBodyJson) { - - OAuth2ClientValidationResponseDTO oAuth2ClientValidationResponseDTO = new OAuth2ClientValidationResponseDTO(); - oAuth2ClientValidationResponseDTO.setValidClient(false); - return oAuth2ClientValidationResponseDTO; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/test/jwt/builder/TestJwtBuilder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/test/jwt/builder/TestJwtBuilder.java deleted file mode 100644 index 76c5543c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/test/jwt/builder/TestJwtBuilder.java +++ /dev/null @@ -1,401 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util.test.jwt.builder; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JOSEObjectType; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWEEncrypter; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.JWEObject; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.crypto.RSAEncrypter; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util.test.jwt.builder.constants.TestJwtBuilderConstants; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.security.KeyStore; -import java.security.cert.Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.time.Instant; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * JWT Builder class to Automate the process of building a JWT for Testing purposes. - * - */ -public class TestJwtBuilder { - private static String issuer = "wHKH6jd5YRJtG_CXSLVfcStMfOAa"; - private static String responseType = "code id_token"; - private static String codeChallengeMethod = "S256"; - private static String nonce = "n-jBXhOmOKCB"; - private static String invalidNonce = null; - private static String clientId = "wHKH6jd5YRJtG_CXSLVfcStMfOAa"; - private static String audience = "https://localhost:9443/oauth2/token"; - private static String scope = "bank:accounts.basic:read bank:transactions:read " + - "common:customer.detail:read openid"; - private static String redirectUri = "https://www.google.com/redirects/redirect1"; - private static String state = "0pN0NBTHcv"; - private static String codeChallenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; - private static String kid = "W_TcnQVcHAy20q8zCMcdByrootw"; - private static String alias = "wso2carbon"; - private static String keyPassword = "wso2carbon"; - private static String acrValue = "urn:cds.au:cdr:2"; - private static String invalidParameter = "invalidParameter"; - private static boolean acrEssential = true; - private static int sharingDuration = 7776000; - private static int expiryPeriod = 3600; - private static int notBeforePeriod = 3600; - private static String keyStorePath = "src/test/resources"; - - private TestJwtBuilder() { - } - - /** - * This method is used to get a valid signed JWT with signature algorithm PS256. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getValidSignedJWT() throws Exception { - JWTClaimsSet claimsSet = getValidJWTClaimsSetBuilder().build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, claimsSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get a valid encrypted JWT with signature algorithm PS256, - * encryption algorithm RSA-OAEP-256 and encryption method A256GCM. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getValidEncryptedJWT() throws Exception { - JWTClaimsSet claimsSet = getValidJWTClaimsSetBuilder().build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256 , claimsSet); - return getEncryptedJWT(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128GCM, signedJWT).serialize(); - } - - /** - * This method is used to get a invalid JWT signed with unsupported signature algorithm. - * ex: RS256 - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithUnsupportedAlgorithm() throws Exception { - JWTClaimsSet claimsSet = getValidJWTClaimsSetBuilder().build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.RS256, claimsSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get a invalid JWT with invalid nonce value. - * ex: null - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithUnsupportedNonce() throws Exception { - - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder.claim(TestJwtBuilderConstants.NONCE, invalidNonce).build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT with unsupported claims value. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithUnsupportedClaims() throws Exception { - Map invalidClaimsMap = getValidClaimsMap(); - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .claim(TestJwtBuilderConstants.CLAIMS, invalidClaimsMap) - .claim(TestJwtBuilderConstants.REQUEST, invalidParameter) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT with exp claim over 60 minutes in the future. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithExpClaimOver60Min() throws Exception { - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .expirationTime(Date.from(Instant.now().plusSeconds(expiryPeriod + 1500))) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT without an exp claim. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithoutExpClaim() throws Exception { - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .expirationTime(null) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT without the code challenge. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithoutCodeChallenge() throws Exception { - - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .claim(TestJwtBuilderConstants.CODE_CHALLENGE, null) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT without the code challenge method. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithoutCodeChallengeMethod() throws Exception { - - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .claim(TestJwtBuilderConstants.CODE_CHALLENGE_METHOD, null) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT without the response type. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithoutResponseType() throws Exception { - - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .claim(TestJwtBuilderConstants.RESPONSE_TYPE, null) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT without nbf claim. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithoutNbfClaim() throws Exception { - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .notBeforeTime(null) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get an invalid JWT with nbf claim over 60 minutes in the past. - * - * @return String - * @throws Exception if an error occurs - */ - public static String getInvalidJWTWithNbfClaimOver60Min() throws Exception { - JWTClaimsSet.Builder builder = getValidJWTClaimsSetBuilder(); - JWTClaimsSet invalidClaimSet = builder - .notBeforeTime(Date.from(Instant.now().minusSeconds(notBeforePeriod + 1500))) - .build(); - SignedJWT signedJWT = getSignedJWT(JWSAlgorithm.PS256, invalidClaimSet); - return signedJWT.serialize(); - } - - /** - * This method is used to get a valid JWTClaimsSet.Builder Object. - * - * @return JWTClaimsSet.Builder - */ - private static JWTClaimsSet.Builder getValidJWTClaimsSetBuilder() { - Map claimsMap = getValidClaimsMap(); - - return new JWTClaimsSet.Builder() - .issuer(issuer) - .audience(audience) - .expirationTime(Date.from(Instant.now().plusSeconds(expiryPeriod))) - .notBeforeTime(Date.from(Instant.now())) - .claim(TestJwtBuilderConstants.RESPONSE_TYPE, responseType) - .claim(TestJwtBuilderConstants.CODE_CHALLENGE_METHOD, codeChallengeMethod) - .claim(TestJwtBuilderConstants.NONCE, nonce) - .claim(TestJwtBuilderConstants.CLIENT_ID, clientId) - .claim(TestJwtBuilderConstants.REDIRECT_URI, redirectUri) - .claim(TestJwtBuilderConstants.SCOPE, scope) - .claim(TestJwtBuilderConstants.STATE, state) - .claim(TestJwtBuilderConstants.CLAIMS, claimsMap) - .claim(TestJwtBuilderConstants.CODE_CHALLENGE, codeChallenge); - } - - - /** - * This method is used to get a valid claims value as a map object. - * - * @return Map - */ - private static Map getValidClaimsMap() { - // Create a new HashMap object to represent the claims - Map claimsMap = new HashMap<>(); - - // Add the sharing_duration key-value pair to the claims map - claimsMap.put(TestJwtBuilderConstants.SHARING_DURATION, sharingDuration); - - // Create a new HashMap object to represent the id_token object - Map idToken = new HashMap<>(); - - // Create a new HashMap object to represent the acr object - Map acr = new HashMap<>(); - acr.put(TestJwtBuilderConstants.ACR_VALUE, acrValue); - acr.put(TestJwtBuilderConstants.ACR_ESSENTIAL, acrEssential); - - // Add the acr map to the id_token map - idToken.put(TestJwtBuilderConstants.ACR, acr); - - // Add the id_token map to the claims map - claimsMap.put(TestJwtBuilderConstants.ID_TOKEN, idToken); - return claimsMap; - } - - /** - * This method is used to get a valid JWT signed with supported signature algorithm. - * ex: PS256 - * - * @param jwsAlgorithm JWSAlgorithm Value - * @param claimsSet JWTClaimsSet Object - * @return SignedJWT - * @throws Exception if an error occurs - */ - private static SignedJWT getSignedJWT(JWSAlgorithm jwsAlgorithm , JWTClaimsSet claimsSet) throws Exception { - RSAPrivateKey privateKey = getPrivateKeyFromKeyStore(); - JWSHeader header = new JWSHeader.Builder(jwsAlgorithm) - .keyID(kid) - .type(JOSEObjectType.JWT) - .build(); - SignedJWT signedJWT = new SignedJWT(header, claimsSet); - JWSSigner signer = new RSASSASigner(privateKey); - signer.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - signedJWT.sign(signer); - return signedJWT; - } - - /** - * This method is used to get a valid JWT encrypted with supported encryption algorithm and encryption method. - * ex: RSA-OAEP-256 - * - * @param jweAlgorithm JWEAlgorithm Value - * @param encryptionMethod EncryptionMethod Value - * @param signedJWT SignedJWT Object - * @return JWEObject - * @throws Exception if an error occurs - */ - private static JWEObject getEncryptedJWT(JWEAlgorithm jweAlgorithm , - EncryptionMethod encryptionMethod, SignedJWT signedJWT) throws Exception { - RSAPublicKey publicKey = getPublicKeyFromKeyStore(); - JWEHeader jweHeader = new JWEHeader.Builder(jweAlgorithm, encryptionMethod) - .build(); - JWEObject jweObject = new JWEObject(jweHeader, new Payload(signedJWT)); - JWEEncrypter encrypter = new RSAEncrypter(publicKey); - encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - jweObject.encrypt(encrypter); - return jweObject; - } - - /** - * This method is used to get the private key from the keystore. - * - * @return RSAPrivateKey - * @throws Exception if an error occurs - */ - private static RSAPrivateKey getPrivateKeyFromKeyStore() throws Exception { - KeyStore keyStore = getKeyStore(); - KeyStore.PasswordProtection keyProtection = new KeyStore.PasswordProtection(keyPassword.toCharArray()); - KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, keyProtection); - return (RSAPrivateKey) privateKeyEntry.getPrivateKey(); - } - - /** - * This method is used to get the public key from the keystore. - * - * @return RSAPublicKey - * @throws Exception if an error occurs - */ - private static RSAPublicKey getPublicKeyFromKeyStore() throws Exception { - KeyStore keyStore = getKeyStore(); - KeyStore.PasswordProtection keyProtection = new KeyStore.PasswordProtection(keyPassword.toCharArray()); - KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, keyProtection); - java.security.cert.Certificate[] certChain = privateKeyEntry.getCertificateChain(); - Certificate cert = certChain[0]; - return (RSAPublicKey) cert.getPublicKey(); - } - - /** - * This method is used to get the keystore. - * - * @return KeyStore - * @throws Exception if an error occurs - */ - private static KeyStore getKeyStore() throws Exception { - File file = new File(keyStorePath); - String absolutePathForTestResources = file.getAbsolutePath(); - String absolutePathForKeyStore = absolutePathForTestResources + "/wso2carbon.jks"; - String[] pathParts = absolutePathForKeyStore.split("/"); - String platformAbsolutePathForKeyStore = String.join(File.separator, pathParts); - InputStream keystoreFile = new FileInputStream(platformAbsolutePathForKeyStore); - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(keystoreFile, keyPassword.toCharArray()); - keystoreFile.close(); - return keyStore; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/test/jwt/builder/constants/TestJwtBuilderConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/test/jwt/builder/constants/TestJwtBuilderConstants.java deleted file mode 100644 index b50c268e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/push/auth/extension/request/validator/util/test/jwt/builder/constants/TestJwtBuilderConstants.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.util.test.jwt.builder.constants; - -/** - * Constant class for TestJwtBuilder Class. - */ -public class TestJwtBuilderConstants { - public static final String RESPONSE_TYPE = "response_type"; - public static final String NONCE = "nonce"; - public static final String SCOPE = "scope"; - public static final String CLIENT_ID = "client_id"; - public static final String REDIRECT_URI = "redirect_uri"; - public static final String STATE = "state"; - public static final String CLAIMS = "claims"; - public static final String CODE_CHALLENGE = "code_challenge"; - public static final String CODE_CHALLENGE_METHOD = "code_challenge_method"; - public static final String SHARING_DURATION = "sharing_duration"; - public static final String ACR = "acr"; - public static final String ACR_VALUE = "value"; - public static final String ACR_ESSENTIAL = "essential"; - public static final String ID_TOKEN = "id_token"; - public static final String REQUEST = "request"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/TokenFilterTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/TokenFilterTest.java deleted file mode 100644 index 07f54e59..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/TokenFilterTest.java +++ /dev/null @@ -1,348 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.token.util.TestUtil; -import com.wso2.openbanking.accelerator.identity.token.validators.ClientAuthenticatorValidator; -import com.wso2.openbanking.accelerator.identity.token.validators.MTLSEnforcementValidator; -import com.wso2.openbanking.accelerator.identity.token.validators.OBIdentityFilterValidator; -import com.wso2.openbanking.accelerator.identity.token.validators.SignatureAlgorithmEnforcementValidator; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.http.HttpStatus; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; - -import static org.testng.Assert.assertEquals; - -/** - * Test for token filter. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class}) -public class TokenFilterTest extends PowerMockTestCase { - - MockHttpServletRequest request; - MockHttpServletResponse response; - FilterChain filterChain; - - @BeforeMethod - public void beforeMethod() { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - } - - @Test(description = "Test the validators are omitted in non regulatory scenario") - public void nonRegulatoryTest() throws Exception { - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(false); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test client id extraction from header in non-regulatory app scenario") - public void nonRegulatoryAppWithAuthorizationHeaderTest() throws Exception { - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - String credentials = "client_id" + ':' + "client_secret"; - String authToken = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); - request.addHeader("Authorization", "Basic " + authToken); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("client_id")).thenReturn(false); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test the certificate in context/header is mandated") - public void noCertificateTest() throws IOException, OpenBankingException, ServletException { - - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()) - .thenReturn(IdentityCommonConstants.CERTIFICATE_HEADER); - filter.doFilter(request, response, filterChain); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Transport certificate not found in the request"); - } - - @Test(description = "Test the certificate in attribute is present if config is disabled") - public void certificateIsNotPresentInAttributeTest() throws IOException, OpenBankingException, ServletException { - - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, false); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - filter.doFilter(request, response, filterChain); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Transport certificate not found in the request"); - - } - - @Test(description = "Test the certificate in the attribute is overridden in header") - public void certificateInAttributeOverriddenTest() throws IOException, OpenBankingException, ServletException { - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, "invalid"); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, - TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT)); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test the validators are omitted if nothing is configured") - public void noValidatorsConfiguredTest() throws Exception { - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test the client ID is enforced") - public void clientIdEnforcementTest() throws Exception { - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - filter.doFilter(request, response, filterChain); - - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Unable to find client id in the request"); - } - - @Test(description = "Test client auth and signature enforcement validators engaged") - public void clientAuthSignatureEnforcementValidatorTest() throws Exception { - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - ClientAuthenticatorValidator clientAuthValidator = Mockito.spy(ClientAuthenticatorValidator.class); - SignatureAlgorithmEnforcementValidator signatureAlgorithmValidator = - Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE, - IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, - TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT)); - - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Mockito.doReturn("private_key_jwt").when(clientAuthValidator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(signatureAlgorithmValidator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(signatureAlgorithmValidator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - - List validators = new ArrayList<>(); - validators.add(clientAuthValidator); - validators.add(signatureAlgorithmValidator); - - Mockito.doReturn(validators).when(filter).getValidators(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test client auth and mtls enforcement validators engaged") - public void clientAuthMTLSEnforcementValidatorTest() throws Exception { - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - ClientAuthenticatorValidator clientAuthValidator = Mockito.spy(ClientAuthenticatorValidator.class); - MTLSEnforcementValidator mtlsEnforcementValidator = - Mockito.spy(MTLSEnforcementValidator.class); - - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE, - IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Mockito.doReturn("private_key_jwt").when(clientAuthValidator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - List validators = new ArrayList<>(); - validators.add(clientAuthValidator); - validators.add(mtlsEnforcementValidator); - - Mockito.doReturn(validators).when(filter).getValidators(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test mtls and signature enforcement validators engaged") - public void signatureMTLSeEnforcementValidatorTest() throws Exception { - - TokenFilter filter = Mockito.spy(TokenFilter.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - MTLSEnforcementValidator mtlsEnforcementValidator = - Mockito.spy(MTLSEnforcementValidator.class); - SignatureAlgorithmEnforcementValidator signatureAlgorithmValidator = - Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE, - IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - Mockito.doReturn("PS256").when(signatureAlgorithmValidator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(signatureAlgorithmValidator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - validators.add(signatureAlgorithmValidator); - - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - Mockito.doReturn(validators).when(filter).getValidators(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } - - @Test(description = "Test client auth, signature and mtls enforcement validators engaged") - public void allValidatorTest() throws Exception { - - SignatureAlgorithmEnforcementValidator signatureValidator = - Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - ClientAuthenticatorValidator clientAuthenticatorValidator = Mockito.spy(ClientAuthenticatorValidator.class); - - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE, - IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE); - - Mockito.doReturn("private_key_jwt").when(clientAuthenticatorValidator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(signatureValidator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(signatureValidator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - validators.add(signatureValidator); - validators.add(clientAuthenticatorValidator); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Mockito.doReturn(validators).when(filter).getValidators(); - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/util/TestConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/util/TestConstants.java deleted file mode 100644 index 971c2158..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/util/TestConstants.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.util; - -/** - * Test constants. - */ -public class TestConstants { - public static final String TARGET_STREAM = "targetStream"; - public static final String CERTIFICATE_HEADER = "x-wso2-mutual-auth-cert"; - public static final String EXPIRED_CERTIFICATE_CONTENT = "-----BEGIN CERTIFICATE-----" + - "MIIFODCCBCCgAwIBAgIEWcWGxDANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJH" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNVBAMTJU9wZW5CYW5raW5nIFBy" + - "ZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwHhcNMTkwNTE2MDg0NDQ2WhcNMjAwNjE2" + - "MDkxNDQ2WjBhMQswCQYDVQQGEwJHQjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxGzAZ" + - "BgNVBAsTEjAwMTU4MDAwMDFIUVFyWkFBWDEfMB0GA1UEAxMWc0Zna2k3Mk9pcXda" + - "TkZPWmc2T2FqaTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANoVwx4E" + - "iWnQs89lj8vKSy/xTbZU2AHS9tFNz7wVa+rkpFyLVPtQW8AthG4hlfrBYMne7/P9" + - "c1Fi/q+n7eomWvJJo44GV44GJhegM6yyRaIcQdpxe9x9G4twWK4cY+VU3TfE6Dbd" + - "DdmAt7ai4KFbbpB33N8RwXoeGZdwxZFNPmfaoZZbz5p9+aSMQf1UyExcdlPXah77" + - "PDZDwAnyy5kYXUPS59S78+p4twqZXyZu9hd+Su5Zod5UObRJ4F5LQzZPS1+KzBje" + - "JM0o8qoRRZTZkLNnmmQw503KXp/LCLrSbFU2ZLGy3bQpKFFc5I6tZiy67ELNzLWo" + - "DzngEbApwhX+jtsCAwEAAaOCAgQwggIAMA4GA1UdDwEB/wQEAwIHgDAgBgNVHSUB" + - "Af8EFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwgeAGA1UdIASB2DCB1TCB0gYLKwYB" + - "BAGodYEGAWQwgcIwKgYIKwYBBQUHAgEWHmh0dHA6Ly9vYi50cnVzdGlzLmNvbS9w" + - "b2xpY2llczCBkwYIKwYBBQUHAgIwgYYMgYNVc2Ugb2YgdGhpcyBDZXJ0aWZpY2F0" + - "ZSBjb25zdGl0dXRlcyBhY2NlcHRhbmNlIG9mIHRoZSBPcGVuQmFua2luZyBSb290" + - "IENBIENlcnRpZmljYXRpb24gUG9saWNpZXMgYW5kIENlcnRpZmljYXRlIFByYWN0" + - "aWNlIFN0YXRlbWVudDBtBggrBgEFBQcBAQRhMF8wJgYIKwYBBQUHMAGGGmh0dHA6" + - "Ly9vYi50cnVzdGlzLmNvbS9vY3NwMDUGCCsGAQUFBzAChilodHRwOi8vb2IudHJ1" + - "c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNydDA6BgNVHR8EMzAxMC+gLaArhilo" + - "dHRwOi8vb2IudHJ1c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNybDAfBgNVHSME" + - "GDAWgBRQc5HGIXLTd/T+ABIGgVx5eW4/UDAdBgNVHQ4EFgQU5eqvEZ6ZdQS5bq/X" + - "dzP5XY/fUXUwDQYJKoZIhvcNAQELBQADggEBAIg8bd/bIh241ewS79lXU058VjCu" + - "JC+4QtcI2XiGV3dBpg10V6Kb6E/h8Gru04uVZW1JK52ivVb5NYs6r8txRsTBIaA8" + - "Cr03LJqEftclL9NbkPZnpEkUfqCBfujNQF8XWaQgXIIA+io1UzV1TG3K9XCa/w2S" + - "sTANKfF8qK5kRsy6z9OGPUE+Oi3DUt+E9p5LCq6n5Bkp9YRGmyYRPs8JMkJmq3sf" + - "wtXOy27LE4exJRuZsF1CA78ObaRytuE3DJcnIRdhOcjWieS/MxZD7bzuuAPu5ySX" + - "i2/qxT3AlWtHtxrz0mKSC3rlgYAHCzCAHoASWKpf5tnB3TodPVZ6DYOu7oI=" + - "-----END CERTIFICATE-----"; - - public static final String CERTIFICATE_CONTENT = "-----BEGIN CERTIFICATE-----\n" + - "MIIFODCCBCCgAwIBAgIEWcbiiTANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJH\n" + - "QjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxLjAsBgNVBAMTJU9wZW5CYW5raW5nIFBy\n" + - "ZS1Qcm9kdWN0aW9uIElzc3VpbmcgQ0EwHhcNMjMxMTE1MDUxMDMxWhcNMjQxMjE1\n" + - "MDU0MDMxWjBhMQswCQYDVQQGEwJHQjEUMBIGA1UEChMLT3BlbkJhbmtpbmcxGzAZ\n" + - "BgNVBAsTEjAwMTU4MDAwMDFIUVFyWkFBWDEfMB0GA1UEAxMWakZRdVE0ZVFiTkNN\n" + - "U3FkQ29nMjFuRjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJslGjTm\n" + - "0tWwnnKgC7WNqUSYNxblURkJyoD5UuSmzpsM5nlUBAxYxBgztTo062LJELzUTzA/\n" + - "9kgLIMMgj+wG1OS475QCgeyoDmwf0SPuFRBl0G0AjxAvJzzs2aijzxiYRbKUa4gm\n" + - "O1KPU3Xlz89mi8lwjTZlxtGk3ABwBG4f5na5TY7uZMlgWPXDnTg7Cc1H4mrMbEFk\n" + - "UaXmb6ZhhGtp0JL04+4Lp16QWrgiHrlop+P8bd+pwmmOmLuglTIEh+v993j+7v8B\n" + - "XYqdmYQ3noiOhK9ynFPD1A7urrm71Pgkuq+Wk5HCvMiBK7zZ4Sn9FDovykDKZTFY\n" + - "MloVDXLhmfDQrmcCAwEAAaOCAgQwggIAMA4GA1UdDwEB/wQEAwIHgDAgBgNVHSUB\n" + - "Af8EFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwgeAGA1UdIASB2DCB1TCB0gYLKwYB\n" + - "BAGodYEGAWQwgcIwKgYIKwYBBQUHAgEWHmh0dHA6Ly9vYi50cnVzdGlzLmNvbS9w\n" + - "b2xpY2llczCBkwYIKwYBBQUHAgIwgYYMgYNVc2Ugb2YgdGhpcyBDZXJ0aWZpY2F0\n" + - "ZSBjb25zdGl0dXRlcyBhY2NlcHRhbmNlIG9mIHRoZSBPcGVuQmFua2luZyBSb290\n" + - "IENBIENlcnRpZmljYXRpb24gUG9saWNpZXMgYW5kIENlcnRpZmljYXRlIFByYWN0\n" + - "aWNlIFN0YXRlbWVudDBtBggrBgEFBQcBAQRhMF8wJgYIKwYBBQUHMAGGGmh0dHA6\n" + - "Ly9vYi50cnVzdGlzLmNvbS9vY3NwMDUGCCsGAQUFBzAChilodHRwOi8vb2IudHJ1\n" + - "c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNydDA6BgNVHR8EMzAxMC+gLaArhilo\n" + - "dHRwOi8vb2IudHJ1c3Rpcy5jb20vb2JfcHBfaXNzdWluZ2NhLmNybDAfBgNVHSME\n" + - "GDAWgBRQc5HGIXLTd/T+ABIGgVx5eW4/UDAdBgNVHQ4EFgQU7T6cMtCSQTT5JWW3\n" + - "O6vifRUSdpkwDQYJKoZIhvcNAQELBQADggEBAE9jrd/AE65vy3SEWdmFKPS4su7u\n" + - "EHy+KH18PETV6jMF2UFIJAOx7jl+5a3O66NkcpxFPeyvSuH+6tAAr2ZjpoQwtW9t\n" + - "Z9k2KSOdNOiJeQgjavwQC6t/BHI3yXWOIQm445BUN1cV9pagcRJjRyL3SPdHVoRf\n" + - "IbF7VI/+ULHwWdZYPXxtwUoda1mQFf6a+2lO4ziUHb3U8iD90FBURzID7WJ1ODSe\n" + - "B5zE/hG9Sxd9wlSXvl1oNmc/ha5oG/7rJpRqrx5Dcq3LEoX9iZZ3knHLkCm/abIQ\n" + - "7Nff8GQytuGhnGZxmGFYKDXdKElcl9dAlZ3bIK2I+I6jD2z2XvSfrhFyRjU=\n" + - "-----END CERTIFICATE-----"; - public static final String CLIENT_ASSERTION = "eyJraWQiOiJqeVJVY3l0MWtWQ2xjSXZsVWxjRHVrVlozdFUiLCJhbGciOiJQUzI1" + - "NiJ9.eyJzdWIiOiJpWXBSbTY0YjJ2bXZtS0RoZEw2S1pEOXo2ZmNhIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6OTQ0My9vYXV0a" + - "DIvdG9rZW4iLCJpc3MiOiJpWXBSbTY0YjJ2bXZtS0RoZEw2S1pEOXo2ZmNhIiwiZXhwIjoxNjEwNjMxNDEyLCJpYXQiOjE2MTA2MDE" + - "0MTIsImp0aSI6IjE2MTA2MDE0MTI5MDAifQ.tmMTlCL-VABhFTA6QQ6UPvUydKuzynidepAa8oZGEBfVyAsiW5IF01NKYD0ynpXXJC" + - "Q6hcbWK0FEGity67p6DeI9LT-xAnaKwZY7H8rbuxWye2vhanM0jVa1vggsmwWYyOR4k55ety9lP1MkcGZpaK48qoaqsX_X7GCSGXzq" + - "BncTEPYfCpVUQtS4ctwoCl06TFbY2Lfm9E24z1rfmU9xPc7au6LpKRLMMHQ8QXuc-FhnWdgEFv_3tAai2ovVmrqEfwj6Z6Ew5bFeI9" + - "jtCR4TSol47hzDwldx5rH7m2OPUx66yEtGrM7UU62fC-4nxplZ69fjlHN4KQ62PxEaCQs0_A"; - - public static final String CLIENT_ASSERTION_NO_HEADER = - "eyJraWQiOiJqeVJVY3l0MWtWQ2xjSXZsVWxjRHVrVlozdFUiLCJhbGciOiJQUzI1" + - "NiJ.eyJzdWIiOiJpWXBSbTY0YjJ2bXZtS0RoZEw2S1pEOXo2ZmNhIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6OTQ0My9vYXV0a" + - "DIvdG9rZW4iLCJpc3MiOiJpWXBSbTY0YjJ2bXZtS0RoZEw2S1pEOXo2ZmNhIiwiZXhwIjoxNjEwNjMxNDEyLCJpYXQiOjE2MTA2MDE" + - "0MTIsImp0aSI6IjE2MTA2MDE0MTI5MDAifQ.tmMTlCL-VABhFTA6QQ6UPvUydKuzynidepAa8oZGEBfVyAsiW5IF01NKYD0ynpXXJC" + - "Q6hcbWK0FEGity67p6DeI9LT-xAnaKwZY7H8rbuxWye2vhanM0jVa1vggsmwWYyOR4k55ety9lP1MkcGZpaK48qoaqsX_X7GCSGXzq" + - "BncTEPYfCpVUQtS4ctwoCl06TFbY2Lfm9E24z1rfmU9xPc7au6LpKRLMMHQ8QXuc-FhnWdgEFv_3tAai2ovVmrqEfwj6Z6Ew5bFeI9" + - "jtCR4TSol47hzDwldx5rH7m2OPUx66yEtGrM7UU62fC-4nxplZ69fjlHN4KQ62PxEaCQs0_A"; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/util/TestUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/util/TestUtil.java deleted file mode 100644 index f5d86e7c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/util/TestUtil.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.util; - -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import org.apache.commons.lang.StringUtils; -import org.json.JSONObject; -import org.wso2.carbon.identity.core.util.IdentityUtil; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletOutputStream; - -/** - * Test utils. - */ -public class TestUtil { - - public static Map getResponse(ServletOutputStream outputStream) { - - Map response = new HashMap<>(); - JSONObject outputStreamMap = new JSONObject(outputStream); - JSONObject targetStream = new JSONObject(outputStreamMap.get(TestConstants.TARGET_STREAM).toString()); - response.put(IdentityCommonConstants.OAUTH_ERROR, - targetStream.get(IdentityCommonConstants.OAUTH_ERROR).toString()); - response.put(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION, - targetStream.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION).toString()); - return response; - } - - public static X509Certificate getCertificate(String certificateContent) { - - if (StringUtils.isNotBlank(certificateContent)) { - // Build the Certificate object from cert content. - try { - return (X509Certificate) IdentityUtil.convertPEMEncodedContentToCertificate(certificateContent); - } catch (CertificateException e) { - //do nothing - } - } - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/ClientAuthenticatorValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/ClientAuthenticatorValidatorTest.java deleted file mode 100644 index 09bc947d..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/ClientAuthenticatorValidatorTest.java +++ /dev/null @@ -1,217 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.DefaultTokenFilter; -import com.wso2.openbanking.accelerator.identity.token.TokenFilter; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.token.util.TestUtil; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.http.HttpStatus; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; - -import static org.testng.Assert.assertEquals; - -/** - * Test for client authenticator validator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class}) -public class ClientAuthenticatorValidatorTest extends PowerMockTestCase { - - MockHttpServletResponse response; - MockHttpServletRequest request; - FilterChain filterChain; - - @BeforeMethod - public void beforeMethod() throws ReflectiveOperationException, IOException { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - - } - - @Test(description = "Test whether authentication follows the registered client authentication method PKJWT") - public void privateKeyJWTValidatorTest() throws IOException, ServletException, OpenBankingException { - - ClientAuthenticatorValidator validator = Mockito.spy(ClientAuthenticatorValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION_TYPE, - IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - Mockito.doReturn("private_key_jwt").when(validator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - filter.doFilter(request, response, filterChain); - - assertEquals(response.getStatus(), HttpServletResponse.SC_OK); - } - - @Test(description = "Test fail scenario authentication follows the registered client authentication method PKJWT") - public void privateKeyJWTValidatorNegativeTest() throws IOException, ServletException, OpenBankingException { - - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - PowerMockito.mockStatic(IdentityCommonUtil.class); - ClientAuthenticatorValidator validator = Mockito.spy(ClientAuthenticatorValidator.class); - - request.setParameter("client_assertion", TestConstants.CLIENT_ASSERTION); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - Mockito.doReturn("private_key_jwt").when(validator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("iYpRm64b2vmvmKDhdL6KZD9z6fca")) - .thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Request does not follow the registered token endpoint auth method private_key_jwt"); - } - - @Test(description = "Test client ID enforcement in client authentication method mtls") - public void privateKeyClientIdEnforcementTest() throws IOException, ServletException, OpenBankingException { - - ClientAuthenticatorValidator validator = Mockito.spy(ClientAuthenticatorValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - - request.setParameter("client_assertion_type", IdentityCommonConstants.OAUTH_JWT_BEARER_GRANT_TYPE); - Mockito.doReturn("private_key_jwt").when(validator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Unable to find client id in the request"); - } - - @Test(description = "Test whether authentication follows the registered client authentication method mtls") - public void mtlsValidatorTest() throws IOException, ServletException, OpenBankingException { - - PowerMockito.mockStatic(IdentityCommonUtil.class); - ClientAuthenticatorValidator validator = Mockito.spy(ClientAuthenticatorValidator.class); - request.setParameter("client_id", "iYpRm64b2vmvmKDhdL6KZD9z6fca"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - Mockito.doReturn("tls_client_auth").when(validator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpServletResponse.SC_OK); - } - - @Test(description = "Test client ID enforcement in client authentication method mtls") - public void mtlsValidatorClientIdEnforcementTest() throws IOException, ServletException, OpenBankingException { - - ClientAuthenticatorValidator validator = Mockito.spy(ClientAuthenticatorValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - Mockito.doReturn("tls_client_auth").when(validator) - .retrieveRegisteredAuthMethod("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), IdentityCommonConstants - .OAUTH2_INVALID_REQUEST_MESSAGE); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Unable to find client id in the request"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSCertificateValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSCertificateValidatorTest.java deleted file mode 100644 index b1ec9332..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSCertificateValidatorTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. - * - * This software is the property of WSO2 LLC. and its suppliers, if any. - * Dissemination of any information or reproduction of any material contained - * herein in any form is strictly forbidden, unless permitted by WSO2 expressly. - * You may not alter or remove any copyright or other notice from copies of this content. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.DefaultTokenFilter; -import com.wso2.openbanking.accelerator.identity.token.TokenFilter; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.token.util.TestUtil; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.http.HttpStatus; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; - -import static org.testng.Assert.assertEquals; - -/** - * class for MTLSCertificateValidator Test. - */ -@PrepareForTest({IdentityCommonUtil.class}) -@PowerMockIgnore({"jdk.internal.reflect.*"}) -public class MTLSCertificateValidatorTest extends PowerMockTestCase { - - MockHttpServletResponse response; - MockHttpServletRequest request; - FilterChain filterChain; - TokenFilter filter; - - @BeforeMethod - public void beforeMethod() throws ReflectiveOperationException, IOException, OpenBankingException { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - - List validators = new ArrayList<>(); - MTLSCertificateValidator mtlsCertificateValidator = Mockito.spy(MTLSCertificateValidator.class); - validators.add(mtlsCertificateValidator); - - filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, null); - - } - - @Test(description = "Test whether the expired certificate fails") - public void testMTLSCertValidationWithExpiredCertificate() throws IOException, ServletException { - - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.EXPIRED_CERTIFICATE_CONTENT); - - filter.doFilter(request, response, filterChain); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_UNAUTHORIZED); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_client"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Invalid mutual TLS request. Client certificate is expired"); - - } - - @Test(description = "Test whether the expired certificate fails") - public void testMTLSCertValidationWithValidCertificate() throws IOException, ServletException { - - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpStatus.SC_OK); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSEnforcementValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSEnforcementValidatorTest.java deleted file mode 100644 index f76ba2b8..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/MTLSEnforcementValidatorTest.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.DefaultTokenFilter; -import com.wso2.openbanking.accelerator.identity.token.TokenFilter; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.token.util.TestUtil; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.http.HttpStatus; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; - -import static org.testng.Assert.assertEquals; - -/** - * Test for MTLS enforcement validator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class}) -public class MTLSEnforcementValidatorTest extends PowerMockTestCase { - - MockHttpServletResponse response; - MockHttpServletRequest request; - FilterChain filterChain; - - @BeforeMethod - public void beforeMethod() throws ReflectiveOperationException, IOException { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - - } - - @Test(description = "Test the complete flow with certificate header configured") - public void certificateHeaderValidation() throws Exception { - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - filter.doFilter(request, response, filterChain); - - assertEquals(response.getStatus(), HttpServletResponse.SC_OK); - } - - @Test(description = "Test the complete flow with certificate passed as a attribute") - public void certificateAttributeValidation() throws Exception { - - PowerMockito.mockStatic(IdentityCommonUtil.class); - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - IdentityCommonUtil util = Mockito.mock(IdentityCommonUtil.class); - - X509Certificate cert = TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, - TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT)); - - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getCertificateFromAttribute(cert)).thenReturn(cert); - - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpServletResponse.SC_OK); - } - - @Test(description = "Test whether the certificate header is present") - public void noCertificateHeaderValidation() throws IOException, OpenBankingException, ServletException { - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - PowerMockito.mockStatic(IdentityCommonUtil.class); - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - filter.doFilter(request, response, filterChain); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Transport certificate not found in the request"); - } - - - - @Test(description = "Test the certificate in attribute is passed as a header") - public void certificateIsPresentInAttributeTest() throws IOException, OpenBankingException, ServletException { - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - - X509Certificate cert = TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, - TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT)); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - PowerMockito.when(IdentityCommonUtil.getCertificateFromAttribute(cert)).thenReturn(cert); - - filter.doFilter(request, response, filterChain); - assertEquals(response.getStatus(), HttpServletResponse.SC_OK); - } - - @Test(description = "Test whether the certificate attribute is valid") - public void invalidCertificateHeaderValidation() throws IOException, OpenBankingException, ServletException { - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, null); - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - filter.doFilter(request, response, filterChain); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Transport certificate not found in the request"); - - } - - @Test(description = "Test whether the certificate passed through the certificate header is valid") - public void invalidCertificateValidation() throws Exception { - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - PowerMockito.mockStatic(IdentityCommonUtil.class); - MTLSEnforcementValidator mtlsEnforcementValidator = Mockito.spy(MTLSEnforcementValidator.class); - - request.addHeader(TestConstants.CERTIFICATE_HEADER, "test"); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - - List validators = new ArrayList<>(); - validators.add(mtlsEnforcementValidator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - - filter.doFilter(request, response, filterChain); - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_client"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Invalid transport certificate. Certificate passed through the request not valid"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/SignatureAlgorithmEnforcementValidatorTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/SignatureAlgorithmEnforcementValidatorTest.java deleted file mode 100644 index 2e087bb0..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/java/com/wso2/openbanking/accelerator/identity/token/validators/SignatureAlgorithmEnforcementValidatorTest.java +++ /dev/null @@ -1,215 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.token.validators; - -import com.wso2.openbanking.accelerator.identity.internal.IdentityExtensionsDataHolder; -import com.wso2.openbanking.accelerator.identity.token.DefaultTokenFilter; -import com.wso2.openbanking.accelerator.identity.token.TokenFilter; -import com.wso2.openbanking.accelerator.identity.token.util.TestConstants; -import com.wso2.openbanking.accelerator.identity.token.util.TestUtil; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.http.HttpStatus; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletResponse; - -import static org.testng.Assert.assertEquals; - -/** - * Test for signature algorithm enforcement validator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({IdentityCommonUtil.class, OAuthServerConfiguration.class}) -public class SignatureAlgorithmEnforcementValidatorTest extends PowerMockTestCase { - - MockHttpServletResponse response; - MockHttpServletRequest request; - FilterChain filterChain; - - @BeforeMethod - public void beforeMethod() { - - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - filterChain = Mockito.spy(FilterChain.class); - - } - - @Test(description = "Test the complete signature algorithm validation flow") - public void signatureAlgorithmValidationTest() throws Exception { - - SignatureAlgorithmEnforcementValidator validator = Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, - TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT)); - Mockito.doReturn("PS256").when(validator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(validator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - - List validators = new ArrayList<>(); - validators.add(validator); - - Map configMap = new HashMap<>(); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - filter.doFilter(request, response, filterChain); - - assertEquals(response.getStatus(), HttpServletResponse.SC_OK); - } - - @Test(description = "Test when registered algorithm and signed algorithm differ") - public void signatureInvalidAlgorithmValidationTest() throws Exception { - Map configMap = new HashMap<>(); - PowerMockito.mockStatic(IdentityCommonUtil.class); - PowerMockito.mockStatic(OAuthServerConfiguration.class); - - OAuthServerConfiguration oAuthServerConfiguration = Mockito.mock(OAuthServerConfiguration.class); - configMap.put(IdentityCommonConstants.ENABLE_TRANSPORT_CERT_AS_HEADER, true); - configMap.put(IdentityCommonConstants.CLIENT_CERTIFICATE_ENCODE, false); - IdentityExtensionsDataHolder.getInstance().setConfigurationMap(configMap); - - SignatureAlgorithmEnforcementValidator validator = Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION); - request.addHeader(TestConstants.CERTIFICATE_HEADER, TestConstants.CERTIFICATE_CONTENT); - - Mockito.doReturn("PS256").when(validator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("RS256").when(validator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("iYpRm64b2vmvmKDhdL6KZD9z6fca")) - .thenReturn(true); - PowerMockito.when(IdentityCommonUtil.getMTLSAuthHeader()).thenReturn(TestConstants.CERTIFICATE_HEADER); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_UNAUTHORIZED); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), IdentityCommonConstants - .OAUTH2_INVALID_CLIENT_MESSAGE); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Registered algorithm does not match with the token signed algorithm"); - } - - @Test(description = "Test the validity of the signed assertion without client ID") - public void signatureInvalidAssertionValidationTest() throws Exception { - - SignatureAlgorithmEnforcementValidator validator = Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, TestConstants.CLIENT_ASSERTION_NO_HEADER); - Mockito.doReturn("PS256").when(validator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_UNAUTHORIZED); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Error occurred while parsing the signed assertion"); - } - - @Test(description = "Test the validity of the signed assertion with client ID") - public void invalidClientAssertionValidationTest() throws Exception { - - SignatureAlgorithmEnforcementValidator validator = Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - request.setParameter(IdentityCommonConstants.CLIENT_ID, "test"); - request.setParameter(IdentityCommonConstants.OAUTH_JWT_ASSERTION, "test"); - request.setAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE, - TestUtil.getCertificate(TestConstants.CERTIFICATE_CONTENT)); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_UNAUTHORIZED); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Error occurred while parsing the signed assertion"); - } - - @Test(description = "Client ID enforcement test") - public void clientIdEnforcementTest() throws Exception { - - SignatureAlgorithmEnforcementValidator validator = Mockito.spy(SignatureAlgorithmEnforcementValidator.class); - PowerMockito.mockStatic(IdentityCommonUtil.class); - Mockito.doReturn("PS256").when(validator) - .getRegisteredSigningAlgorithm("iYpRm64b2vmvmKDhdL6KZD9z6fca"); - Mockito.doReturn("PS256").when(validator) - .getRequestSigningAlgorithm(TestConstants.CLIENT_ASSERTION); - - List validators = new ArrayList<>(); - validators.add(validator); - - TokenFilter filter = Mockito.spy(TokenFilter.class); - Mockito.doReturn(new DefaultTokenFilter()).when(filter).getDefaultTokenFilter(); - Mockito.doReturn(validators).when(filter).getValidators(); - PowerMockito.when(IdentityCommonUtil.getRegulatoryFromSPMetaData("test")).thenReturn(true); - filter.doFilter(request, response, filterChain); - - Map responseMap = TestUtil.getResponse(response.getOutputStream()); - assertEquals(response.getStatus(), HttpStatus.SC_BAD_REQUEST); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR), "invalid_request"); - assertEquals(responseMap.get(IdentityCommonConstants.OAUTH_ERROR_DESCRIPTION), - "Unable to find client id in the request"); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/common.auth.script.js b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/common.auth.script.js deleted file mode 100644 index 41bb1c33..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/common.auth.script.js +++ /dev/null @@ -1,61 +0,0 @@ -var psuChannel = 'Online Banking'; - -function onLoginRequest(context) { - reportingData(context, "AuthenticationAttempted", false, psuChannel); - - executeStep(1, { - onSuccess: function (context) { - var supportedAcrValues = ['urn:openbanking:psd2:sca', 'urn:openbanking:psd2:ca']; - var selectedAcr = selectAcrFrom(context, supportedAcrValues); - reportingData(context, "AuthenticationSuccessful", false, psuChannel); - - if (isACREnabled()) { - - context.selectedAcr = selectedAcr; - if (isTRAEnabled()) { - if (selectedAcr === 'urn:openbanking:psd2:ca') { - executeTRAFunction(context); - } else { - executeStep(2, { - onSuccess: function (context) { - reportingData(context, "AuthenticationSuccessful", true, psuChannel); - }, - onFail: function (context) { - reportingData(context, "AuthenticationFailed", false, psuChannel); - } - }); - } - } else { - if (selectedAcr == 'urn:openbanking:psd2:sca') { - executeStep(2, { - onSuccess: function (context) { - reportingData(context, "AuthenticationSuccessful", true, psuChannel); - }, - onFail: function (context) { - reportingData(context, "AuthenticationFailed", false, psuChannel); - } - }); - } - } - - } else { - if (isTRAEnabled()) { - executeTRAFunction(context); - } else { - executeStep(2, { - onSuccess: function (context) { - reportingData(context, "AuthenticationSuccessful", true, psuChannel); - }, - onFail: function (context) { - reportingData(context, "AuthenticationFailed", false, psuChannel); - } - }); - } - } - }, - onFail: function (context) { //basic auth fail - reportingData(context, "AuthenticationFailed", false, psuChannel); - //retry - } - }); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/testng.xml deleted file mode 100644 index f2b8a270..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/testng.xml +++ /dev/null @@ -1,151 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/wso2carbon.jks b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/wso2carbon.jks deleted file mode 100644 index c8775783..00000000 Binary files a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.identity/src/test/resources/wso2carbon.jks and /dev/null differ diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/pom.xml deleted file mode 100644 index 18e6a508..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/pom.xml +++ /dev/null @@ -1,216 +0,0 @@ - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.keymanager - bundle - WSO2 Open Banking - KeyManager Extensions - - - - org.wso2.eclipse.osgi - org.eclipse.osgi.services - - - org.eclipse.osgi - org.eclipse.osgi - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.api - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.impl - - - org.mockito - mockito-all - - - org.powermock - powermock-api-mockito - test - - - org.testng - testng - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - org.powermock - powermock-module-testng - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.jacoco - jacoco-maven-plugin - - - - **/*Component.class - **/*DataHolder.class - **/OBKeyManagerConfiguration.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.80 - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.keymanager.internal - - - org.apache.axis2;version="${axis2.imp.pkg.version.range}", - org.apache.axis2.client;version="${axis2.imp.pkg.version.range}", - org.apache.axis2.context;version="${axis2.imp.pkg.version.range}", - org.apache.commons.logging;version="${commons.logging.version}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - org.wso2.carbon.apimgt.api;version="${org.wso2.carbon.apimgt.version.range}", - org.wso2.carbon.apimgt.api.model;version="${org.wso2.carbon.apimgt.version.range}", - org.wso2.carbon.apimgt.impl;version="${org.wso2.carbon.apimgt.version.range}", - org.wso2.carbon.apimgt.impl.jwt;version="${org.wso2.carbon.apimgt.version.range}", - org.wso2.carbon.authenticator.stub;version="${carbon.kernel.version.range}", - org.wso2.carbon.user.mgt.stub;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.oauth.stub;version="${org.wso2.carbon.identity.oauth.stub.version.range}", - org.wso2.carbon.identity.oauth.stub.dto;version="${org.wso2.carbon.identity.oauth.stub.version.range}", - - - !com.wso2.openbanking.accelerator.keymanager.internal, - com.wso2.openbanking.accelerator.keymanager.*;version="${project.version}", - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerUtil.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerUtil.java deleted file mode 100644 index fed1c6be..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerUtil.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.keymanager.internal.KeyManagerDataHolder; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ServiceContext; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.ExceptionCodes; -import org.wso2.carbon.apimgt.api.model.OAuthAppRequest; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.UserCoreConstants; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; - -import java.lang.reflect.InvocationTargetException; -import java.rmi.RemoteException; -import java.util.HashMap; -import java.util.Map; - -/** - * Util class for OB key manager. - */ -public class KeyManagerUtil { - - private static final Log log = LogFactory.getLog(KeyManagerUtil.class); - - /** - * Method to get the session Cookie. - * - * @return Session cookie as a String - * @throws APIManagementException When failed to obtain the session cookie - * @deprecated ApplicationManagementService is used instead of SOAP API calls. - */ - @Deprecated - @Generated(message = "Excluding from unit test coverage") - public static String getSessionCookie() throws APIManagementException { - - String sessionCookie = ""; - APIManagerConfiguration config = KeyManagerDataHolder.getInstance().getApiManagerConfigurationService() - .getAPIManagerConfiguration(); - String adminUsername = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); - - char[] adminPassword = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray(); - try { - if (KeyManagerDataHolder.getInstance().getAuthenticationAdminStub().login(adminUsername, - String.valueOf(adminPassword), "localhost")) { - ServiceContext serviceContext = KeyManagerDataHolder.getInstance().getAuthenticationAdminStub() - ._getServiceClient().getLastOperationContext() - .getServiceContext(); - sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); - } - } catch (RemoteException e) { - throw new APIManagementException("Error occurred while making remote call.", e); - } catch (LoginAuthenticationExceptionException e) { - throw new APIManagementException("Error occurred while authenticating user.", e); - } - return sessionCookie; - } - - - /** - * Method to bind session cookie to Admin service client. - * - * @param serviceClient Admin service client - * @param sessionCookie session cookie as a string - * @deprecated ApplicationManagementService is used instead of SOAP API calls. - */ - @Deprecated - @Generated(message = "Excluding from unit test coverage") - public static void setAdminServiceSession(ServiceClient serviceClient, String sessionCookie) { - - Options userAdminOption = serviceClient.getOptions(); - userAdminOption.setManageSession(true); - userAdminOption.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie); - } - - /** - * Obtain OB Key Manage Extension Impl class from config. - * - * @return obKeyManagerExtensionInterface - */ - public static OBKeyManagerExtensionInterface getOBKeyManagerExtensionImpl() throws APIManagementException { - OBKeyManagerExtensionInterface obKeyManagerExtensionImpl; - try { - String obKeyManagerExtensionImplName = OpenBankingConfigParser.getInstance() - .getOBKeyManagerExtensionImpl(); - if (!StringUtils.isEmpty(obKeyManagerExtensionImplName)) { - obKeyManagerExtensionImpl = (OBKeyManagerExtensionInterface) - Class.forName(obKeyManagerExtensionImplName).getDeclaredConstructor().newInstance(); - return obKeyManagerExtensionImpl; - } else { - return null; - } - - } catch (InstantiationException | IllegalAccessException | - InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { - throw new APIManagementException("Failed to obtain OB Key Manager Extension Impl instance", e); - } - } - - /** - * Extract values for additional properties from input. - * - * @param oauthAppRequest OAuthAppRequest object - * @return Additional Property Map - * @throws APIManagementException - */ - public static HashMap getValuesForAdditionalProperties(OAuthAppRequest oauthAppRequest) - throws APIManagementException { - // Get additional properties defined in the config - Map> keyManagerAdditionalProperties = OpenBankingConfigParser.getInstance() - .getKeyManagerAdditionalProperties(); - HashMap additionalProperties = new HashMap<>(); - Object additionalPropertiesJSON; - try { - // Get values for additional properties given at key generation step - additionalPropertiesJSON = new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse((String) oauthAppRequest.getOAuthApplicationInfo() - .getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES)); - if (!(additionalPropertiesJSON instanceof JSONObject)) { - log.error(APIConstants.JSON_ADDITIONAL_PROPERTIES + " is not a JSON object"); - throw new APIManagementException(ExceptionCodes.JSON_PARSE_ERROR.getErrorMessage(), - ExceptionCodes.JSON_PARSE_ERROR); - } - } catch (ParseException e) { - throw new APIManagementException(ExceptionCodes.JSON_PARSE_ERROR.getErrorMessage(), e, - ExceptionCodes.JSON_PARSE_ERROR); - } - - JSONObject additionalPropertiesJSONObject = (JSONObject) additionalPropertiesJSON; - // Add values of additional properties defined in the config to the default additional property list JSON object - for (String key : keyManagerAdditionalProperties.keySet()) { - additionalProperties.put(key, additionalPropertiesJSONObject.getAsString(key)); - } - return additionalProperties; - } - - /** - * Obtain Application role name using application name. - * @param applicationName Application name - * @return Application role name - */ - protected static String getAppRoleName(String applicationName) { - - return org.wso2.carbon.identity.application.mgt.ApplicationConstants.APPLICATION_DOMAIN + - UserCoreConstants.DOMAIN_SEPARATOR + applicationName; - } - - /** - * Add the application role to the admin so that admin can manipulate app data. - * @param applicationName Application Name - * @throws APIManagementException - */ - @Generated(message = "excluding from coverage because it is a void method with external calls") - protected static void addApplicationRoleToAdmin(String applicationName) throws APIManagementException { - - APIManagerConfiguration config = KeyManagerDataHolder.getInstance().getApiManagerConfigurationService() - .getAPIManagerConfiguration(); - String adminUsername = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); - String roleName = getAppRoleName(applicationName); - String[] newRoles = {roleName}; - - try { - // assign new application role to the user. - UserRealm realm = getUserRealm(adminUsername); - if (realm != null) { - if (((AbstractUserStoreManager) realm.getUserStoreManager()).isUserInRole(adminUsername, roleName)) { - if (log.isDebugEnabled()) { - log.debug("The user: " + adminUsername + " is already having the role: " + roleName); - } - } else { - realm.getUserStoreManager().updateRoleListOfUser(adminUsername, null, newRoles); - if (log.isDebugEnabled()) { - log.debug("Assigning application role : " + roleName + " to the user : " + adminUsername); - } - } - } - } catch (UserStoreException e) { - throw new APIManagementException("Error while assigning application role: " + roleName + - " to the user: " + adminUsername, e); - } - } - - @Generated(message = "separated for unit testing purposes") - protected static UserRealm getUserRealm(String username) throws APIManagementException { - - try { - int tenantId = IdentityTenantUtil.getTenantIdOfUser(username); - return KeyManagerDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); - } catch (UserStoreException e) { - throw new APIManagementException("Error while obtaining user realm for user: " + username, e); - } - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerConfiguration.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerConfiguration.java deleted file mode 100644 index b02b314f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerConfiguration.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import org.apache.commons.lang.StringUtils; -import org.osgi.service.component.annotations.Component; -import org.wso2.carbon.apimgt.api.model.ConfigurationDto; -import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * Key manager configuration class to override the default key manager interface implementation. - */ -@Component( - name = "com.wso2.open.banking.keymanager.config", - immediate = true, - service = KeyManagerConnectorConfiguration.class -) -public class OBKeyManagerConfiguration implements KeyManagerConnectorConfiguration { - - @Override - public String getImplementation() { - - return OBKeyManagerImpl.class.getName(); - } - - @Override - public String getJWTValidator() { - - return JWTValidatorImpl.class.getName(); - } - - @Override - public List getConnectionConfigurations() { - - List configurationDtoList = new ArrayList<>(); - configurationDtoList - .add(new ConfigurationDto("Username", "Username", "input", "Username of admin user", "", - true, false, Collections.emptyList(), false)); - configurationDtoList - .add(new ConfigurationDto("Password", "Password", "input", - "Password of Admin user", "", true, true, Collections.emptyList(), false)); - return configurationDtoList; - - } - - @Override - public List getApplicationConfigurations() { - - List applicationConfigurationsList = new ArrayList(); - applicationConfigurationsList - .add(new ConfigurationDto(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME, - "Application Access Token Expiry Time ", "input", "Type Application Access Token Expiry Time " + - "in seconds ", APIConstants.KeyManager.NOT_APPLICABLE_VALUE, false, false, - Collections.EMPTY_LIST, false)); - applicationConfigurationsList - .add(new ConfigurationDto(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME, - "User Access Token Expiry Time ", "input", "Type User Access Token Expiry Time " + - "in seconds ", APIConstants.KeyManager.NOT_APPLICABLE_VALUE, false, false, - Collections.EMPTY_LIST, false)); - applicationConfigurationsList - .add(new ConfigurationDto(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME, - "Refresh Token Expiry Time ", "input", "Type Refresh Token Expiry Time " + - "in seconds ", APIConstants.KeyManager.NOT_APPLICABLE_VALUE, false, false, - Collections.EMPTY_LIST, false)); - applicationConfigurationsList - .add(new ConfigurationDto(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME, - "Id Token Expiry Time", "input", "Type ID Token Expiry Time " + - "in seconds ", APIConstants.KeyManager.NOT_APPLICABLE_VALUE, false, false, - Collections.EMPTY_LIST, false)); - - Map> keyManagerAdditionalProperties = OpenBankingConfigParser.getInstance() - .getKeyManagerAdditionalProperties(); - - for (Map.Entry> propertyElement : keyManagerAdditionalProperties.entrySet()) { - String propertyName = propertyElement.getKey(); - Map property = propertyElement.getValue(); - boolean required = !StringUtils.isEmpty(property.get("required")) - && Boolean.parseBoolean(property.get("required")); - boolean mask = !StringUtils.isEmpty(property.get("mask")) - && Boolean.parseBoolean(property.get("mask")); - boolean multiple = !StringUtils.isEmpty(property.get("multiple")) - && Boolean.parseBoolean(property.get("multiple")); - List values = StringUtils.isEmpty(property.get("values")) ? Collections.EMPTY_LIST - : Arrays.asList(property.get("values").split(",")); - - applicationConfigurationsList.add(new ConfigurationDto(propertyName, property.get("label"), - property.get("type"), property.get("tooltip"), property.get("default"), required , mask - , values, multiple)); - } - - return applicationConfigurationsList; - } - - @Override - public String getType() { - - return OBKeyManagerConstants.CUSTOM_KEYMANAGER_TYPE; - } - - @Override - public String getDefaultScopesClaim() { - - return APIConstants.JwtTokenConstants.SCOPE; - } - - @Override - public String getDefaultConsumerKeyClaim() { - - return APIConstants.JwtTokenConstants.AUTHORIZED_PARTY; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerConstants.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerConstants.java deleted file mode 100644 index 766f3588..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerConstants.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.keymanager; - -/** - * OB Key Manager Constants. - */ -public class OBKeyManagerConstants { - - public static final String CUSTOM_KEYMANAGER_TYPE = "ObKeyManager"; - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerExtensionInterface.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerExtensionInterface.java deleted file mode 100644 index d2fd842e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerExtensionInterface.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.keymanager; - -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.model.ConfigurationDto; -import org.wso2.carbon.apimgt.api.model.OAuthAppRequest; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * Interface for validation OB Key Manager Additional Properties. - */ -public interface OBKeyManagerExtensionInterface { - - /** - * Validate additional properties. - * - * @param obAdditionalProperties OB Additional Properties Map - * @throws APIManagementException when failed to validate a given property - */ - void validateAdditionalProperties(Map obAdditionalProperties) - throws APIManagementException; - - /** - * Do changes to app request before creating the app at toolkit level. - * - * @param oAuthAppRequest OAuth Application Request - * @param additionalProperties Values for additional property list defined in the config - * @throws APIManagementException when failed to validate a given property - */ - void doPreCreateApplication(OAuthAppRequest oAuthAppRequest, HashMap additionalProperties) - throws APIManagementException; - - /** - * Do changes to app request before updating the app at toolkit level. - * - * @param oAuthAppRequest OAuth Application Request - * @param additionalProperties Values for additional property list defined in the config - * @throws APIManagementException when failed to validate a given property - */ - - void doPreUpdateApplication(OAuthAppRequest oAuthAppRequest, HashMap additionalProperties, - ServiceProvider serviceProvider) - throws APIManagementException; - - /** - * Do changes to service provider before updating the service provider properties. - * - * @param oAuthConsumerAppDTO oAuth application DTO - * @param serviceProvider Service provider application - * @param additionalProperties Values for additional property list defined in the config - * @param isCreateApp Whether this functions is called at app creation - * @throws APIManagementException when failed to validate a given property - */ - void doPreUpdateSpApp(OAuthConsumerAppDTO oAuthConsumerAppDTO, ServiceProvider serviceProvider, - HashMap additionalProperties, boolean isCreateApp) - throws APIManagementException; -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerImpl.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerImpl.java deleted file mode 100644 index ee86cf1c..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/OBKeyManagerImpl.java +++ /dev/null @@ -1,470 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import com.wso2.openbanking.accelerator.keymanager.internal.KeyManagerDataHolder; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.ExceptionCodes; -import org.wso2.carbon.apimgt.api.model.AccessTokenInfo; -import org.wso2.carbon.apimgt.api.model.AccessTokenRequest; -import org.wso2.carbon.apimgt.api.model.ApplicationConstants; -import org.wso2.carbon.apimgt.api.model.ConfigurationDto; -import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration; -import org.wso2.carbon.apimgt.api.model.OAuthAppRequest; -import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo; -import org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl; -import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; -import org.wso2.carbon.identity.oauth.OAuthAdminService; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * OB key manager client impl class. - */ -public class OBKeyManagerImpl extends AMDefaultKeyManagerImpl implements OBKeyManagerExtensionInterface { - - private static final Log log = LogFactory.getLog(OBKeyManagerImpl.class); - - public static final String OAUTH2 = "oauth2"; - - @Override - public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException { - - try { - ApplicationManagementServiceImpl applicationManagementService = getApplicationMgmtServiceImpl(); - ServiceProvider serviceProvider = applicationManagementService.getServiceProviderByClientId( - tokenRequest.getClientId(), IdentityApplicationConstants.OAuth2.NAME, tenantDomain); - if (serviceProvider != null) { - ServiceProviderProperty regulatoryProperty = Arrays.stream(serviceProvider.getSpProperties()) - .filter(serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase(OpenBankingConstants.REGULATORY)).findAny().orElse(null); - if (regulatoryProperty != null && "true".equalsIgnoreCase(regulatoryProperty.getValue())) { - return null; - } - } - } catch (IdentityApplicationManagementException e) { - log.error("Error while generating keys. ", e); - } - return super.getNewApplicationAccessToken(tokenRequest); - } - - @Override - public String getType() { - - return OBKeyManagerConstants.CUSTOM_KEYMANAGER_TYPE; - } - - /** - * Validate OAuth Application Properties. - * - * @param oAuthApplicationInfo OAuthApplication Information - * @throws APIManagementException when failed to validate the OAuth application properties - */ - @Override - protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthApplicationInfo) - throws APIManagementException { - - String type = getType(); - List missedRequiredValues = new ArrayList<>(); - Map obAdditionalProperties = new HashMap<>(); - - KeyManagerConnectorConfiguration oBKeyManagerConnectorConfiguration = KeyManagerDataHolder.getInstance() - .getKeyManagerConnectorConfiguration(type); - // Obtain additional key manager configurations defined in config - Map> keyManagerAdditionalProperties = OpenBankingConfigParser.getInstance() - .getKeyManagerAdditionalProperties(); - - if (oBKeyManagerConnectorConfiguration != null) { - List applicationConfigurationDtoList = oBKeyManagerConnectorConfiguration - .getApplicationConfigurations(); - Object additionalProperties = oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES); - if (additionalProperties != null) { - Object additionalPropertiesJson; - try { - additionalPropertiesJson = new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(additionalProperties.toString()); - if (!(additionalPropertiesJson instanceof JSONObject)) { - String errMsg = "Additional properties is not a valid json object"; - log.error(errMsg); - throw new APIManagementException(errMsg, ExceptionCodes - .from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, - errMsg)); - } - } catch (ParseException e) { - String errMsg = "Additional properties is not a valid JSON string"; - throw new APIManagementException(errMsg, e, ExceptionCodes - .from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, - errMsg)); - } - - for (ConfigurationDto configurationDto : applicationConfigurationDtoList) { - String key = configurationDto.getName(); - String values = ((JSONObject) additionalPropertiesJson).getAsString(key); - - if (values == null) { - // AbstractKeyManager Validations - // Check if mandatory parameters are missing - if (configurationDto.isRequired()) { - missedRequiredValues.add(configurationDto.getName()); - } - } else { - // OBKeyManager Validations - if (keyManagerAdditionalProperties.containsKey(key)) { - configurationDto.setValues(Arrays.asList(values)); - obAdditionalProperties.put(key, configurationDto); - } else { - // AMDefaultKeyManager validations - // Check for invalid time periods - if (StringUtils.isNotBlank(values) && !StringUtils - .equals(values, APIConstants.KeyManager.NOT_APPLICABLE_VALUE)) { - try { - Long longValue = Long.parseLong(values); - if (longValue < 0) { - String errMsg = "Application configuration values cannot have negative values."; - throw new APIManagementException(errMsg, ExceptionCodes - .from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, - errMsg)); - } - } catch (NumberFormatException e) { - String errMsg = "Application configuration values cannot have string values."; - throw new APIManagementException(errMsg, e, ExceptionCodes - .from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg)); - } - } - } - } - } - if (!missedRequiredValues.isEmpty()) { - throw new APIManagementException( - "Missing required properties to create/update oauth " + "application", - ExceptionCodes.KEY_MANAGER_MISSING_REQUIRED_PROPERTIES_IN_APPLICATION); - } - // Call external method to validate additional properties - if (obAdditionalProperties.size() != 0) { - validateAdditionalProperties(obAdditionalProperties); - } - } - } else { - throw new APIManagementException("Invalid Key Manager Type " + type, ExceptionCodes.KEY_MANAGER_NOT_FOUND); - } - } - - /** - * Overriding the default create application method with Open Banking requirements. - * - * @param oauthAppRequest OAuthApplicationRequest object - * @return OAuthApplicationInfo object - * @throws APIManagementException when failed to create the application properly in Key Manager - */ - @Override - @Generated(message = "Excluding from code coverage since it is covered from other method") - public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws APIManagementException { - - HashMap additionalProperties = KeyManagerUtil.getValuesForAdditionalProperties(oauthAppRequest); - if (Boolean.parseBoolean(additionalProperties.get(OpenBankingConstants.REGULATORY))) { - // Adding SP property to identify create request. Will be removed when setting up authenticators. - additionalProperties.put("AppCreateRequest", "true"); - } - doPreCreateApplication(oauthAppRequest, additionalProperties); - OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo(); - String username = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME); - oAuthApplicationInfo = super.createApplication(oauthAppRequest); - // Need to get the application name after creating the application to obtain the generated app name - String appName = oAuthApplicationInfo.getClientName(); - // Admin needs to have application role to retrieve and edit the app - KeyManagerUtil.addApplicationRoleToAdmin(appName); - - try { - String tenantDomain = ServiceProviderUtils.getSpTenantDomain(oAuthApplicationInfo.getClientId()); - updateSpProperties(appName, tenantDomain, username, additionalProperties, true); - - ServiceProvider appServiceProvider = getApplicationMgmtServiceImpl() - .getServiceProvider(appName, tenantDomain); - ServiceProviderProperty regulatoryProperty = getSpPropertyFromSPMetaData( - OpenBankingConstants.REGULATORY, appServiceProvider.getSpProperties()); - - if (regulatoryProperty != null) { - if (Boolean.parseBoolean(regulatoryProperty.getValue())) { - OAuthAppRequest updatedOauthAppRequest = oauthAppRequest; - ServiceProviderProperty appNameProperty = getSpPropertyFromSPMetaData("DisplayName", - appServiceProvider.getSpProperties()); - if (appNameProperty != null) { - updatedOauthAppRequest.getOAuthApplicationInfo().setClientName(appNameProperty.getValue()); - } - // Assigning null as it is how the tokenScope parameter is used in the updateApplication method - updatedOauthAppRequest.getOAuthApplicationInfo().addParameter("tokenScope", null); - super.updateApplication(updatedOauthAppRequest); - } - } - return oAuthApplicationInfo; - - } catch (OpenBankingException | APIManagementException e) { - throw new APIManagementException(ExceptionCodes.OAUTH2_APP_CREATION_FAILED.getErrorMessage(), - e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED); - } catch (IdentityApplicationManagementException e) { - String errMsg = "error occurred in retrieving service provider for app " + appName; - log.error(errMsg); - throw new APIManagementException(errMsg, e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED); - } - } - - @Override - @Generated(message = "Excluding from code coverage since it is covered from other method") - public OAuthApplicationInfo updateApplication(OAuthAppRequest oAuthAppRequest) throws APIManagementException { - - HashMap additionalProperties = KeyManagerUtil.getValuesForAdditionalProperties(oAuthAppRequest); - // Adding SP property to identify update request. Will be removed when updating authenticators. - additionalProperties.put("AppCreateRequest", "false"); - OAuthApplicationInfo oAuthApplicationInfo = oAuthAppRequest.getOAuthApplicationInfo(); - String clientId = oAuthApplicationInfo.getClientId(); - // There is no way to identify the client type in here. So we have to hardcode "oauth2" as the client type - try { - ServiceProvider serviceProvider = getApplicationMgmtServiceImpl() - .getServiceProviderByClientId(clientId, OAUTH2, tenantDomain); - doPreUpdateApplication(oAuthAppRequest, additionalProperties, serviceProvider); - String appName = serviceProvider.getApplicationName(); - String username = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME); - updateSpProperties(appName, tenantDomain, username, additionalProperties, false); - } catch (IdentityApplicationManagementException e) { - String errMsg = "Cannot find Service provider application for client Id " + clientId; - log.error(errMsg); - throw new APIManagementException(errMsg, ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED); - } - - oAuthApplicationInfo = super.updateApplication(oAuthAppRequest); - return oAuthApplicationInfo; - } - - @Override - @Generated(message = "Excluding from code coverage since it is covered from other method") - public OAuthApplicationInfo retrieveApplication(String consumerKey) throws APIManagementException { - - OAuthApplicationInfo oAuthApplicationInfo = super.retrieveApplication(consumerKey); - String name = oAuthApplicationInfo.getClientName(); - try { - String tenantDomain = ServiceProviderUtils.getSpTenantDomain(consumerKey); - org.wso2.carbon.identity.application.common.model.ServiceProvider appServiceProvider = - getApplicationMgmtServiceImpl().getServiceProvider(name, tenantDomain); - // Iterate OB specific additional properties to check whether they override the value of any predefined - // sp properties in application management listeners - List spProperties = - new ArrayList<>(Arrays.asList(appServiceProvider.getSpProperties())); - return updateAdditionalProperties(oAuthApplicationInfo, spProperties); - } catch (IdentityApplicationManagementException | OpenBankingException e) { - throw new APIManagementException(ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED.getErrorMessage(), - e, ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED); - } - } - - /** - * @param spAppName Generate service provider application name - * @param tenantDomain Tenant domain of the service provider application - * @param username Application owner - * @param additionalProperties new Service provider property map - * @param isCreateApp Whether this function is called at app creation - * @throws APIManagementException - */ - protected void updateSpProperties(String spAppName, String tenantDomain, String username, - HashMap additionalProperties, boolean isCreateApp) - throws APIManagementException { - - try { - org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO oAuthConsumerAppDTO = getOAuthAdminService(). - getOAuthApplicationDataByAppName(spAppName); - ServiceProvider serviceProvider = getApplicationMgmtServiceImpl() - .getServiceProvider(spAppName, tenantDomain); - doPreUpdateSpApp(oAuthConsumerAppDTO, serviceProvider, additionalProperties, isCreateApp); - // Iterate OB specific additional properties to check whether they override the value of any predefined - // sp properties in application management listeners - List spProperties = - new ArrayList<>(Arrays.asList(serviceProvider.getSpProperties())); - for (Map.Entry propertyElement : additionalProperties.entrySet()) { - ServiceProviderProperty overridenSPproperty = spProperties.stream().filter( - serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase(propertyElement.getKey())).findAny().orElse(null); - // If SP property is overridden, remove old SP property and add the new one - if (overridenSPproperty != null) { - spProperties.remove(overridenSPproperty); - overridenSPproperty.setValue(propertyElement.getValue()); - spProperties.add(overridenSPproperty); - } else { - ServiceProviderProperty additionalProperty = new ServiceProviderProperty(); - additionalProperty.setName(propertyElement.getKey()); - additionalProperty.setValue(propertyElement.getValue()); - spProperties.add(additionalProperty); - } - } - serviceProvider.setSpProperties(spProperties.toArray(new ServiceProviderProperty[0])); - try { - getApplicationMgmtServiceImpl().updateApplication(serviceProvider, tenantDomain, username); - if (log.isDebugEnabled()) { - log.debug("Successfully updated service provider properties for app " + spAppName); - } - } catch (IdentityApplicationManagementException e) { - String errMsg = "error occurred while updating service provider " + spAppName; - log.error(errMsg); - throw new APIManagementException(errMsg, e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED); - } - - try { - getOAuthAdminService().updateConsumerApplication(oAuthConsumerAppDTO); - if (log.isDebugEnabled()) { - log.debug("Successfully updated oAuth application DTO for app " + spAppName); - } - } catch (IdentityOAuthAdminException e) { - String errMsg = "error occurred while updating oAuth Application data for app " + spAppName; - log.error(errMsg); - throw new APIManagementException(errMsg, e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED); - } - - } catch (IdentityApplicationManagementException | IdentityOAuthAdminException e) { - String errMsg = "error occurred in retrieving service provider or oAuth app " + spAppName; - log.error(errMsg); - throw new APIManagementException(errMsg, e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED); - } - - } - - /** - * Extract values for additional properties defined in the config from database and add to oAuthApplicationInfo. - * - * @return oAuth application Info - */ - protected OAuthApplicationInfo updateAdditionalProperties(OAuthApplicationInfo oAuthApplicationInfo, - List spProperties) { - - Map> keyManagerAdditionalProperties = OpenBankingConfigParser.getInstance() - .getKeyManagerAdditionalProperties(); - for (String key : keyManagerAdditionalProperties.keySet()) { - for (ServiceProviderProperty spProperty : spProperties) { - if (spProperty.getName().equalsIgnoreCase(key)) { - ((HashMap) oAuthApplicationInfo.getParameter( - APIConstants.JSON_ADDITIONAL_PROPERTIES)).put(key, spProperty.getValue()); - } - } - } - return oAuthApplicationInfo; - } - - /** - * Validate additional properties at toolkit level. - * - * @param obAdditionalProperties Values for additional property list defined in the config - * @throws APIManagementException when failed to validate a given property - */ - @Generated(message = "Excluding from code coverage since the method body is at toolkit") - public void validateAdditionalProperties(Map obAdditionalProperties) - throws APIManagementException { - - OBKeyManagerExtensionInterface obKeyManagerExtensionImpl = KeyManagerUtil.getOBKeyManagerExtensionImpl(); - if (obKeyManagerExtensionImpl != null) { - obKeyManagerExtensionImpl.validateAdditionalProperties(obAdditionalProperties); - } - } - - /** - * Do changes to app request before creating the app at toolkit level. - * - * @param additionalProperties Values for additional property list defined in the config - * @throws APIManagementException when failed to validate a given property - */ - @Generated(message = "Excluding from code coverage since the method body is at toolkit") - public void doPreCreateApplication(OAuthAppRequest oAuthAppRequest, HashMap additionalProperties) - throws APIManagementException { - OBKeyManagerExtensionInterface obKeyManagerExtensionImpl = KeyManagerUtil.getOBKeyManagerExtensionImpl(); - if (obKeyManagerExtensionImpl != null) { - obKeyManagerExtensionImpl.doPreCreateApplication(oAuthAppRequest, additionalProperties); - } - } - - /** - * Do changes to app request before updating the app at toolkit level. - * - * @param additionalProperties Values for additional property list defined in the config - * @throws APIManagementException when failed to validate a given property - */ - @Generated(message = "Excluding from code coverage since the method body is at toolkit") - public void doPreUpdateApplication(OAuthAppRequest oAuthAppRequest, HashMap additionalProperties, - ServiceProvider serviceProvider) throws APIManagementException { - OBKeyManagerExtensionInterface obKeyManagerExtensionImpl = KeyManagerUtil.getOBKeyManagerExtensionImpl(); - if (obKeyManagerExtensionImpl != null) { - obKeyManagerExtensionImpl.doPreUpdateApplication(oAuthAppRequest, additionalProperties, serviceProvider); - } - } - - /** - * Do changes to service provider before updating the service provider properties. - * - * @param oAuthConsumerAppDTO oAuth application DTO - * @param serviceProvider Service provider application - * @param isCreateApp Whether this function is called at app creation - * @throws APIManagementException when failed to validate a given property - */ - @Generated(message = "Excluding from code coverage since the method body is at toolkit") - public void doPreUpdateSpApp(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO oAuthConsumerAppDTO, - ServiceProvider serviceProvider, - HashMap additionalProperties, boolean isCreateApp) - throws APIManagementException { - - OBKeyManagerExtensionInterface obKeyManagerExtensionImpl = KeyManagerUtil.getOBKeyManagerExtensionImpl(); - if (obKeyManagerExtensionImpl != null) { - obKeyManagerExtensionImpl.doPreUpdateSpApp(oAuthConsumerAppDTO, serviceProvider, additionalProperties, - isCreateApp); - } - } - - @Generated(message = "Added for unit testing purposes") - protected ApplicationManagementServiceImpl getApplicationMgmtServiceImpl() { - - return ApplicationManagementServiceImpl.getInstance(); - } - - @Generated(message = "Added for unit testing purposes") - protected OAuthAdminService getOAuthAdminService() { - return new OAuthAdminService(); - } - - protected ServiceProviderProperty getSpPropertyFromSPMetaData(String propertyName, - ServiceProviderProperty[] spProperties) { - - return Arrays.asList(spProperties).stream().filter(serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase(propertyName)).findAny().orElse(null); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/internal/KeyManagerDataHolder.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/internal/KeyManagerDataHolder.java deleted file mode 100644 index 0e35ac0e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/internal/KeyManagerDataHolder.java +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager.internal; - -import org.apache.axis2.AxisFault; -import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; -import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub; -import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.user.mgt.stub.UserAdminStub; - -import java.util.HashMap; -import java.util.Map; - -/** - * Data holder for key manager client extension. - */ -public class KeyManagerDataHolder { - - private APIManagerConfigurationService apiManagerConfigurationService; - private static volatile KeyManagerDataHolder instance; - private static final String IDENTITY_APPLICATION_MGT_SERVICE = "IdentityApplicationManagementService"; - public static final String AUTHENTICATION_ADMIN_SERVICE = "AuthenticationAdmin"; - public static final String USER_ADMIN_SERVICE = "UserAdmin"; - public static final String OAUTH_ADMIN_SERVICE = "OAuthAdminService"; - private AuthenticationAdminStub authenticationAdminStub; - private OAuthAdminServiceStub oAuthAdminServiceStub; - private UserAdminStub userAdminStub; - private String backendServerURL = ""; - private RealmService realmService; - private Map keyManagerConnectorConfigurationMap = new HashMap<>(); - - public static KeyManagerDataHolder getInstance() { - - if (instance == null) { - synchronized (KeyManagerDataHolder.class) { - if (instance == null) { - instance = new KeyManagerDataHolder(); - } - } - } - return instance; - } - - public UserAdminStub getUserAdminStub() throws AxisFault { - - if (userAdminStub == null) { - String userAdminServiceURL = backendServerURL + USER_ADMIN_SERVICE; - userAdminStub = new UserAdminStub(userAdminServiceURL); - } - return userAdminStub; - } - - public void setUserAdminStub(UserAdminStub userAdminStub) { - - this.userAdminStub = userAdminStub; - } - - public AuthenticationAdminStub getAuthenticationAdminStub() throws AxisFault { - - if (authenticationAdminStub == null) { - String authenticationServiceURL = backendServerURL + AUTHENTICATION_ADMIN_SERVICE; - authenticationAdminStub = new AuthenticationAdminStub(authenticationServiceURL); - } - - return authenticationAdminStub; - } - - public void setAuthenticationAdminStub(AuthenticationAdminStub authenticationAdminStub) { - - this.authenticationAdminStub = authenticationAdminStub; - } - - public OAuthAdminServiceStub getOauthAdminServiceStub() throws AxisFault { - - if (oAuthAdminServiceStub == null) { - String oauthAdminServiceURL = backendServerURL + OAUTH_ADMIN_SERVICE; - oAuthAdminServiceStub = new OAuthAdminServiceStub(oauthAdminServiceURL); - } - return oAuthAdminServiceStub; - } - - - public void setOauthAdminServiceStub(OAuthAdminServiceStub oAuthAdminServiceStub) { - - this.oAuthAdminServiceStub = oAuthAdminServiceStub; - } - - public void setApiManagerConfiguration(APIManagerConfigurationService apiManagerConfigurationService) { - - this.apiManagerConfigurationService = apiManagerConfigurationService; - backendServerURL = apiManagerConfigurationService.getAPIManagerConfiguration() - .getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL); - - } - - public APIManagerConfigurationService getApiManagerConfigurationService() { - - return apiManagerConfigurationService; - } - - public String getBackendServerURL() { - - return backendServerURL; - } - - public void addKeyManagerConnectorConfiguration(String type, - KeyManagerConnectorConfiguration keyManagerConnectorConfiguration) { - - keyManagerConnectorConfigurationMap.put(type, keyManagerConnectorConfiguration); - } - - public void removeKeyManagerConnectorConfiguration(String type) { - - keyManagerConnectorConfigurationMap.remove(type); - } - - public KeyManagerConnectorConfiguration getKeyManagerConnectorConfiguration(String type) { - - return keyManagerConnectorConfigurationMap.get(type); - } - - public Map getKeyManagerConnectorConfigurations() { - - return keyManagerConnectorConfigurationMap; - } - - public RealmService getRealmService() { - - if (realmService == null) { - throw new RuntimeException("Realm Service is not available. Component did not start correctly."); - } - return realmService; - } - - void setRealmService(RealmService realmService) { - - this.realmService = realmService; - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/internal/KeyManagerServiceComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/internal/KeyManagerServiceComponent.java deleted file mode 100644 index 993a8320..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/java/com/wso2/openbanking/accelerator/keymanager/internal/KeyManagerServiceComponent.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.user.core.service.RealmService; - -import java.util.Map; - -/** - * Service component for key manager client. - */ -@Component( - name = "com.wso2.open.banking.keymanager", - immediate = true -) -public class KeyManagerServiceComponent { - - private static final Log log = LogFactory.getLog(KeyManagerServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - log.debug("Open banking key manager extension component is activated "); - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - log.debug("Open banking key manager extension is deactivated "); - } - - @Reference( - service = APIManagerConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unSetAPIMConfigs" - ) - public void setAPIMConfig(APIManagerConfigurationService apManagerConfigurationService) { - - KeyManagerDataHolder.getInstance().setApiManagerConfiguration(apManagerConfigurationService); - } - - public void unSetAPIMConfigs(APIManagerConfigurationService apManagerConfigurationService) { - - KeyManagerDataHolder.getInstance().setApiManagerConfiguration(apManagerConfigurationService); - } - - /** - * Initialize the KeyManager Connector configuration Service Service dependency. - * - * @param keyManagerConnectorConfiguration {@link KeyManagerConnectorConfiguration} service reference. - */ - @Reference( - name = "keyManager.connector.service", - service = KeyManagerConnectorConfiguration.class, - cardinality = ReferenceCardinality.MULTIPLE, - policy = ReferencePolicy.DYNAMIC, - unbind = "removeKeyManagerConnectorConfiguration") - protected void addKeyManagerConnectorConfiguration( - KeyManagerConnectorConfiguration keyManagerConnectorConfiguration) { - - KeyManagerDataHolder.getInstance() - .addKeyManagerConnectorConfiguration(keyManagerConnectorConfiguration.getType(), - keyManagerConnectorConfiguration); - - } - - /** - * De-reference the JWTTransformer service. - * - * @param keyManagerConnectorConfiguration - */ - protected void removeKeyManagerConnectorConfiguration( - KeyManagerConnectorConfiguration keyManagerConnectorConfiguration, Map properties) { - if (properties.containsKey(APIConstants.KeyManager.KEY_MANAGER_TYPE)) { - String type = (String) properties.get(APIConstants.KeyManager.KEY_MANAGER_TYPE); - KeyManagerDataHolder.getInstance().removeKeyManagerConnectorConfiguration(type); - } - } - - @Reference( - name = "realm.service", - service = RealmService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRealmService" - ) - protected void setRealmService(RealmService realmService) { - - log.debug("Setting the Realm Service"); - KeyManagerDataHolder.getInstance().setRealmService(realmService); - } - - protected void unsetRealmService(RealmService realmService) { - - log.debug("UnSetting the Realm Service"); - KeyManagerDataHolder.getInstance().setRealmService(null); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/resources/findbugs-include.xml deleted file mode 100644 index f04bf7e4..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,34 +0,0 @@ - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerTest.java deleted file mode 100644 index 565e0d5b..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerTest.java +++ /dev/null @@ -1,521 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.util.ServiceProviderUtils; -import com.wso2.openbanking.accelerator.keymanager.internal.KeyManagerDataHolder; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.OperationContext; -import org.apache.axis2.context.ServiceContext; -import org.apache.axis2.transport.http.HTTPConstants; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.model.AccessTokenInfo; -import org.wso2.carbon.apimgt.api.model.AccessTokenRequest; -import org.wso2.carbon.apimgt.api.model.ConfigurationDto; -import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration; -import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; -import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl; -import org.wso2.carbon.identity.oauth.OAuthAdminService; -import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceIdentityOAuthAdminException; -import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub; -import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO; -import org.wso2.carbon.user.mgt.stub.UserAdminStub; - -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -/** - * Test class for KeyManager. - */ -@PrepareForTest({OpenBankingConfigParser.class, APIManagementException.class, ServiceProviderUtils.class}) -@PowerMockIgnore("jdk.internal.reflect.*") -public class KeyManagerTest extends PowerMockTestCase { - - @Mock - private OAuthAdminServiceStub oAuthAdminServiceStub; - - @Mock - private AuthenticationAdminStub authenticationAdminStub; - - @Mock - private UserAdminStub userAdminStub; - - @Mock - private KeyManagerDataHolder keyManagerDataHolder; - - @Mock - private ServiceClient serviceClient; - - @Mock - private OperationContext operationContext; - - @Mock - private ServiceContext serviceContext; - - @Mock - private APIManagerConfiguration config; - - @Mock - private APIManagerConfigurationService apiManagerConfigurationService; - - @InjectMocks - OBKeyManagerImpl obKeyManager = new OBKeyManagerImpl(); - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - @Mock - ApplicationManagementServiceImpl applicationManagementServiceImpl; - - @Mock - OAuthAdminService oAuthAdminService; - - @Mock - ServiceProviderUtils serviceProviderUtils; - - @Mock - org.wso2.carbon.identity.application.common.model.ServiceProvider serviceProvider; - - @Mock - org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO oAuthConsumerAppDTO; - - String dummyPropertyName1 = "dummyName1"; - String dummyPropertyName2 = "dummyName2"; - String dummyValue1 = "dummyValue1"; - String dummyValue2 = "dummyValue2"; - - String defaultPropertyName1 = "defaultName1"; - String defaultPropertyName2 = "defaultName2"; - String defaultValue1 = "defaultValue1"; - String defaultValue2 = "defaultValue2"; - - String dummyString = "dummyString"; - - Map property = new HashMap<>(); - - @BeforeClass - public void init() { - - MockitoAnnotations.initMocks(this); - } - - @BeforeMethod() - public void before() { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - openBankingConfigParser = PowerMockito.mock(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void testGetNewApplicationAccessToken() throws APIManagementException, RemoteException, - OAuthAdminServiceIdentityOAuthAdminException, - LoginAuthenticationExceptionException, IdentityApplicationManagementException { - - OBKeyManagerImpl obKeyManager = spy(new OBKeyManagerImplMock()); - OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); - oAuthConsumerAppDTO.setApplicationName("AppName"); - - AccessTokenRequest tokenRequest = new AccessTokenRequest(); - tokenRequest.setClientId("0001"); - - ServiceProvider serviceProvider = new ServiceProvider(); - ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty(); - serviceProviderProperty.setDisplayName(OpenBankingConstants.REGULATORY); - serviceProviderProperty.setName(OpenBankingConstants.REGULATORY); - serviceProviderProperty.setValue("true"); - ServiceProviderProperty[] spPropertyArray = new ServiceProviderProperty[1]; - spPropertyArray[0] = serviceProviderProperty; - serviceProvider.setSpProperties(spPropertyArray); - - KeyManagerDataHolder.getInstance().setUserAdminStub(userAdminStub); - Options userAdminOptions = new Options(); - userAdminOptions.setManageSession(true); - userAdminOptions.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, "sessionCookie"); - - Mockito.when(userAdminStub._getServiceClient()).thenReturn(serviceClient); - Mockito.when(serviceClient.getOptions()).thenReturn(userAdminOptions); - Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(config); - Mockito.when(config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL)).thenReturn("KmBackEndURL"); - KeyManagerDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfigurationService); - KeyManagerDataHolder.getInstance().setAuthenticationAdminStub(authenticationAdminStub); - KeyManagerDataHolder.getInstance().setOauthAdminServiceStub(oAuthAdminServiceStub); - - AccessTokenRequest accessTokenRequest = new AccessTokenRequest(); - - Mockito.when(keyManagerDataHolder.getApiManagerConfigurationService()) - .thenReturn(apiManagerConfigurationService); - Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(config); - Mockito.when(config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME)).thenReturn("userName"); - Mockito.when(config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD)).thenReturn("password"); - - Mockito.when(keyManagerDataHolder.getAuthenticationAdminStub()).thenReturn(authenticationAdminStub); - Mockito.when(authenticationAdminStub.login(anyString(), anyString(), anyString())).thenReturn(true); - Mockito.when(authenticationAdminStub._getServiceClient()).thenReturn(serviceClient); - Mockito.when(serviceClient.getLastOperationContext()).thenReturn(operationContext); - Mockito.when(operationContext.getServiceContext()).thenReturn(serviceContext); - Mockito.when(serviceContext.getProperty(HTTPConstants.COOKIE_STRING)).thenReturn("cookie"); - - Mockito.when(keyManagerDataHolder.getOauthAdminServiceStub()).thenReturn(oAuthAdminServiceStub); - Mockito.when(oAuthAdminServiceStub._getServiceClient()).thenReturn(serviceClient); - Mockito.when(oAuthAdminServiceStub.getOAuthApplicationData(anyString())) - .thenReturn(oAuthConsumerAppDTO); - - Mockito.when(obKeyManager.getApplicationMgmtServiceImpl()).thenReturn(applicationManagementServiceImpl); - Mockito.when(applicationManagementServiceImpl.getServiceProviderByClientId( - anyString(), anyString(), anyString())).thenReturn(serviceProvider); - AccessTokenInfo accessTokenInfo = obKeyManager.getNewApplicationAccessToken(accessTokenRequest); - Assert.assertTrue(accessTokenInfo == null); - - } - - @Test(description = "Add the values for additional properties defined in the config to oAuthApplicationInfo") - public void testUpdateAdditionalProperties() { - - Map> keyManagerAdditionalProperties = new HashMap<>(); - keyManagerAdditionalProperties.put(dummyPropertyName1, property); - keyManagerAdditionalProperties.put(dummyPropertyName2, property); - - when(openBankingConfigParser.getKeyManagerAdditionalProperties()).thenReturn(keyManagerAdditionalProperties); - spy(ServiceProvider.class); - - List spProperties = - new ArrayList<>(); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty1 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty2 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - spProperty1.setName(dummyPropertyName1); - spProperty1.setValue(dummyValue1); - spProperty2.setName(dummyPropertyName2); - spProperty2.setValue(dummyValue2); - - spProperties.add(spProperty1); - spProperties.add(spProperty2); - - HashMap additionalProperties = new HashMap<>(); - additionalProperties.put(defaultPropertyName1, defaultValue1); - additionalProperties.put(defaultPropertyName2, defaultValue2); - - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - oAuthApplicationInfo.addParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES, - additionalProperties); - oAuthApplicationInfo = obKeyManager.updateAdditionalProperties(oAuthApplicationInfo, spProperties); - - additionalProperties.put(dummyPropertyName1, dummyValue1); - additionalProperties.put(dummyPropertyName2, dummyValue2); - - Assert.assertEquals(additionalProperties, (HashMap) oAuthApplicationInfo. - getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES)); - } - - @Test - public void testUpdateSpProperties() throws Exception { - - OBKeyManagerImpl obKeyManager = spy(new OBKeyManagerImplMock()); - - Mockito.when(obKeyManager.getApplicationMgmtServiceImpl()).thenReturn(applicationManagementServiceImpl); - Mockito.when(obKeyManager.getOAuthAdminService()).thenReturn(oAuthAdminService); - Mockito.when(oAuthAdminService.getOAuthApplicationDataByAppName(Mockito.anyString())) - .thenReturn(oAuthConsumerAppDTO); - - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty[] spProperties = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty[2]; - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty1 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty2 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - spProperty1.setName(defaultPropertyName1); - spProperty1.setValue(defaultValue1); - spProperty2.setName(defaultPropertyName2); - spProperty2.setValue(defaultValue2); - - spProperties[0] = (spProperty1); - spProperties[1] = (spProperty2); - - ServiceProvider serviceProvider = spy(ServiceProvider.class); - doNothing().when(applicationManagementServiceImpl).updateApplication(Mockito.anyObject(), Mockito.anyString(), - Mockito.anyString()); - - serviceProvider.setSpProperties(spProperties); - serviceProvider.setApplicationName(dummyString); - - Mockito.when(applicationManagementServiceImpl.getServiceProvider(dummyString, dummyString)) - .thenReturn(serviceProvider); - - String overriddenDummyValue = "overriddenDummyValue"; - HashMap additionalProperties = new HashMap<>(); - additionalProperties.put(dummyPropertyName1, dummyValue1); - additionalProperties.put(dummyPropertyName2, dummyValue2); - additionalProperties.put(defaultPropertyName2, overriddenDummyValue); - - List updatedSpProperties = - new ArrayList<>(Arrays.asList(spProperties)); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty3 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty4 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty5 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - spProperty3.setName(dummyPropertyName1); - spProperty3.setValue(dummyValue1); - spProperty4.setName(dummyPropertyName2); - spProperty4.setValue(dummyValue2); - spProperty5.setName(defaultPropertyName2); - spProperty5.setValue(overriddenDummyValue); - - updatedSpProperties.add(spProperty3); - updatedSpProperties.add(spProperty4); - updatedSpProperties.remove(spProperty2); - updatedSpProperties.add(spProperty5); - - org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO oAuthConsumerAppDTOdummy = - new org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO(); - ServiceProvider serviceProviderDummy = new ServiceProvider(); - HashMap dummyMap = new HashMap<>(); - - doNothing().when(obKeyManager).doPreUpdateSpApp(oAuthConsumerAppDTOdummy, serviceProviderDummy, dummyMap, - true); - - obKeyManager.updateSpProperties( - dummyString, dummyString, dummyString, additionalProperties, true); - - List - updatedSpPropertiesFromFunction = new ArrayList<>(Arrays.asList(serviceProvider.getSpProperties())); - - // Two sp property arrays have same sp property elements but as different object. Therefore, - // their comparison needs to be explicitly done - Assert.assertTrue(compareSpPropertyList(updatedSpProperties, updatedSpPropertiesFromFunction)); - } - - /** - * Compare two arraylist for equality of size and equality of the attributes of each object in the array. - * - * @param originalList original list - * @param comparedList compared list - * @return whether elements in the array are equal or not - */ - private Boolean compareSpPropertyList(List originalList, List comparedList) { - - if (originalList.size() != comparedList.size()) { - return false; - } else { - int equalElementCount = 0; - for (org.wso2.carbon.identity.application.common.model.ServiceProviderProperty originalProperty - : originalList) { - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty updatedProperty - = comparedList.stream().filter(serviceProviderProperty -> serviceProviderProperty.getName() - .equalsIgnoreCase(originalProperty.getName())).findAny().orElse(null); - if (originalProperty.getValue() == updatedProperty.getValue()) { - equalElementCount++; - } - } - return originalList.size() == equalElementCount; - } - } - - @DataProvider - public Object[][] validateOAuthAppCreationPropertiesDataProvider() { - - Map> keyManagerAdditionalProperties = new HashMap<>(); - keyManagerAdditionalProperties.put(dummyPropertyName1, property); - keyManagerAdditionalProperties.put(dummyPropertyName2, property); - - Map> keyManagerWithoutAdditionalProperties = new HashMap<>(); - - List applicationConfigurationsList = new ArrayList(); - ConfigurationDto optionalApplicationConfiguration = new ConfigurationDto(dummyPropertyName1, - dummyPropertyName1, "", "", APIConstants.KeyManager.NOT_APPLICABLE_VALUE, true, false, - Collections.EMPTY_LIST, false); - ConfigurationDto mandatoryApplicationConfiguration = new ConfigurationDto(dummyPropertyName2, - dummyPropertyName2, "", "", APIConstants.KeyManager.NOT_APPLICABLE_VALUE, false, false, - Collections.EMPTY_LIST, false); - // Configurations defined in the config - applicationConfigurationsList - .add(optionalApplicationConfiguration); - applicationConfigurationsList - .add(mandatoryApplicationConfiguration); - - List applicationConfigurationsListWithCorrectDefaultValue = new ArrayList(); - ConfigurationDto applicationConfigurationWithCorrectDefaultValue = new ConfigurationDto(dummyPropertyName1, - dummyPropertyName1, "", "", "500", false, false, - Collections.EMPTY_LIST, false); - applicationConfigurationsListWithCorrectDefaultValue.add(applicationConfigurationWithCorrectDefaultValue); - - // Input values for properties from the UI - String inputJsonWithValuesForMandatoryProperties = - "{\"dummyName1\" : \"dummyValue1\" , \"dummyName2\" : \"dummyValue2\"}"; - String inputJsonWithoutValuesForMandatoryProperties = "{\"dummyName2\" : \"dummyValue2\"}"; - String inputNonJsonStringForAdditionalProperties = "dummy string"; - // Only N/A or numbers greater than zero are allowed for additional property values if they are not defined - // separately in config - String inputJsonWithIncorrectValueForDefaultProperties = - "{\"dummyName1\" : \"dummyValue1\" , \"dummyName2\" : \"dummyValue2\"}"; - String inputJsonWithCorrectValueForDefaultProperties = "{\"dummyName1\" : \"800\"}"; - String inputJsonWithEmptyValueForDefaultProperties = "{\"dummyName1\" : \"\"}"; - String inputJsonWithIncorrectNumberValueForDefaultProperties = "{\"dummyName1\" : \"-800\"}"; - String inputWithInvalidJsonString = "\"dummyName1\" : \"-800\""; - - return new Object[][]{ - {keyManagerAdditionalProperties, applicationConfigurationsList, - inputJsonWithValuesForMandatoryProperties, null}, - {keyManagerAdditionalProperties, applicationConfigurationsList, - inputJsonWithoutValuesForMandatoryProperties, APIManagementException.class}, - {keyManagerAdditionalProperties, applicationConfigurationsList, - inputWithInvalidJsonString, APIManagementException.class}, - {keyManagerAdditionalProperties, applicationConfigurationsList, - inputNonJsonStringForAdditionalProperties, APIManagementException.class}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, - inputJsonWithIncorrectValueForDefaultProperties, APIManagementException.class}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, - inputJsonWithIncorrectValueForDefaultProperties, APIManagementException.class}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, - inputJsonWithCorrectValueForDefaultProperties, null}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, - inputJsonWithCorrectValueForDefaultProperties, null}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, - inputJsonWithIncorrectNumberValueForDefaultProperties, APIManagementException.class}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, null, null}, - {keyManagerWithoutAdditionalProperties, applicationConfigurationsList, - inputJsonWithEmptyValueForDefaultProperties, null} - }; - } - - @Test(dataProvider = "validateOAuthAppCreationPropertiesDataProvider", - description = "Validate user inputs for application creation") - public void testValidateOAuthAppCreationProperties(Map> - keyManagerAdditionalProperties, - List applicationConfigurationsList, - String valuesForProperties, - Class exceptionType) { - - try { - Mockito.when(openBankingConfigParser.getKeyManagerAdditionalProperties()) - .thenReturn(keyManagerAdditionalProperties); - KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = - mock(KeyManagerConnectorConfiguration.class); - KeyManagerDataHolder.getInstance().addKeyManagerConnectorConfiguration(obKeyManager.getType(), - keyManagerConnectorConfiguration); - - Mockito.when(keyManagerDataHolder.getKeyManagerConnectorConfiguration(obKeyManager.getType())) - .thenReturn(keyManagerConnectorConfiguration); - Mockito.when(keyManagerConnectorConfiguration.getApplicationConfigurations()) - .thenReturn(applicationConfigurationsList); - - String dummyString = "dummy"; - - mockStatic(ServiceProviderUtils.class); - Mockito.when(serviceProviderUtils.getSpTenantDomain(dummyString)).thenReturn(dummyString); - OBKeyManagerImpl obKeyManager = spy(new OBKeyManagerImplMock()); - - Mockito.when(obKeyManager.getApplicationMgmtServiceImpl()).thenReturn(applicationManagementServiceImpl); - Mockito.when(applicationManagementServiceImpl.getServiceProvider(dummyString, dummyString)) - .thenReturn(serviceProvider); - - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - oAuthApplicationInfo.addParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES, - valuesForProperties); - - obKeyManager.validateOAuthAppCreationProperties(oAuthApplicationInfo); - Assert.assertTrue(exceptionType == null); - } catch (Exception e) { - Assert.assertEquals(e.getClass(), exceptionType); - } - } - - @Test - public void testGetSpPropertyFromSPMetaData() { - - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty[] spProperties = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty[2]; - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty1 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty spProperty2 = - new org.wso2.carbon.identity.application.common.model.ServiceProviderProperty(); - spProperty1.setName(defaultPropertyName1); - spProperty1.setValue(defaultValue1); - spProperty2.setName(defaultPropertyName2); - spProperty2.setValue(defaultValue2); - - spProperties[0] = (spProperty1); - spProperties[1] = (spProperty2); - - org.wso2.carbon.identity.application.common.model.ServiceProviderProperty property = - obKeyManager.getSpPropertyFromSPMetaData(defaultPropertyName1, spProperties); - - Assert.assertTrue(property != null); - } - -} - -class OBKeyManagerImplMock extends OBKeyManagerImpl { - - @Override - protected OAuthAdminService getOAuthAdminService() { - - return mock(OAuthAdminService.class); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerUtilTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerUtilTest.java deleted file mode 100644 index 193c8064..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/java/com/wso2/openbanking/accelerator/keymanager/KeyManagerUtilTest.java +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.keymanager; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.keymanager.internal.KeyManagerDataHolder; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.model.OAuthAppRequest; -import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -/** - * Test class for KeyManagerUtil. - */ -@PrepareForTest({OpenBankingConfigParser.class, KeyManagerDataHolder.class, IdentityTenantUtil.class}) -@PowerMockIgnore("jdk.internal.reflect.*") -public class KeyManagerUtilTest extends PowerMockTestCase { - - String dummyPropertyName1 = "dummyName1"; - String dummyPropertyName2 = "dummyName2"; - String dummyValue1 = "dummyValue1"; - String dummyValue2 = "dummyValue2"; - - Map property = new HashMap<>(); - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - @Mock - RealmService realmService; - - @Mock - private KeyManagerDataHolder keyManagerDataHolder; - - @Mock - private APIManagerConfigurationService apiManagerConfigurationService; - - @Mock - private APIManagerConfiguration config; - - @Mock - private UserRealm userRealm; - - @Mock - private AbstractUserStoreManager abstractUserStoreManager; - - @Mock - private RealmConfiguration realmConfiguration; - - @BeforeClass - public void init() { - - MockitoAnnotations.initMocks(this); - } - - @BeforeMethod() - public void before() { - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - openBankingConfigParser = PowerMockito.mock(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()) - .thenReturn(openBankingConfigParser); - - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - - @Test - public void getEmptyOBKeyManagerExtensionImplTest() throws APIManagementException { - - when(openBankingConfigParser.getOBKeyManagerExtensionImpl()) - .thenReturn(""); - Assert.assertNull(KeyManagerUtil.getOBKeyManagerExtensionImpl()); - } - - @Test - public void getCorrectOBKeyManagerExtensionImplTest() throws APIManagementException { - - when(openBankingConfigParser.getOBKeyManagerExtensionImpl()) - .thenReturn("com.wso2.openbanking.accelerator.keymanager.OBKeyManagerImpl"); - Assert.assertTrue(KeyManagerUtil.getOBKeyManagerExtensionImpl() instanceof OBKeyManagerImpl); - } - - @Test(description = "Get the value from the JSON input for the properties defined in the config") - public void testGetValuesForAdditionalProperties() throws Exception { - - Map> keyManagerAdditionalProperties = new HashMap<>(); - keyManagerAdditionalProperties.put(dummyPropertyName1, property); - keyManagerAdditionalProperties.put(dummyPropertyName2, property); - - PowerMockito.when(openBankingConfigParser.getKeyManagerAdditionalProperties()) - .thenReturn(keyManagerAdditionalProperties); - - HashMap result = new HashMap<>(); - result.put(dummyPropertyName1, dummyValue1); - result.put(dummyPropertyName2, dummyValue2); - - OAuthAppRequest oAuthAppRequest = new OAuthAppRequest(); - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - oAuthApplicationInfo.addParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES, - "{\"dummyName1\" : \"dummyValue1\" , \"dummyName2\" : \"dummyValue2\"}"); - oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo); - - Assert.assertEquals(result, KeyManagerUtil.getValuesForAdditionalProperties(oAuthAppRequest)); - } - - @Test(description = "Get the value from the invalid JSON input for the properties defined in the config") - public void testGetValuesForAdditionalPropertiesFailure() { - - Map> keyManagerAdditionalProperties = new HashMap<>(); - keyManagerAdditionalProperties.put(dummyPropertyName1, property); - keyManagerAdditionalProperties.put(dummyPropertyName2, property); - - PowerMockito.when(openBankingConfigParser.getKeyManagerAdditionalProperties()) - .thenReturn(keyManagerAdditionalProperties); - - HashMap result = new HashMap<>(); - result.put(dummyPropertyName1, dummyValue1); - result.put(dummyPropertyName2, dummyValue2); - - OAuthAppRequest oAuthAppRequest = new OAuthAppRequest(); - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - oAuthApplicationInfo.addParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES, - "\"dummyName1\" : \"dummyValue1\" , \"dummyName2\" : \"dummyValue2\""); - oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo); - try { - KeyManagerUtil.getValuesForAdditionalProperties(oAuthAppRequest); - } catch (Exception e) { - Assert.assertEquals(e.getClass(), APIManagementException.class); - } - - } - - @Test(description = "Add existing role to admin") - private void testAddExistingApplicationRoleToAdmin() throws UserStoreException, APIManagementException { - - int dummyTenantId = 1; - mockStatic(IdentityTenantUtil.class); - mockStatic(KeyManagerDataHolder.class); - PowerMockito.when(IdentityTenantUtil.getTenantId(Mockito.anyString())).thenReturn(dummyTenantId); - - when(KeyManagerDataHolder.getInstance()).thenReturn(keyManagerDataHolder); - Mockito.when(keyManagerDataHolder.getApiManagerConfigurationService()) - .thenReturn(apiManagerConfigurationService); - Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(config); - Mockito.when(config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME)).thenReturn("userName"); - - PowerMockito.when(keyManagerDataHolder.getRealmService()).thenReturn(realmService); - PowerMockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm); - PowerMockito.when(userRealm.getUserStoreManager()).thenReturn(abstractUserStoreManager); - - Mockito.when(abstractUserStoreManager.isUserInRole(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - KeyManagerUtil.addApplicationRoleToAdmin("dummy"); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/resources/testng.xml deleted file mode 100644 index b62f8f57..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.keymanager/src/test/resources/testng.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/pom.xml deleted file mode 100644 index 1b934f36..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - - com.wso2.openbanking.accelerator.runtime - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../pom.xml - - - 4.0.0 - com.wso2.openbanking.accelerator.runtime.identity.authn.filter - jar - WSO2 Open Banking - Identity Authentication Filter - Proxy Filter Which Invokes OAuth Client Authenticators - - - - org.apache.cxf - cxf-core - - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth - provided - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.client.authn.filter - provided - - - org.springframework - spring-web - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - provided - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/src/main/java/com/wso2/openbanking/accelerator/runtime/identity/authn/filter/OBOAuthClientAuthenticatorProxy.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/src/main/java/com/wso2/openbanking/accelerator/runtime/identity/authn/filter/OBOAuthClientAuthenticatorProxy.java deleted file mode 100644 index e38d8398..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/src/main/java/com/wso2/openbanking/accelerator/runtime/identity/authn/filter/OBOAuthClientAuthenticatorProxy.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.runtime.identity.authn.filter; - -import com.wso2.openbanking.accelerator.identity.common.IdentityServiceExporter; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.cxf.jaxrs.impl.MetadataMap; -import org.apache.cxf.message.Message; -import org.wso2.carbon.identity.oauth.client.authn.filter.OAuthClientAuthenticatorProxy; -import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes; -import org.wso2.carbon.identity.oauth.common.OAuthConstants; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -/** - * JAX-RS interceptor which intercepts requests. This interceptor will act as a proxy for OAuth2 Client Authenticators. - * This will pick correct authenticator which can handle OAuth client authentication and engage it. - */ -public class OBOAuthClientAuthenticatorProxy extends OAuthClientAuthenticatorProxy { - - private static final Log log = LogFactory.getLog(OBOAuthClientAuthenticatorProxy.class); - private static final String HTTP_REQUEST = "HTTP.REQUEST"; - private OAuthClientAuthnService oAuthClientAuthnService; - - /** - * Handles the incoming JAX-RS message for the purpose of OAuth2 client authentication. - * - * @param message JAX-RS message - */ - @Override - public void handleMessage(Message message) { - - Map bodyContentParams = getContentParams(message); - HttpServletRequest request = ((HttpServletRequest) message.get(HTTP_REQUEST)); - if (oAuthClientAuthnService == null) { - oAuthClientAuthnService = IdentityServiceExporter.getOAuthClientAuthnService(); - } - OAuthClientAuthnContext oAuthClientAuthnContext = oAuthClientAuthnService.authenticateClient(request, - bodyContentParams); - if (!oAuthClientAuthnContext.isPreviousAuthenticatorEngaged()) { - oAuthClientAuthnContext.setErrorCode(OAuth2ErrorCodes.INVALID_CLIENT); - oAuthClientAuthnContext.setErrorMessage("Unsupported client authentication mechanism"); - } - setContextToRequest(request, oAuthClientAuthnContext); - } - - /** - * Retrieve body content as a String, List map. - * - * @param message JAX-RS incoming message - * @return Body parameter of the incoming request message - */ - protected Map getContentParams(Message message) { - - Map contentMap = new HashMap<>(); - List contentList = message.getContent(List.class); - contentList.forEach(item -> { - if (item instanceof MetadataMap) { - MetadataMap metadataMap = (MetadataMap) item; - metadataMap.forEach((key, value) -> { - if (key instanceof String && value instanceof List) { - contentMap.put((String) key, (List) value); - } - }); - } - }); - return contentMap; - } - - /** - * Set client authentication context to the request. - * - * @param request - Request - * @param oAuthClientAuthnContext - Context - */ - private void setContextToRequest(HttpServletRequest request, OAuthClientAuthnContext oAuthClientAuthnContext) { - - log.debug("Setting OAuth client authentication context to request"); - request.setAttribute(OAuthConstants.CLIENT_AUTHN_CONTEXT, - oAuthClientAuthnContext); - } - -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/src/main/resources/findbugs-include.xml deleted file mode 100644 index 649d044e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/com.wso2.openbanking.accelerator.runtime.identity.authn.filter/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/pom.xml deleted file mode 100644 index edc3b4c5..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.runtime/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - - 4.0.0 - com.wso2.openbanking.accelerator.runtime - WSO2 Open Banking - Runtime Components - pom - - - com.wso2.openbanking.accelerator.runtime.identity.authn.filter - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/pom.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/pom.xml deleted file mode 100644 index b80a60de..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/pom.xml +++ /dev/null @@ -1,191 +0,0 @@ - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../pom.xml - - - com.wso2.openbanking.accelerator.service.activator - bundle - WSO2 Open Banking - Service Activator Component - - - - org.wso2.carbon - org.wso2.carbon.core - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - - - org.testng - testng - test - - - org.mockito - mockito-all - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - org.jacoco - jacoco-maven-plugin - - - - **/ServiceRegisterComponent.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.80 - - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.service.activator.internal, - - - org.osgi.framework; version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component; version="${osgi.service.component.imp.pkg.version.range}", - - - !com.wso2.openbanking.accelerator.service.activator.internal, - com.wso2.openbanking.accelerator.service.activator.*; version="${project.version}", - - * - <_dsannotations>* - - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/OBServiceObserver.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/OBServiceObserver.java deleted file mode 100644 index a274c661..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/OBServiceObserver.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.service.activator; - -/** - * OBServiceObserver - *

- * When the ServiceActivator OSGI bundle is activated, the implementations of OBServiceObserver interface - * will get notified. Once implemented add the FQN of the implemented class to the configuration. - */ -public interface OBServiceObserver { - - void activate(); -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceObservable.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceObservable.java deleted file mode 100644 index f5c881d6..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceObservable.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.service.activator.internal; - -import com.wso2.openbanking.accelerator.service.activator.OBServiceObserver; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * ServiceObservable. - *

- * Maintains one-to-many dependency with OBServiceObservers in such a way that whenever ServiceActivator - * OSGI bundle changes its status to ACTIVE, the dependents get notified - */ -public class ServiceObservable { - - private static volatile ServiceObservable instance; - private final List obServiceObservers; - - private ServiceObservable() { - this.obServiceObservers = new ArrayList<>(); - } - - public static ServiceObservable getInstance() { - if (instance == null) { - synchronized (ServiceObservable.class) { - if (instance == null) { - instance = new ServiceObservable(); - } - } - } - return instance; - } - - public synchronized void registerServiceObserver(OBServiceObserver obServiceObserver) { - this.obServiceObservers.add(obServiceObserver); - } - - public synchronized void activateAllServiceObservers() { - this.obServiceObservers.parallelStream() - .filter(Objects::nonNull) - .forEach(OBServiceObserver::activate); - - this.obServiceObservers.clear(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceRegisterComponent.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceRegisterComponent.java deleted file mode 100644 index 656e196f..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceRegisterComponent.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.service.activator.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.service.activator.OBServiceObserver; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; - -import java.util.Objects; - -/** - * ServiceRegisterComponent. - * - * OSGI Component class to register and activate subscriber (observer) classes - */ -@Component -public class ServiceRegisterComponent { - - private static final Log LOG = LogFactory.getLog(ServiceRegisterComponent.class); - - @Activate - protected void activate(ComponentContext context) { - ServiceObservable serviceObservable = ServiceObservable.getInstance(); - - OpenBankingConfigParser.getInstance().getServiceActivatorSubscribers() - .stream() - .map(this::getInstanceFromFQN) - .filter(Objects::nonNull) - .forEach(serviceObservable::registerServiceObserver); - - serviceObservable.activateAllServiceObservers(); - LOG.debug("All OB service observers are activated"); - } - - @Deactivate - protected void deactivate(ComponentContext context) { - LOG.debug("Metadata Updater bundle is deactivated"); - } - - private OBServiceObserver getInstanceFromFQN(String fqn) { - try { - return (OBServiceObserver) Class.forName(fqn).newInstance(); - } catch (ClassNotFoundException e) { - LOG.error("Unable to find the OBServiceObserver class implementation", e); - } catch (InstantiationException | IllegalAccessException e) { - LOG.error("Error occurred while loading the OBServiceObserver class implementation", e); - } - return null; - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/test/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceObservableTest.java b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/test/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceObservableTest.java deleted file mode 100644 index 7e4a8d79..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/test/java/com/wso2/openbanking/accelerator/service/activator/internal/ServiceObservableTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.service.activator.internal; - -import com.wso2.openbanking.accelerator.service.activator.OBServiceObserver; -import org.mockito.Mockito; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -/** - * ServiceObservableTest. - *

- * Tests for ServiceObservable class - */ -public class ServiceObservableTest { - - ServiceObservable uut; - - @BeforeClass - public void init() { - uut = ServiceObservable.getInstance(); - } - - @Test - public void testActivateAllServiceObservers() { - OBServiceObserver obServiceObserverMock = Mockito.mock(OBServiceObserver.class); - Mockito.doNothing().when(obServiceObserverMock).activate(); - OBServiceObserver obServiceObserverMock1 = Mockito.mock(OBServiceObserver.class); - Mockito.doNothing().when(obServiceObserverMock1).activate(); - - uut.registerServiceObserver(obServiceObserverMock); - uut.registerServiceObserver(obServiceObserverMock1); - uut.activateAllServiceObservers(); - - Mockito.verify(obServiceObserverMock, Mockito.times(1)).activate(); - Mockito.verify(obServiceObserverMock1, Mockito.times(1)).activate(); - } -} diff --git a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/test/resources/testng.xml b/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/test/resources/testng.xml deleted file mode 100644 index 77515f81..00000000 --- a/open-banking-accelerator/components/com.wso2.openbanking.accelerator.service.activator/src/test/resources/testng.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/pom.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/pom.xml deleted file mode 100644 index 61986ede..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/pom.xml +++ /dev/null @@ -1,251 +0,0 @@ - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - - com.wso2.openbanking.accelerator.consent.extensions - bundle - WSO2 Open Banking - Consent Extensions - - - - net.minidev - json-smart - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - - - commons-logging - commons-logging - - - org.testng - testng - test - - - org.mockito - mockito-all - test - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.service - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.dao - provided - - - org.quartz-scheduler.wso2 - quartz - ${quartz.version} - - - org.powermock - powermock-api-mockito - - - org.powermock - powermock-module-testng - - - org.wso2.carbon.identity.local.auth.api - org.wso2.carbon.identity.local.auth.api.core - - - org.slf4j - slf4j-api - - - provided - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push.common - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.event.notifications.service - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.jacoco - jacoco-maven-plugin - - - - **/*Constants.class - **/*Component.class - **/*DataHolder.class - **/*Exception.class - **/*Step.class - **/*Data.class - **/*Builder.class - **/*ConsentExtensionExporter.class - **/*ConsentValidationResult.class - **/*ConsentValidator.class - **/*Default.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.consent.extensions.internal - - - com.wso2.openbanking.accelerator.common.*;version="${project.version}", - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - net.minidev.json.*;version="${json-smart}", - javax.servlet.http; version="${imp.pkg.version.javax.servlet}", - com.wso2.openbanking.accelerator.consent.mgt.service.*;version="${project.version}", - - - !com.wso2.openbanking.accelerator.consent.extensions.internal, - com.wso2.openbanking.accelerator.consent.extensions.*;version="${project.version}", - - - * - <_dsannotations>* - - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/builder/ConsentAdminBuilder.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/builder/ConsentAdminBuilder.java deleted file mode 100644 index d2ce9137..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/builder/ConsentAdminBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.admin.builder; - -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.consent.extensions.admin.model.ConsentAdminHandler; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Builder class for consent admin handler. - */ -public class ConsentAdminBuilder { - - private static final Log log = LogFactory.getLog(ConsentAdminBuilder.class); - private ConsentAdminHandler consentAdminHandler = null; - private static String adminBuilderConfigPath = "Consent.AdminHandler"; - - public void build() { - - String handlerConfig = (String) ConsentExtensionsDataHolder.getInstance().getOpenBankingConfigurationService(). - getConfigurations().get(adminBuilderConfigPath); - consentAdminHandler = (ConsentAdminHandler) OpenBankingUtils.getClassInstanceFromFQN(handlerConfig); - - log.debug("Admin handler loaded successfully"); - } - - public ConsentAdminHandler getConsentAdminHandler() { - return consentAdminHandler; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/impl/DefaultConsentAdminHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/impl/DefaultConsentAdminHandler.java deleted file mode 100644 index 85c236a8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/impl/DefaultConsentAdminHandler.java +++ /dev/null @@ -1,417 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.admin.impl; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.admin.model.ConsentAdminData; -import com.wso2.openbanking.accelerator.consent.extensions.admin.model.ConsentAdminHandler; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.util.jobs.ExpiredConsentStatusUpdateJob; -import com.wso2.openbanking.accelerator.consent.extensions.util.jobs.RetentionDatabaseSyncJob; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventNotificationPersistenceServiceHandler; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Map; - -/** - * Consent admin handler default implementation. - */ -public class DefaultConsentAdminHandler implements ConsentAdminHandler { - private static final Log log = LogFactory.getLog(DefaultConsentAdminHandler.class); - private static final String AUTHORISED = "authorised"; - private static final String FETCH_FROM_RETENTION_DB_QUERY_PARAM = "fetchFromRetentionDatabase"; - - @Override - public void handleSearch(ConsentAdminData consentAdminData) throws ConsentException { - - JSONObject response = new JSONObject(); - - ArrayList consentIDs = null; - ArrayList clientIDs = null; - ArrayList consentTypes = null; - ArrayList consentStatuses = null; - ArrayList userIDs = null; - Long fromTime = null; - Long toTime = null; - Integer limit = null; - Integer offset = null; - boolean fetchFromRetentionDatabase = false; - - Map queryParams = consentAdminData.getQueryParams(); - - if (validateAndGetQueryParam(queryParams, "consentIDs") != null) { - consentIDs = new ArrayList<>(Arrays.asList(validateAndGetQueryParam(queryParams, "consentIDs"). - split(","))); - } - if (validateAndGetQueryParam(queryParams, "clientIDs") != null) { - clientIDs = new ArrayList<>(Arrays.asList(validateAndGetQueryParam(queryParams, "clientIDs"). - split(","))); - } - if (validateAndGetQueryParam(queryParams, "consentTypes") != null) { - consentTypes = new ArrayList<>(Arrays.asList(validateAndGetQueryParam(queryParams, "consentTypes"). - split(","))); - } - if (validateAndGetQueryParam(queryParams, "consentStatuses") != null) { - consentStatuses = new ArrayList<>(Arrays.asList(validateAndGetQueryParam(queryParams, "consentStatuses"). - split(","))); - - } - if (validateAndGetQueryParam(queryParams, "userIDs") != null) { - userIDs = new ArrayList<>(Arrays.asList(validateAndGetQueryParam(queryParams, "userIDs"). - split(","))); - } - if (validateAndGetQueryParam(queryParams, "fromTime") != null) { - try { - fromTime = Long.parseLong(validateAndGetQueryParam(queryParams, "fromTime")); - } catch (NumberFormatException e) { - log.error("Number format incorrect in search for parameter fromTime. Ignoring parameter"); - } - } - if (validateAndGetQueryParam(queryParams, "toTime") != null) { - try { - toTime = Long.parseLong(validateAndGetQueryParam(queryParams, "toTime")); - } catch (NumberFormatException e) { - log.error("Number format incorrect in search for parameter toTime. Ignoring parameter"); - } - } - if (validateAndGetQueryParam(queryParams, "limit") != null) { - try { - limit = Integer.parseInt(validateAndGetQueryParam(queryParams, "limit")); - } catch (NumberFormatException e) { - log.error("Number format incorrect in search for parameter limit. Ignoring parameter"); - } - } - if (validateAndGetQueryParam(queryParams, "offset") != null) { - try { - offset = Integer.parseInt(validateAndGetQueryParam(queryParams, "offset")); - } catch (NumberFormatException e) { - log.error("Number format incorrect in search for parameter offset. Ignoring parameter"); - } - } - if (validateAndGetQueryParam(queryParams, FETCH_FROM_RETENTION_DB_QUERY_PARAM) != null) { - fetchFromRetentionDatabase = Boolean.parseBoolean(validateAndGetQueryParam(queryParams, - FETCH_FROM_RETENTION_DB_QUERY_PARAM)); - } - int count, total = 0; - - try { - ArrayList results = ConsentExtensionsDataHolder.getInstance() - .getConsentCoreService().searchDetailedConsents(consentIDs, clientIDs, consentTypes, - consentStatuses, userIDs, fromTime, toTime, limit, offset, fetchFromRetentionDatabase); - JSONArray searchResults = new JSONArray(); - for (DetailedConsentResource result : results) { - searchResults.add(ConsentExtensionUtils.detailedConsentToJSON(result)); - } - response.appendField("data", searchResults); - count = searchResults.size(); - total = results.size(); - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - - //retrieve the total of the data set queried - if (limit != null || offset != null) { - try { - ArrayList results = ConsentExtensionsDataHolder.getInstance() - .getConsentCoreService().searchDetailedConsents(consentIDs, clientIDs, consentTypes, - consentStatuses, userIDs, fromTime, toTime, null, null, fetchFromRetentionDatabase); - total = results.size(); - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } - - JSONObject metadata = new JSONObject(); - metadata.appendField("count", count); - metadata.appendField("offset", offset); - metadata.appendField("limit", limit); - metadata.appendField("total", total); - - response.appendField("metadata", metadata); - consentAdminData.setResponseStatus(ResponseStatus.OK); - consentAdminData.setResponsePayload(response); - } - - private String validateAndGetQueryParam(Map queryParams, String key) { - if (queryParams.containsKey(key) && (((ArrayList) queryParams.get(key)).get(0) instanceof String)) { - return (String) ((ArrayList) queryParams.get(key)).get(0); - } - return null; - } - - @Override - public void handleRevoke(ConsentAdminData consentAdminData) throws ConsentException { - - try { - Map queryParams = consentAdminData.getQueryParams(); - - String consentId = validateAndGetQueryParam(queryParams, "consentID"); - if (consentId == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Mandatory parameter consent ID not available"); - } else { - ConsentResource consentResource = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .getConsent(consentId, false); - - if (!AUTHORISED.equalsIgnoreCase(consentResource.getCurrentStatus())) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, - "Consent is not in a revocable status"); - } else { - boolean success = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .revokeConsentWithReason(validateAndGetQueryParam(queryParams, "consentID"), "revoked", - validateAndGetQueryParam(queryParams, "userID"), - ConsentCoreServiceConstants.CONSENT_REVOKE_FROM_DASHBOARD_REASON); - if (success) { - // persist a new notification to the DB - // This is a sample event notification persisting. This can be modified in the Toolkit level - if (OpenBankingConfigParser.getInstance().isRealtimeEventNotificationEnabled()) { - JSONObject notificationInfo = new JSONObject(); - notificationInfo.put("consentID", consentId); - notificationInfo.put("status", "Consent Revocation"); - notificationInfo.put("timeStamp", System.currentTimeMillis()); - EventNotificationPersistenceServiceHandler.getInstance().persistRevokeEvent( - consentResource.getClientID(), consentId, - "Consent Revocation", notificationInfo); - } - } - } - } - consentAdminData.setResponseStatus(ResponseStatus.OK); - consentAdminData.setResponseStatus(ResponseStatus.NO_CONTENT); - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Exception occurred while revoking consents"); - } - } - - public void handleConsentAmendmentHistoryRetrieval(ConsentAdminData consentAdminData) throws ConsentException { - - JSONObject response = new JSONObject(); - String consentID = null; - Map queryParams = consentAdminData.getQueryParams(); - - if (validateAndGetQueryParam(queryParams, "consentId") != null) { - consentID = validateAndGetQueryParam(queryParams, "consentId"); - } - - if (StringUtils.isBlank(consentID)) { - log.error("Request missing the mandatory query parameter consentId"); - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Mandatory query parameter consentId " + - "not available"); - } - - int count = 0; - - try { - ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance().getConsentCoreService(); - Map results = consentCoreService.getConsentAmendmentHistoryData(consentID); - - JSONArray consentHistory = new JSONArray(); - for (Map.Entry result : results.entrySet()) { - JSONObject consentResourceJSON = new JSONObject(); - ConsentHistoryResource consentHistoryResource = result.getValue(); - DetailedConsentResource detailedConsentHistory = consentHistoryResource.getDetailedConsentResource(); - consentResourceJSON.appendField("historyId", result.getKey()); - consentResourceJSON.appendField("amendedReason", consentHistoryResource.getReason()); - consentResourceJSON.appendField("amendedTime", detailedConsentHistory.getUpdatedTime()); - consentResourceJSON.appendField("consentData", - ConsentExtensionUtils.detailedConsentToJSON(detailedConsentHistory)); - consentHistory.add(consentResourceJSON); - } - response.appendField("consentID", consentID); - response.appendField("currentConsent", - ConsentExtensionUtils.detailedConsentToJSON(consentCoreService.getDetailedConsent(consentID))); - response.appendField("consentAmendmentHistory", consentHistory); - count = consentHistory.size(); - } catch (ConsentManagementException e) { - log.error("Error while retrieving consent amendment history data", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - - JSONObject metadata = new JSONObject(); - metadata.appendField("amendmentCount", count); - response.appendField("metadata", metadata); - consentAdminData.setResponseStatus(ResponseStatus.OK); - consentAdminData.setResponsePayload(response); - } - - @Override - public void handleConsentExpiry(ConsentAdminData consentAdminData) throws ConsentException { - - try { - ExpiredConsentStatusUpdateJob.updateExpiredStatues(); - consentAdminData.setResponseStatus(ResponseStatus.OK); - consentAdminData.setResponseStatus(ResponseStatus.NO_CONTENT); - } catch (ConsentManagementException e) { - log.error("Error while retrieving expiring consents", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - - } - - @Override - public void handleTemporaryRetentionDataSyncing(ConsentAdminData consentAdminData) throws ConsentException { - - if (OpenBankingConfigParser.getInstance().isRetentionDataDBSyncEnabled()) { - consentAdminData.setResponseStatus(ResponseStatus.BAD_REQUEST); - log.error("Retention data DB sync periodical job is already enabled"); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - "Retention data DB sync periodical job is already enabled"); - } - try { - RetentionDatabaseSyncJob.syncRetentionDatabase(); - consentAdminData.setResponseStatus(ResponseStatus.NO_CONTENT); - } catch (ConsentManagementException e) { - log.error("Error while triggering retention data DB sync method", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } - - @Override - public void handleConsentStatusAuditSearch(ConsentAdminData consentAdminData) throws ConsentException { - - JSONObject response = new JSONObject(); - ArrayList consentIDs = null; - Integer limit = null; - Integer offset = null; - boolean fetchFromRetentionDatabase = false; - - Map queryParams = consentAdminData.getQueryParams(); - - if (validateAndGetQueryParam(queryParams, "consentIDs") != null) { - consentIDs = new ArrayList<>(Arrays.asList(validateAndGetQueryParam(queryParams, "consentIDs"). - split(","))); - } - if (validateAndGetQueryParam(queryParams, "limit") != null) { - try { - limit = Integer.parseInt(validateAndGetQueryParam(queryParams, "limit")); - } catch (NumberFormatException e) { - log.error("Number format incorrect in search for parameter limit. Ignoring parameter"); - } - } - if (validateAndGetQueryParam(queryParams, "offset") != null) { - try { - offset = Integer.parseInt(validateAndGetQueryParam(queryParams, "offset")); - } catch (NumberFormatException e) { - log.error("Number format incorrect in search for parameter offset. Ignoring parameter"); - } - } - if (validateAndGetQueryParam(queryParams, FETCH_FROM_RETENTION_DB_QUERY_PARAM) != null) { - fetchFromRetentionDatabase = Boolean.parseBoolean(validateAndGetQueryParam(queryParams, - FETCH_FROM_RETENTION_DB_QUERY_PARAM)); - } - int count, total = 0; - - try { - ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance().getConsentCoreService(); - ArrayList results = consentCoreService.getConsentStatusAuditRecords(consentIDs, - limit, offset, fetchFromRetentionDatabase); - - JSONArray consentAuditRecords = new JSONArray(); - for (ConsentStatusAuditRecord statusAuditRecord : results) { - JSONObject statusAuditRecordJSON = new JSONObject(); - statusAuditRecordJSON.appendField("statusAuditId", statusAuditRecord.getStatusAuditID()); - statusAuditRecordJSON.appendField("consentId", statusAuditRecord.getConsentID()); - statusAuditRecordJSON.appendField("currentStatus", statusAuditRecord.getCurrentStatus()); - statusAuditRecordJSON.appendField("actionTime", statusAuditRecord.getActionTime()); - statusAuditRecordJSON.appendField("reason", statusAuditRecord.getReason()); - statusAuditRecordJSON.appendField("actionBy", statusAuditRecord.getActionBy()); - statusAuditRecordJSON.appendField("previousStatus", statusAuditRecord.getPreviousStatus()); - consentAuditRecords.add(statusAuditRecordJSON); - } - response.appendField("data", consentAuditRecords); - count = consentAuditRecords.size(); - total = results.size(); - } catch (ConsentManagementException e) { - log.error("Error while retrieving consent status audit data"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - - //retrieve the total of the data set queried - if (limit != null || offset != null) { - try { - ArrayList results = ConsentExtensionsDataHolder.getInstance() - .getConsentCoreService().getConsentStatusAuditRecords(consentIDs, - null, null, fetchFromRetentionDatabase); - total = results.size(); - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } - - JSONObject metadata = new JSONObject(); - metadata.appendField("count", count); - metadata.appendField("offset", offset); - metadata.appendField("limit", limit); - metadata.appendField("total", total); - response.appendField("metadata", metadata); - consentAdminData.setResponseStatus(ResponseStatus.OK); - consentAdminData.setResponsePayload(response); - } - - @Override - public void handleConsentFileSearch(ConsentAdminData consentAdminData) throws ConsentException { - - JSONObject response = new JSONObject(); - String consentID = null; - boolean fetchFromRetentionDatabase = false; - Map queryParams = consentAdminData.getQueryParams(); - - if (validateAndGetQueryParam(queryParams, "consentId") != null) { - consentID = validateAndGetQueryParam(queryParams, "consentId"); - } - - if (StringUtils.isBlank(consentID)) { - log.error("Request missing the mandatory query parameter consentId"); - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Mandatory query parameter consentId " + - "not available"); - } - if (validateAndGetQueryParam(queryParams, FETCH_FROM_RETENTION_DB_QUERY_PARAM) != null) { - fetchFromRetentionDatabase = Boolean.parseBoolean(validateAndGetQueryParam(queryParams, - FETCH_FROM_RETENTION_DB_QUERY_PARAM)); - } - - try { - ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance().getConsentCoreService(); - ConsentFile file = consentCoreService.getConsentFile(consentID, fetchFromRetentionDatabase); - response.appendField("consentFile", file.getConsentFile()); - } catch (ConsentManagementException e) { - log.error("Error while retrieving consent file"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - consentAdminData.setResponseStatus(ResponseStatus.OK); - consentAdminData.setResponsePayload(response); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/model/ConsentAdminData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/model/ConsentAdminData.java deleted file mode 100644 index 39fdf9a4..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/model/ConsentAdminData.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.admin.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import net.minidev.json.JSONObject; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Data wrapper for consent admin data. - */ -public class ConsentAdminData { - - private Map headers; - private JSONObject payload; - private Map queryParams; - private String absolutePath; - private HttpServletRequest request; - private HttpServletResponse response; - private ResponseStatus responseStatus; - private JSONObject responsePayload; - - public ConsentAdminData(Map headers, JSONObject payload, Map queryParams, - String absolutePath, HttpServletRequest request, HttpServletResponse response) { - this.headers = headers; - this.payload = payload; - this.queryParams = queryParams; - this.absolutePath = absolutePath; - this.request = request; - this.response = response; - } - - public ConsentAdminData(Map headers, Map queryParams, String absolutePath, - HttpServletRequest request, HttpServletResponse response) { - this.headers = headers; - payload = null; - this.queryParams = queryParams; - this.absolutePath = absolutePath; - this.request = request; - this.response = response; - } - - - public HttpServletRequest getRequest() { - return request; - } - - public HttpServletResponse getResponse() { - return response; - } - - public Map getQueryParams() { - return queryParams; - } - - public JSONObject getPayload() { - return payload; - } - - public Map getHeaders() { - return headers; - } - - public void setResponseStatus(ResponseStatus responseStatus) { - this.responseStatus = responseStatus; - } - - public void setResponsePayload(JSONObject responsePayload) { - this.responsePayload = responsePayload; - } - - public JSONObject getResponsePayload() { - return responsePayload; - } - - public ResponseStatus getResponseStatus() { - return responseStatus; - } - - public void setResponseHeader(String key, String value) { - response.setHeader(key, value); - } - - public void setResponseHeaders(Map headers) { - for (Map.Entry header : headers.entrySet()) { - setResponseHeader(header.getKey(), header.getValue()); - } - } - - public String getAbsolutePath() { - return absolutePath; - } - - public void setAbsolutePath(String absolutePath) { - this.absolutePath = absolutePath; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/model/ConsentAdminHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/model/ConsentAdminHandler.java deleted file mode 100644 index 65f514bf..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/admin/model/ConsentAdminHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.admin.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; - -/** - * Consent admin handler interface. - */ -public interface ConsentAdminHandler { - - public void handleSearch(ConsentAdminData consentAdminData) throws ConsentException; - - public void handleRevoke(ConsentAdminData consentAdminData) throws ConsentException; - - /** - * This method is used to handle the consent amendment history retrieval request. - * - * @param consentAdminData Data wrapper for consent admin data that holds the request context data - * @throws ConsentException thrown if any error occurs in the process - */ - public void handleConsentAmendmentHistoryRetrieval(ConsentAdminData consentAdminData) throws ConsentException; - - public void handleConsentExpiry(ConsentAdminData consentAdminData) throws ConsentException; - - /** - * Method to handle the temporary retention data syncing with the retention database. - * @param consentAdminData consentAdminData - * @throws ConsentException if any error occurs while syncing the retention database - */ - public void handleTemporaryRetentionDataSyncing(ConsentAdminData consentAdminData) throws ConsentException; - - /** - * Method to handle the consent status audit search. - * @param consentAdminData consentAdminData - * @throws ConsentException if any error occurs while searching the consent status audit - */ - public void handleConsentStatusAuditSearch(ConsentAdminData consentAdminData) throws ConsentException; - - /** - * Method to handle the consent file search. - * @param consentAdminData consentAdminData - * @throws ConsentException if any error occurs while searching the consent file - */ - public void handleConsentFileSearch(ConsentAdminData consentAdminData) throws ConsentException; - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/builder/ConsentStepsBuilder.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/builder/ConsentStepsBuilder.java deleted file mode 100644 index 7a84bf78..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/builder/ConsentStepsBuilder.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.builder; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Builder class for consent steps. - */ -public class ConsentStepsBuilder { - - private static final Log log = LogFactory.getLog(ConsentStepsBuilder.class); - private List consentPersistSteps = null; - private List consentRetrievalSteps = null; - private static final String RETRIEVE = "Retrieve"; - private static final String PERSIST = "Persist"; - - public void build() { - - try { - Map> stepsConfig = - ConsentExtensionsDataHolder.getInstance().getOpenBankingConfigurationService().getAuthorizeSteps(); - Map persistIntegerStringMap = stepsConfig.get(PERSIST); - if (persistIntegerStringMap != null) { - consentPersistSteps = persistIntegerStringMap.keySet().stream() - .map(integer -> (ConsentPersistStep) OpenBankingUtils - .getClassInstanceFromFQN(persistIntegerStringMap.get(integer))) - .collect(Collectors.toList()); - log.debug("Persistence steps loaded successfully"); - } - Map retrieveIntegerStringMap = stepsConfig.get(RETRIEVE); - if (retrieveIntegerStringMap != null) { - consentRetrievalSteps = retrieveIntegerStringMap.keySet().stream() - .map(integer -> (ConsentRetrievalStep) OpenBankingUtils - .getClassInstanceFromFQN(retrieveIntegerStringMap.get(integer))) - .collect(Collectors.toList()); - log.debug("Retrieval steps loaded successfully"); - } - } catch (OpenBankingRuntimeException e) { - log.error("Authorize steps not loaded successfully. Please verify configurations. " + e.getMessage()); - } - } - - public List getConsentPersistSteps() { - return consentPersistSteps; - } - - public List getConsentRetrievalSteps() { - return consentRetrievalSteps; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/CIBAConsentPersistStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/CIBAConsentPersistStep.java deleted file mode 100644 index a7062374..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/CIBAConsentPersistStep.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - package com.wso2.openbanking.accelerator.consent.extensions.authorize.impl; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -/** - * Consent persistence step for CIBA flow. - */ -public class CIBAConsentPersistStep implements ConsentPersistStep { - - @Override - public void execute(ConsentPersistData consentPersistData) throws ConsentException { - - try { - ConsentData consentData = consentPersistData.getConsentData(); - Map sensitiveDataMap = consentData.getSensitiveDataMap(); - - ConsentResource consentResource; - - if (consentData.getConsentResource() == null) { - consentResource = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .getConsent(consentData.getConsentId(), false); - } else { - consentResource = consentData.getConsentResource(); - } - - if (sensitiveDataMap != null) { - //Storing mapping to be used to bind consent id scope for CIBA flows - if (sensitiveDataMap.containsKey("auth_req_id")) { - Map consentAttributes = new HashMap<>(); - consentAttributes.put("auth_req_id", (String) consentData.getSensitiveDataMap().get("auth_req_id")); - ConsentExtensionsDataHolder.getInstance().getConsentCoreService().storeConsentAttributes - (consentResource.getConsentID(), consentAttributes); - } - } - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Exception occured while persisting consent"); - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/CIBAConsentRetrievalStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/CIBAConsentRetrievalStep.java deleted file mode 100644 index b5fe62c8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/CIBAConsentRetrievalStep.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Consent retrieval step for CIBA flow. - */ -public class CIBAConsentRetrievalStep implements ConsentRetrievalStep { - - private static final Log log = LogFactory.getLog(CIBAConsentRetrievalStep.class); - private static final String OPENBANKING_INTENT_ID = "openbanking_intent_id"; - private static final String VALUE = "value"; - - @Override - public void execute(ConsentData consentData, JSONObject jsonObject) throws ConsentException { - - //If query params are null it should be a CIBA flow - // Run this step only if it is a CIBA flow - if (consentData.getSpQueryParams() == null) { - if (consentData.getSensitiveDataMap().containsKey("request")) { - String requestObject = (String) consentData.getSensitiveDataMap().get("request"); - String consentId = validateCibaRequestObjectAndExtractConsentId(requestObject); - consentData.setConsentId(consentId); - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Request object unavailable"); - } - } - - } - - private String validateCibaRequestObjectAndExtractConsentId(String requestObject) { - - String consentId = null; - JSONObject jsonObject = ConsentExtensionUtils.getRequestObjectPayload(requestObject); - - if (jsonObject.containsKey(OPENBANKING_INTENT_ID)) { - JSONObject intentObject = (JSONObject) jsonObject.get(OPENBANKING_INTENT_ID); - if (intentObject.containsKey(VALUE)) { - consentId = (String) intentObject.get(VALUE); - } - } - - if (consentId == null) { - log.error("intent_id not found in request object"); - throw new ConsentException(ResponseStatus.BAD_REQUEST, "intent_id not found in request object"); - } - return consentId; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/DefaultConsentPersistStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/DefaultConsentPersistStep.java deleted file mode 100644 index 47a06698..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/DefaultConsentPersistStep.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.impl; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; - - -/** - * Consent persist step default implementation. - */ -public class DefaultConsentPersistStep implements ConsentPersistStep { - - private static final Log log = LogFactory.getLog(DefaultConsentPersistStep.class); - - @Override - public void execute(ConsentPersistData consentPersistData) throws ConsentException { - - try { - ConsentData consentData = consentPersistData.getConsentData(); - ConsentResource consentResource; - - if (consentData.getConsentId() == null && consentData.getConsentResource() == null) { - log.error("Consent ID not available in consent data"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Consent ID not available in consent data"); - } - - if (consentData.getConsentResource() == null) { - consentResource = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .getConsent(consentData.getConsentId(), false); - } else { - consentResource = consentData.getConsentResource(); - } - - if (consentData.getAuthResource() == null) { - log.error("Auth resource not available in consent data"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Auth resource not available in consent data"); - } - - consentPersist(consentPersistData, consentResource); - - - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Exception occured while persisting consent"); - } - } - - /** - * This method defined to handle consent persistence based on the consent type. - * - * @param consentPersistData Consent Persist Data Object - * @param consentResource Consent Resource Object - * @throws ConsentManagementException - */ - public static void consentPersist(ConsentPersistData consentPersistData, ConsentResource consentResource) - throws ConsentManagementException { - - ConsentData consentData = consentPersistData.getConsentData(); - - JSONObject payload = consentPersistData.getPayload(); - - if (payload.get(ConsentExtensionConstants.ACCOUNT_IDS) == null || - !(payload.get(ConsentExtensionConstants.ACCOUNT_IDS) instanceof JSONArray)) { - log.error(ErrorConstants.ACCOUNT_ID_NOT_FOUND_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.ACCOUNT_ID_NOT_FOUND_ERROR); - } - - JSONArray accountIds = (JSONArray) payload.get(ConsentExtensionConstants.ACCOUNT_IDS); - ArrayList accountIdsString = new ArrayList<>(); - for (Object account : accountIds) { - if (!(account instanceof String)) { - log.error(ErrorConstants.ACCOUNT_ID_FORMAT_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.ACCOUNT_ID_FORMAT_ERROR); - } - accountIdsString.add((String) account); - } - String consentStatus; - - if (consentPersistData.getApproval()) { - consentStatus = ConsentExtensionConstants.AUTHORIZED_STATUS; - } else { - consentStatus = ConsentExtensionConstants.REJECTED_STATUS; - } - - ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .bindUserAccountsToConsent(consentResource, consentData.getUserId(), - consentData.getAuthResource().getAuthorizationID(), accountIdsString, consentStatus, - consentStatus); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/DefaultConsentRetrievalStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/DefaultConsentRetrievalStep.java deleted file mode 100644 index 0deca7b5..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/DefaultConsentRetrievalStep.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.impl; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.utils.ConsentRetrievalUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Consent retrieval step default implementation. - */ -public class DefaultConsentRetrievalStep implements ConsentRetrievalStep { - - private static final Log log = LogFactory.getLog(DefaultConsentRetrievalStep.class); - - @Override - public void execute(ConsentData consentData, JSONObject jsonObject) throws ConsentException { - - if (!consentData.isRegulatory()) { - return; - } - - ConsentCoreServiceImpl consentCoreService = ConsentServiceUtil.getConsentService(); - - try { - // If this is a CIBA flow, consent ID is already set at the CIBAConsentRetrievalStep - String consentId = consentData.getConsentId(); - if (consentId == null) { - // If query params are null, this is a CIBA flow. Therefore consent ID should be set at CIBA consent - // retrieval step - if (consentData.getSpQueryParams() == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "CIBA consent retrieval step has not been " + - "executed successfully before default consent persist step"); - } - String requestObject = ConsentRetrievalUtil.extractRequestObject(consentData.getSpQueryParams()); - consentId = ConsentRetrievalUtil.extractConsentId(requestObject); - consentData.setConsentId(consentId); - } - ConsentResource consentResource = consentCoreService.getConsent(consentId, false); - - if (!consentResource.getCurrentStatus().equals(ConsentExtensionConstants.AWAITING_AUTH_STATUS)) { - log.error("Consent not in authorizable state"); - //Currently throwing error as 400 response. Developer also have the option of appending a field IS_ERROR - // to the jsonObject and showing it to the user in the webapp. If so, the IS_ERROR have to be checked in - // any later steps. - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Consent not in authorizable state"); - } - - AuthorizationResource authorizationResource = ConsentExtensionsDataHolder.getInstance() - .getConsentCoreService().searchAuthorizations(consentId).get(0); - if (!authorizationResource.getAuthorizationStatus().equals(ConsentExtensionConstants.CREATED_STATUS)) { - log.error("Authorization not in authorizable state"); - //Currently throwing error as 400 response. Developer also have the option of appending a field IS_ERROR - // to the jsonObject and showing it to the user in the webapp. If so, the IS_ERROR have to be checked in - // any later steps. - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Authorization not in authorizable state"); - } - - consentData.setType(consentResource.getConsentType()); - consentData.setAuthResource(authorizationResource); - consentData.setConsentResource(consentResource); - - //Appending Consent Data - JSONArray consentDataJSON = getConsentDataSet(consentResource); - jsonObject.appendField(ConsentExtensionConstants.CONSENT_DATA, consentDataJSON); - - //Appending Dummy data for Accounts consent. Ideally should be separate step calling accounts service - JSONArray accountsJSON = ConsentRetrievalUtil.appendDummyAccountID(); - jsonObject.appendField(ConsentExtensionConstants.ACCOUNTS, accountsJSON); - - } catch (ConsentException e) { - JSONObject errorObj = (JSONObject) e.getPayload(); - JSONArray errorList = (JSONArray) errorObj.get("Errors"); - jsonObject.put(ConsentExtensionConstants.IS_ERROR, - ((JSONObject) errorList.get(0)).getAsString("Message")); - return; - } catch (ConsentManagementException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Exception occurred while getting consent data"); - } - } - - /** - * Method to retrieve consent related data from the initiation payload. - * @param consentResource Consent Resource - * @return consent - */ - public JSONArray getConsentDataSet(ConsentResource consentResource) { - - return ConsentRetrievalUtil.getConsentData(consentResource); - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/NonRegulatoryConsentStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/NonRegulatoryConsentStep.java deleted file mode 100644 index 30b0475f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/NonRegulatoryConsentStep.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Default retrieval step to get comprehensive consent. - */ -public class NonRegulatoryConsentStep implements ConsentRetrievalStep { - - private static final String OPENID_SCOPES = "openid_scopes"; - private static final String OPENID = "openid"; - private static final String CONSENT_MGT = "consentmgt"; - private static final String DEFAULT = "default"; - private static final String CONSENT_READ_ALL_SCOPE = "consents:read_all"; - private static final String CONSENT_READ_SELF_SCOPE = "consents:read_self"; - private static final Map CONSENT_SCOPES = new HashMap<>(); - - - @Override - public void execute(ConsentData consentData, JSONObject jsonObject) { - if (consentData.isRegulatory()) { - return; - } - - if (consentData.getScopeString().toLowerCase().contains(CONSENT_MGT)) { - consentData.setType(CONSENT_MGT); - } else if (consentData.getScopeString().contains(OPENID)) { - consentData.setType(DEFAULT); - } - String scopeString = consentData.getScopeString(); - addScopesArray(scopeString, jsonObject); - } - - /** - * Add scopes to json object. - * - * @param scopeString scopes string - * @param jsonObject json object - */ - private void addScopesArray(String scopeString, JSONObject jsonObject) { - - if (StringUtils.isNotBlank(scopeString)) { - // Remove "openid" from the scope list to display. - List openIdScopes = Stream.of(scopeString.split(" ")) - .filter(x -> !StringUtils.equalsIgnoreCase(x, OPENID)) - // if scope found in CONSENT_SCOPES map return meaningful scope value, else return scope - .map(scope -> getConsentScopes().getOrDefault(scope, scope)) - .collect(Collectors.toList()); - JSONArray scopeArray = new JSONArray(); - scopeArray.addAll(openIdScopes); - jsonObject.put(OPENID_SCOPES, scopeArray); - } - } - - protected synchronized Map getConsentScopes() { - if (CONSENT_SCOPES.isEmpty()) { - // Add meaningful string value to scopes - CONSENT_SCOPES.put(CONSENT_READ_ALL_SCOPE, "Manage all consents"); - CONSENT_SCOPES.put(CONSENT_READ_SELF_SCOPE, "Manage your consents"); - } - return CONSENT_SCOPES; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/RequestObjectCheckStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/RequestObjectCheckStep.java deleted file mode 100644 index 3de0a34a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/impl/RequestObjectCheckStep.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.authorize.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.common.AuthErrorCode; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import net.minidev.json.JSONObject; -/** - * Step to check whether the request object is sent in the authorization reques for - * regulatory app. - */ -public class RequestObjectCheckStep implements ConsentRetrievalStep { - - @Override - public void execute(ConsentData consentData, JSONObject jsonObject) throws ConsentException { - - if (consentData.isRegulatory() && !checkRequestObject(consentData.getSpQueryParams())) { - JSONObject json = new JSONObject(); - json.put("error", AuthErrorCode.INVALID_REQUEST.toString()); - json.put("redirect_uri", consentData.getRedirectURI().toString()); - throw new ConsentException(ResponseStatus.BAD_REQUEST, json); - } - } - - private boolean checkRequestObject(String spQueryParams) { - - boolean requestObjectExist = false; - if (spQueryParams != null && !spQueryParams.trim().isEmpty()) { - String requestObject = null; - String[] spQueries = spQueryParams.split("&"); - for (String param : spQueries) { - if (param.contains("request=")) { - requestObjectExist = true; - } - } - } - return requestObjectExist; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentData.java deleted file mode 100644 index ea3efe1b..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentData.java +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.model; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; - -import java.io.Serializable; -import java.net.URI; -import java.util.HashMap; -import java.util.Map; - -/** - * Data wrapper for consent retrieve flow data. - * - */ -public class ConsentData implements Serializable { - - private static final long serialVersionUID = -568639746792395972L; - private String sessionDataKey; - private String userId; - private String spQueryParams; - private String scopeString; - private String application; - private String consentId; - private String clientId; - private Boolean regulatory; - private Map requestHeaders; - private ConsentResource consentResource; - private AuthorizationResource authResource; - private Map metaDataMap; - private Map sensitiveDataMap; - private URI redirectURI; - private String state; - - //Mandatory parameter to be set by extension. This will be considered "DEFAULT" if not set. - private String type; - - public ConsentData(String sessionDataKey, String userId, String spQueryParams, String scopeString, - String application, Map requestHeaders) { - - this.sessionDataKey = sessionDataKey; - this.userId = userId; - this.spQueryParams = spQueryParams; - this.scopeString = scopeString; - this.application = application; - this.requestHeaders = requestHeaders; - this.metaDataMap = new HashMap<>(); - } - - public String getSessionDataKey() { - return sessionDataKey; - } - - public void setSessionDataKey(String sessionDataKey) { - this.sessionDataKey = sessionDataKey; - } - - public String getUserId() { - - return userId; - } - - public void setUserId(String userId) { - - this.userId = userId; - } - - public String getApplication() { - - return application; - } - - public void setApplication(String application) { - - this.application = application; - } - - public String getScopeString() { - - return scopeString; - } - - public void setScopeString(String scopeString) { - - this.scopeString = scopeString; - } - - public String getSpQueryParams() { - - return spQueryParams; - } - - public void setSpQueryParams(String spQueryParams) { - - this.spQueryParams = spQueryParams; - } - - public Map getRequestHeaders() { - return requestHeaders; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public ConsentResource getConsentResource() { - return consentResource; - } - - public void setConsentResource(ConsentResource consentResource) { - this.consentResource = consentResource; - } - - public String getConsentId() { - return consentId; - } - - public void setConsentId(String consentId) { - this.consentId = consentId; - } - - public AuthorizationResource getAuthResource() { - return authResource; - } - - public void setAuthResource(AuthorizationResource authResource) { - this.authResource = authResource; - } - - public Boolean isRegulatory() { - return regulatory; - } - - public void setRegulatory(Boolean regulatory) { - this.regulatory = regulatory; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public Map getMetaDataMap() { - return metaDataMap; - } - - public void setMetaDataMap(Map metaDataMap) { - this.metaDataMap = metaDataMap; - } - - public void addData(String key, Object value) { - - this.metaDataMap.put(key, value); - } - - public void addAllData(Map data) { - - this.metaDataMap.putAll(data); - } - - public URI getRedirectURI() { - return redirectURI; - } - - public void setRedirectURI(URI redirectURI) { - this.redirectURI = redirectURI; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public Map getSensitiveDataMap() { - return sensitiveDataMap; - } - - public void setSensitiveDataMap(Map sensitiveDataMap) { - this.sensitiveDataMap = sensitiveDataMap; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentPersistData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentPersistData.java deleted file mode 100644 index c73455b0..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentPersistData.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.model; - -import net.minidev.json.JSONObject; - -import java.util.HashMap; -import java.util.Map; - -/** - * Data wrapper for consent persist flow data. - */ -public class ConsentPersistData { - - //Payload of the persist request - private JSONObject payload; - //Request headers of the persist request - private Map headers; - //Consent data object used in the retrieval flow populated via a cache - private ConsentData consentData; - //Boolean value representing whether the approval was granted by the user - private boolean approval; - //Additional metadata - private Map metadata; - //Browser cookies - private Map browserCookies; - - public ConsentPersistData(JSONObject payload, Map headers, boolean approval, - ConsentData consentData) { - this.payload = payload; - this.headers = headers; - this.approval = approval; - this.consentData = consentData; - metadata = new HashMap<>(); - browserCookies = new HashMap<>(); - } - - public JSONObject getPayload() { - return payload; - } - - public void setPayload(JSONObject payload) { - this.payload = payload; - } - - public Map getHeaders() { - return headers; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public boolean getApproval() { - return approval; - } - - public void setApproval(boolean approval) { - this.approval = approval; - } - - public ConsentData getConsentData() { - return consentData; - } - - public void setConsentData(ConsentData consentData) { - this.consentData = consentData; - } - - public Map getMetadata() { - return metadata; - } - - public void addMetadata(String key, Object value) { - - this.metadata.put(key, value); - } - - public void addMultipleMetadata(Map data) { - - this.metadata.putAll(data); - } - - public Map getBrowserCookies() { - - return browserCookies; - } - - public void setBrowserCookies(Map cookies) { - - this.browserCookies.putAll(cookies); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentPersistStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentPersistStep.java deleted file mode 100644 index 0b36dffd..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentPersistStep.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; - -/** - * Consent persist step interface. - */ -public interface ConsentPersistStep { - - /** - * Method to be implemented as a step for consent persistence. Once implemented add the step to the configuration. - * - * @param consentPersistData Includes all the generic data of the consents. - * @throws ConsentException Exception thrown in case of failure. - */ - void execute(ConsentPersistData consentPersistData) throws ConsentException; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentRetrievalStep.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentRetrievalStep.java deleted file mode 100644 index 6d4d5cc2..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/model/ConsentRetrievalStep.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.model; - - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import net.minidev.json.JSONObject; - -/** - * Consent retrieval step interface. - */ -public interface ConsentRetrievalStep { - - /** - * Method to be implemented as a step for consent retrieval. Once implemented add the step to the configuration. - * - * @param consentData Includes all the data that is received to the consent page. - * @param jsonObject Passed on through each step where the response body sent to the page is built. - * @throws ConsentException Exception thrown in case of failure. - */ - void execute(ConsentData consentData, JSONObject jsonObject) throws ConsentException; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/utils/ConsentRetrievalUtil.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/utils/ConsentRetrievalUtil.java deleted file mode 100644 index f0cc17b4..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/utils/ConsentRetrievalUtil.java +++ /dev/null @@ -1,700 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.utils; - - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.time.format.DateTimeParseException; -import java.util.Base64; - -/** - * Util class for Consent authorize implementation. - */ -public class ConsentRetrievalUtil { - - private static final Log log = LogFactory.getLog(ConsentRetrievalUtil.class); - - /** - * Method to extract request object from query params. - * - * @param spQueryParams Query params - * @return requestObject - */ - public static String extractRequestObject(String spQueryParams) { - - if (StringUtils.isNotBlank(spQueryParams)) { - String requestObject = null; - String[] spQueries = spQueryParams.split("&"); - for (String param : spQueries) { - if (param.contains("request=")) { - requestObject = (param.substring("request=".length())).replaceAll( - "\\r\\n|\\r|\\n|\\%20", ""); - } - } - if (requestObject != null) { - return requestObject; - } - } - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, ErrorConstants.REQUEST_OBJ_EXTRACT_ERROR); - } - - /** - * Method to validate the request object and extract consent ID. - * - * @param requestObject Request object - * @return consentId - */ - public static String extractConsentId(String requestObject) { - - String consentId = null; - try { - // validate request object and get the payload - String requestObjectPayload; - String[] jwtTokenValues = requestObject.split("\\."); - if (jwtTokenValues.length == ConsentExtensionConstants.NUMBER_OF_PARTS_IN_JWS) { - requestObjectPayload = new String(Base64.getUrlDecoder().decode(jwtTokenValues[1]), - StandardCharsets.UTF_8); - } else { - log.error(ErrorConstants.REQUEST_OBJ_NOT_SIGNED); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.REQUEST_OBJ_NOT_SIGNED); - } - Object payload = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(requestObjectPayload); - if (!(payload instanceof JSONObject)) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.NOT_JSON_PAYLOAD); - } - JSONObject jsonObject = (JSONObject) payload; - - // get consent id from the request object - if (jsonObject.containsKey(ConsentExtensionConstants.CLAIMS)) { - JSONObject claims = (JSONObject) jsonObject.get(ConsentExtensionConstants.CLAIMS); - for (String claim : ConsentExtensionConstants.CLAIM_FIELDS) { - if (claims.containsKey(claim)) { - JSONObject claimObject = (JSONObject) claims.get(claim); - if (claimObject.containsKey(ConsentExtensionConstants.OPENBANKING_INTENT_ID)) { - JSONObject intentObject = (JSONObject) claimObject - .get(ConsentExtensionConstants.OPENBANKING_INTENT_ID); - if (intentObject.containsKey(ConsentExtensionConstants.VALUE)) { - consentId = (String) intentObject.get(ConsentExtensionConstants.VALUE); - break; - } - } - } - } - } - - if (consentId == null) { - log.error(ErrorConstants.INTENT_ID_NOT_FOUND); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.INTENT_ID_NOT_FOUND); - } - return consentId; - - } catch (ParseException e) { - log.error(ErrorConstants.REQUEST_OBJ_PARSE_ERROR, e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, ErrorConstants.REQUEST_OBJ_PARSE_ERROR); - } - } - - - /** - * Check if the expiry date time of the consent has elapsed. - * - * @param expiryDate The expiry date/time of consent - * @return boolean result of validation - */ - public static boolean validateExpiryDateTime(String expiryDate) throws ConsentException { - - try { - OffsetDateTime expDate = OffsetDateTime.parse(expiryDate); - if (log.isDebugEnabled()) { - log.debug(String.format(ErrorConstants.DATE_PARSE_MSG, expDate, OffsetDateTime.now())); - } - return OffsetDateTime.now().isBefore(expDate); - } catch (DateTimeParseException e) { - log.error(ErrorConstants.EXP_DATE_PARSE_ERROR, e); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.ACC_CONSENT_RETRIEVAL_ERROR); - } - } - - /** - * Method to add debtor account details to consent data to send it to the consent page. - * - * @param initiation Initiation object from the request - * @param consentDataJSON Consent information object - */ - public static void populateDebtorAccount(JSONObject initiation, JSONArray consentDataJSON) { - if (initiation.get(ConsentExtensionConstants.DEBTOR_ACC) != null) { - JSONObject debtorAccount = (JSONObject) initiation.get(ConsentExtensionConstants.DEBTOR_ACC); - JSONArray debtorAccountArray = new JSONArray(); - - //Adding Debtor Account Scheme Name - if (debtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME) != null) { - debtorAccountArray.add(ConsentExtensionConstants.SCHEME_NAME_TITLE + " : " + - debtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME)); - } - - //Adding Debtor Account Identification - if (debtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION) != null) { - debtorAccountArray.add(ConsentExtensionConstants.IDENTIFICATION_TITLE + " : " + - debtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION)); - } - - //Adding Debtor Account Name - if (debtorAccount.getAsString(ConsentExtensionConstants.NAME) != null) { - debtorAccountArray.add(ConsentExtensionConstants.NAME_TITLE + " : " + - debtorAccount.getAsString(ConsentExtensionConstants.NAME)); - } - - //Adding Debtor Account Secondary Identification - if (debtorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) != null) { - debtorAccountArray.add(ConsentExtensionConstants.SECONDARY_IDENTIFICATION_TITLE + " : " + - debtorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION)); - } - - - JSONObject jsonElementDebtor = new JSONObject(); - jsonElementDebtor.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.DEBTOR_ACC_TITLE); - jsonElementDebtor.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), debtorAccountArray); - consentDataJSON.add(jsonElementDebtor); - } - } - - - /** - * Method to add debtor account details to consent data to send it to the consent page. - * - * @param initiation Initiation object from the request - * @param consentDataJSON Consent information object - */ - public static void populateCreditorAccount(JSONObject initiation, JSONArray consentDataJSON) { - if (initiation.get(ConsentExtensionConstants.CREDITOR_ACC) != null) { - JSONObject creditorAccount = (JSONObject) initiation.get(ConsentExtensionConstants.CREDITOR_ACC); - JSONArray creditorAccountArray = new JSONArray(); - //Adding Debtor Account Scheme Name - if (creditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME) != null) { - creditorAccountArray.add(ConsentExtensionConstants.SCHEME_NAME_TITLE + " : " + - creditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME)); - } - //Adding Debtor Account Identification - if (creditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION) != null) { - creditorAccountArray.add(ConsentExtensionConstants.IDENTIFICATION_TITLE + " : " + - creditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION)); - } - //Adding Debtor Account Name - if (creditorAccount.getAsString(ConsentExtensionConstants.NAME) != null) { - creditorAccountArray.add(ConsentExtensionConstants.NAME_TITLE + " : " + - creditorAccount.getAsString(ConsentExtensionConstants.NAME)); - } - //Adding Debtor Account Secondary Identification - if (creditorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) != null) { - creditorAccountArray.add(ConsentExtensionConstants.SECONDARY_IDENTIFICATION_TITLE + " : " + - creditorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION)); - } - - JSONObject jsonElementCreditor = new JSONObject(); - jsonElementCreditor.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CREDITOR_ACC_TITLE); - jsonElementCreditor.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - creditorAccountArray); - consentDataJSON.add(jsonElementCreditor); - } - } - - - /** - * Method to append Dummy data for Account ID. Ideally should be separate step calling accounts service - * - * @return accountsJSON - */ - public static JSONArray appendDummyAccountID() { - - JSONArray accountsJSON = new JSONArray(); - JSONObject accountOne = new JSONObject(); - accountOne.appendField("account_id", "12345"); - accountOne.appendField("display_name", "Salary Saver Account"); - - accountsJSON.add(accountOne); - - JSONObject accountTwo = new JSONObject(); - accountTwo.appendField("account_id", "67890"); - accountTwo.appendField("account_id", "67890"); - accountTwo.appendField("display_name", "Max Bonus Account"); - - accountsJSON.add(accountTwo); - - return accountsJSON; - - } - - /** - * Method that consists the implementation for the validation of payload and the consent, - * this method also invokes the relevant methods to populate data for each flow. - * - * @param consentResource Consent Resource parameter containing consent related information retrieved - * from database. - * @return ConsentDataJson array - */ - public static JSONArray getConsentData(ConsentResource consentResource) throws ConsentException { - - JSONArray consentDataJSON = new JSONArray(); - try { - - String receiptString = consentResource.getReceipt(); - Object receiptJSON = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(receiptString); - - // Checking whether the request body is in JSON format - if (!(receiptJSON instanceof JSONObject)) { - log.error(ErrorConstants.NOT_JSON_OBJECT_ERROR); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.NOT_JSON_OBJECT_ERROR); - } - - if (!ConsentExtensionConstants.AWAITING_AUTH_STATUS.equals(consentResource.getCurrentStatus())) { - log.error(ErrorConstants.STATE_INVALID_ERROR); - // Currently throwing an error as a 400 response. - // Developers have the option of appending a field IS_ERROR to the jsonObject - // and showing it to the user in the webapp.If so,the IS_ERROR has to be checked in any later steps. - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.STATE_INVALID_ERROR); - } - - JSONObject receipt = (JSONObject) receiptJSON; - - // Checks if 'data' object is present in the receipt - if (receipt.containsKey(ConsentExtensionConstants.DATA)) { - JSONObject data = (JSONObject) receipt.get(ConsentExtensionConstants.DATA); - - String type = consentResource.getConsentType(); - switch (type) { - case ConsentExtensionConstants.ACCOUNTS: - populateAccountData(data, consentDataJSON); - break; - case ConsentExtensionConstants.PAYMENTS: - populatePaymentData(data, consentDataJSON); - break; - case ConsentExtensionConstants.FUNDSCONFIRMATIONS: - populateCofData(data, consentDataJSON); - break; - case ConsentExtensionConstants.VRP: - populateVRPData(data, consentDataJSON); - break; - default: - break; - } - } else { - log.error(ErrorConstants.DATA_OBJECT_MISSING_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.DATA_OBJECT_MISSING_ERROR); - } - } catch (ParseException e) { - log.error(ErrorConstants.CONSENT_RETRIEVAL_ERROR, e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.CONSENT_RETRIEVAL_ERROR); - } - return consentDataJSON; - } - - /** - * Populate Domestic and international Payment Details. - * - * @param data data request from the request - * @param consentDataJSON Consent information - */ - private static void populatePaymentData(JSONObject data, JSONArray consentDataJSON) { - - JSONArray paymentTypeArray = new JSONArray(); - JSONObject jsonElementPaymentType = new JSONObject(); - - if (data.containsKey(ConsentExtensionConstants.INITIATION)) { - JSONObject initiation = (JSONObject) data.get(ConsentExtensionConstants.INITIATION); - - if (initiation.containsKey(ConsentExtensionConstants.CURRENCY_OF_TRANSFER)) { - //For International Payments - //Adding Payment Type - paymentTypeArray.add(ConsentExtensionConstants.INTERNATIONAL_PAYMENTS); - - jsonElementPaymentType.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.PAYMENT_TYPE_TITLE); - jsonElementPaymentType.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - paymentTypeArray); - consentDataJSON.add(jsonElementPaymentType); - - //Adding Currency Of Transfer - JSONArray currencyTransferArray = new JSONArray(); - currencyTransferArray.add(initiation.getAsString(ConsentExtensionConstants.CURRENCY_OF_TRANSFER)); - - JSONObject jsonElementCurTransfer = new JSONObject(); - jsonElementCurTransfer.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CURRENCY_OF_TRANSFER_TITLE); - jsonElementCurTransfer.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - currencyTransferArray); - consentDataJSON.add(jsonElementCurTransfer); - } else { - //Adding Payment Type - paymentTypeArray.add(ConsentExtensionConstants.DOMESTIC_PAYMENTS); - - jsonElementPaymentType.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.PAYMENT_TYPE_TITLE); - jsonElementPaymentType.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - paymentTypeArray); - consentDataJSON.add(jsonElementPaymentType); - } - - //Adding InstructionIdentification - JSONArray identificationArray = new JSONArray(); - identificationArray.add(initiation.getAsString(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION)); - - JSONObject jsonElementIdentification = new JSONObject(); - jsonElementIdentification.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION_TITLE); - jsonElementIdentification.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - identificationArray); - consentDataJSON.add(jsonElementIdentification); - - //Adding EndToEndIdentification - JSONArray endToEndIdentificationArray = new JSONArray(); - endToEndIdentificationArray - .add(initiation.getAsString(ConsentExtensionConstants.END_TO_END_IDENTIFICATION)); - - JSONObject jsonElementEndToEndIdentification = new JSONObject(); - jsonElementEndToEndIdentification.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.END_TO_END_IDENTIFICATION_TITLE); - jsonElementEndToEndIdentification.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - endToEndIdentificationArray); - consentDataJSON.add(jsonElementEndToEndIdentification); - - //Adding InstructedAmount - JSONObject instructedAmount = (JSONObject) initiation.get(ConsentExtensionConstants.INSTRUCTED_AMOUNT); - JSONArray instructedAmountArray = new JSONArray(); - - if (instructedAmount.getAsString(ConsentExtensionConstants.AMOUNT_TITLE) != null) { - instructedAmountArray.add(ConsentExtensionConstants.AMOUNT_TITLE + " : " + - instructedAmount.getAsString(ConsentExtensionConstants.AMOUNT)); - } - - if (instructedAmount.getAsString(ConsentExtensionConstants.CURRENCY) != null) { - instructedAmountArray.add(ConsentExtensionConstants.CURRENCY_TITLE + " : " + - instructedAmount.getAsString(ConsentExtensionConstants.CURRENCY)); - } - - JSONObject jsonElementInstructedAmount = new JSONObject(); - jsonElementInstructedAmount.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.INSTRUCTED_AMOUNT_TITLE); - jsonElementInstructedAmount.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - instructedAmountArray); - consentDataJSON.add(jsonElementInstructedAmount); - - // Adding Debtor Account - populateDebtorAccount(initiation, consentDataJSON); - // Adding Creditor Account - populateCreditorAccount(initiation, consentDataJSON); - - } - } - - /** - * Populate account Details. - * - * @param data data request from the request - * @param consentDataJSON Consent information - */ - private static void populateAccountData(JSONObject data, JSONArray consentDataJSON) { - - //Adding Permissions - JSONArray permissions = (JSONArray) data.get(ConsentExtensionConstants.PERMISSIONS); - if (permissions != null) { - JSONObject jsonElementPermissions = new JSONObject(); - jsonElementPermissions.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.PERMISSIONS); - jsonElementPermissions.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - permissions); - consentDataJSON.add(jsonElementPermissions); - } - - //Adding Expiration Date Time - String expirationDate = data.getAsString(ConsentExtensionConstants.EXPIRATION_DATE); - if (expirationDate != null) { - if (!ConsentRetrievalUtil.validateExpiryDateTime(expirationDate)) { - log.error(ErrorConstants.CONSENT_EXPIRED); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.CONSENT_EXPIRED); - } - JSONArray expiryArray = new JSONArray(); - expiryArray.add(expirationDate); - - JSONObject jsonElementExpiry = new JSONObject(); - jsonElementExpiry.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.EXPIRATION_DATE_TITLE); - jsonElementExpiry.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - expiryArray); - consentDataJSON.add(jsonElementExpiry); - } - - //Adding Transaction From Date Time - String fromDateTime = data.getAsString(ConsentExtensionConstants.TRANSACTION_FROM_DATE); - if (fromDateTime != null) { - JSONArray fromDateTimeArray = new JSONArray(); - fromDateTimeArray.add(fromDateTime); - - JSONObject jsonElementFromDateTime = new JSONObject(); - jsonElementFromDateTime.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.TRANSACTION_FROM_DATE_TITLE); - jsonElementFromDateTime.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - fromDateTimeArray); - consentDataJSON.add(jsonElementFromDateTime); - } - - //Adding Transaction To Date Time - String toDateTime = data.getAsString(ConsentExtensionConstants.TRANSACTION_TO_DATE); - if (toDateTime != null) { - JSONArray toDateTimeArray = new JSONArray(); - toDateTimeArray.add(toDateTime); - - JSONObject jsonElementToDateTime = new JSONObject(); - jsonElementToDateTime.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.TRANSACTION_TO_DATE_TITLE); - jsonElementToDateTime.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - toDateTimeArray); - consentDataJSON.add(jsonElementToDateTime); - } - } - - /** - * Populate funds confirmation Details. - * - * @param initiation data from the request - * @param consentDataJSON Consent information - */ - private static void populateCofData(JSONObject initiation, JSONArray consentDataJSON) { - - //Adding Expiration Date Time - if (initiation.getAsString(ConsentExtensionConstants.EXPIRATION_DATE) != null) { - - if (!ConsentRetrievalUtil - .validateExpiryDateTime(initiation.getAsString(ConsentExtensionConstants.EXPIRATION_DATE))) { - log.error(ErrorConstants.CONSENT_EXPIRED); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.CONSENT_EXPIRED); - } - - String expiry = initiation.getAsString(ConsentExtensionConstants.EXPIRATION_DATE); - JSONArray expiryArray = new JSONArray(); - expiryArray.add(expiry); - - JSONObject jsonElementExpiry = new JSONObject(); - jsonElementExpiry.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.EXPIRATION_DATE_TITLE); - jsonElementExpiry.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), expiryArray); - consentDataJSON.add(jsonElementExpiry); - } else { - JSONArray expiryArray = new JSONArray(); - expiryArray.add(ConsentExtensionConstants.OPEN_ENDED_AUTHORIZATION); - - JSONObject jsonElementExpiry = new JSONObject(); - jsonElementExpiry.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.EXPIRATION_DATE_TITLE); - jsonElementExpiry.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), expiryArray); - consentDataJSON.add(jsonElementExpiry); - } - - if (initiation.get(ConsentExtensionConstants.DEBTOR_ACC) != null) { - //Adding Debtor Account - populateDebtorAccount(initiation, consentDataJSON); - } - } - - /** - * Populate VRP Details. - * - * @param data Control Parameters from the request - * @param consentDataJSON Consent information object - */ - private static void populateVRPData(JSONObject data, JSONArray consentDataJSON) { - - if (!data.containsKey(ConsentExtensionConstants.CONTROL_PARAMETERS)) { - log.error(ErrorConstants.CONTROL_PARAMETERS_MISSING_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.CONTROL_PARAMETERS_MISSING_ERROR); - } else { - - JSONObject controlParameters = (JSONObject) data. - get(ConsentExtensionConstants.CONTROL_PARAMETERS); - - //Adding Payment Type - JSONArray paymentTypeArray = new JSONArray(); - JSONObject jsonElementPaymentType = new JSONObject(); - paymentTypeArray.add(ConsentExtensionConstants.DOMESTIC_VRP); - jsonElementPaymentType.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.PAYMENT_TYPE_TITLE); - jsonElementPaymentType.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - paymentTypeArray); - consentDataJSON.add(jsonElementPaymentType); - - String validToDateTime = controlParameters.getAsString(ConsentExtensionConstants.VALID_TO_DATE_TIME); - if (validToDateTime != null) { - // Constructing jsonElementValidToDataTime - JSONObject jsonElementValidToDateTime = new JSONObject(); - jsonElementValidToDateTime.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CONTROL_PARAMETER_VALID_TO_DATE_TITLE); - JSONArray dateControlParameterArray = new JSONArray(); - dateControlParameterArray.add((controlParameters). - get(ConsentExtensionConstants.VALID_TO_DATE_TIME)); - jsonElementValidToDateTime.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - dateControlParameterArray); - - consentDataJSON.add(jsonElementValidToDateTime); - } - - String validFromDateTime = controlParameters.getAsString - (ConsentExtensionConstants.VALID_FROM_DATE_TIME); - if (validFromDateTime != null) { - // Constructing jsonElementValidFromDataTime - JSONObject jsonElementValidFromDateTime = new JSONObject(); - jsonElementValidFromDateTime.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CONTROL_PARAMETER_VALID_FROM_DATE_TITLE); - JSONArray dateTimeControlParameterArray = new JSONArray(); - dateTimeControlParameterArray.add((controlParameters). - get(ConsentExtensionConstants.VALID_FROM_DATE_TIME)); - jsonElementValidFromDateTime.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - dateTimeControlParameterArray); - consentDataJSON.add(jsonElementValidFromDateTime); - } - - Object maxAmount = controlParameters.get(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT); - - if (maxAmount instanceof JSONObject) { - JSONObject jsonElementControlParameter = new JSONObject(); - jsonElementControlParameter.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CONTROL_PARAMETER_MAX_INDIVIDUAL_AMOUNT_TITLE); - JSONArray controlParameterArray = new JSONArray(); - - JSONObject maximumIndividualAmount = (JSONObject) maxAmount; - - String formattedAmount = String.format("%s %s", - maximumIndividualAmount.getAsString(ConsentExtensionConstants.CURRENCY), - maximumIndividualAmount.getAsString(ConsentExtensionConstants.AMOUNT)); - controlParameterArray.add(formattedAmount); - jsonElementControlParameter.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - controlParameterArray); - - consentDataJSON.add(jsonElementControlParameter); - } else { - log.error(ErrorConstants.MAX_AMOUNT_NOT_JSON_OBJECT_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.MAX_AMOUNT_NOT_JSON_OBJECT_ERROR); - } - - Object periodicLimit = controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - - if (periodicLimit instanceof JSONArray) { - JSONArray periodicLimitsArrays = (JSONArray) periodicLimit; - - for (Object periodicLimitObject : periodicLimitsArrays) { - if (periodicLimitObject instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) periodicLimitObject; - - Object periodAlignmentObject = jsonObject.get(ConsentExtensionConstants.PERIOD_ALIGNMENT); - - if (periodAlignmentObject instanceof String) { - // Constructing jsonElementPeriodAlignment - JSONObject jsonElementPeriodAlignment = new JSONObject(); - jsonElementPeriodAlignment.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CONTROL_PARAMETER_PERIOD_ALIGNMENT_TITLE); - - JSONArray periodAlignmentArray = new JSONArray(); - periodAlignmentArray.add(periodAlignmentObject); - - jsonElementPeriodAlignment.appendField(StringUtils. - lowerCase(ConsentExtensionConstants.DATA), periodAlignmentArray); - consentDataJSON.add(jsonElementPeriodAlignment); - } else { - log.error(ErrorConstants.PERIOD_ALIGNMENT_NOT_STRING_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.PERIOD_ALIGNMENT_NOT_STRING_ERROR); - } - - Object periodTypeObject = jsonObject.get(ConsentExtensionConstants.PERIOD_TYPE); - - if (periodTypeObject instanceof String) { - - JSONObject jsonElementPeriodType = new JSONObject(); - jsonElementPeriodType.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CONTROL_PARAMETER_PERIOD_TYPE_TITLE); - - JSONArray periodTypeArray = new JSONArray(); - periodTypeArray.add(periodTypeObject); - - jsonElementPeriodType.appendField(StringUtils.lowerCase(ConsentExtensionConstants.DATA), - periodTypeArray); - - consentDataJSON.add(jsonElementPeriodType); - - } else { - log.error(ErrorConstants.PERIOD_TYPE_NOT_STRING_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.PERIOD_TYPE_NOT_STRING_ERROR); - } - // Constructing jsonElementPeriodicLimitsAmountCurrency - periodicLimits amount and currency - Object amount = jsonObject.get(ConsentExtensionConstants.AMOUNT); - Object currency = jsonObject.get(ConsentExtensionConstants.CURRENCY); - - if (amount instanceof String && currency instanceof String) { - String periodTypeString = (String) periodTypeObject; - - JSONObject jsonElementPeriodicLimitsAmountCurrency = new JSONObject(); - jsonElementPeriodicLimitsAmountCurrency.appendField(ConsentExtensionConstants.TITLE, - ConsentExtensionConstants.CONTROL_PARAMETER_AMOUNT_TITLE + - periodTypeString); - - JSONArray periodicLimitsArray = new JSONArray(); - - String amountString = (String) amount; - String currencyString = (String) currency; - - String formattedPeriodicAmount = String.format("%s %s", currencyString, amountString); - periodicLimitsArray.add(formattedPeriodicAmount); - - jsonElementPeriodicLimitsAmountCurrency.appendField(StringUtils. - lowerCase(ConsentExtensionConstants.DATA), periodicLimitsArray); - consentDataJSON.add(jsonElementPeriodicLimitsAmountCurrency); - - } else { - log.error(ErrorConstants.NOT_STRING_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NOT_STRING_ERROR); - } - } - } - } else { - log.error(ErrorConstants.NOT_JSON_ARRAY_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.NOT_JSON_ARRAY_ERROR); - } - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ConsentMgrAuthServletImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ConsentMgrAuthServletImpl.java deleted file mode 100644 index bd53588a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ConsentMgrAuthServletImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Constants; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.model.OBAuthServletInterface; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; - -import static com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Utils.i18n; - - -/** - * ConsentMgrAuthServletImpl - *

- * The consent management implementation of servlet extension that handles self-care portal use cases. - */ -public class ConsentMgrAuthServletImpl implements OBAuthServletInterface { - - @Override - public Map updateRequestAttribute(HttpServletRequest request, JSONObject dataSet, - ResourceBundle resourceBundle) { - - Map updatedRequestData = new HashMap<>(); - - boolean userClaimsConsentOnly = Boolean.parseBoolean(request.getParameter(Constants.USER_CLAIMS_CONSENT_ONLY)); - updatedRequestData.put("userClaimsConsentOnly", userClaimsConsentOnly); - - boolean displayScopes = (boolean) request.getSession().getAttribute("displayScopes"); - if (displayScopes) { - JSONArray openIdScopesArray = dataSet.getJSONArray("openid_scopes"); - if (openIdScopesArray != null) { - List oidScopes = new ArrayList<>(); - for (int scopeIndex = 0; scopeIndex < openIdScopesArray.length(); scopeIndex++) { - oidScopes.add(openIdScopesArray.getString(scopeIndex)); - } - updatedRequestData.put(Constants.OIDC_SCOPES, oidScopes); - } - } - - // Strings - updatedRequestData.put("openidUserClaims", i18n(resourceBundle, "openid.user.claims")); - updatedRequestData.put("requestAccessProfile", i18n(resourceBundle, "request.access.profile")); - updatedRequestData.put("requestedAttributes", i18n(resourceBundle, "requested.attributes")); - updatedRequestData.put("bySelectingFollowingAttributes", - i18n(resourceBundle, "by.selecting.following.attributes")); - updatedRequestData.put("mandatoryClaimsRecommendation", - i18n(resourceBundle, "mandatory.claims.recommendation")); - updatedRequestData.put("continueDefault", i18n(resourceBundle, "continue")); - updatedRequestData.put("deny", i18n(resourceBundle, "deny")); - - return updatedRequestData; - } - - @Generated(message = "ignoring since method doesn't contain a logic") - @Override - public Map updateSessionAttribute(HttpServletRequest request, JSONObject dataSet, - ResourceBundle resourceBundle) { - return new HashMap<>(); - } - - @Generated(message = "ignoring since method doesn't contain a logic") - @Override - public Map updateConsentData(HttpServletRequest request) { - return new HashMap<>(); - } - - @Generated(message = "ignoring since method doesn't contain a logic") - @Override - public Map updateConsentMetaData(HttpServletRequest request) { - return new HashMap<>(); - } - - @Generated(message = "ignoring since method doesn't contain a logic") - @Override - public String getJSPPath() { - return "/default_consent.jsp"; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ISDefaultAuthServletImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ISDefaultAuthServletImpl.java deleted file mode 100644 index 8c60e950..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ISDefaultAuthServletImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Constants; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Utils; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.model.OBAuthServletInterface; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; - -/** - * The default implementation of servlet extension that handles non OB use cases. - * Required in other vanilla auth flows. - */ -public class ISDefaultAuthServletImpl implements OBAuthServletInterface { - - @Override - public Map updateRequestAttribute(HttpServletRequest request, JSONObject dataSet, - ResourceBundle resourceBundle) { - - Map returnMaps = new HashMap<>(); - - // Claims - if (request.getParameter(Constants.REQUESTED_CLAIMS) != null) { - - String[] requestedClaimList = request.getParameter(Constants.REQUESTED_CLAIMS) - .split(Constants.CLAIM_SEPARATOR); - - returnMaps.put("requestedClaims", Utils.splitClaims(requestedClaimList)); - } - - if (request.getParameter(Constants.MANDATORY_CLAIMS) != null) { - String[] mandatoryClaimList = request.getParameter(Constants.MANDATORY_CLAIMS) - .split(Constants.CLAIM_SEPARATOR); - - returnMaps.put("mandatoryClaims", Utils.splitClaims(mandatoryClaimList)); - } - - - // Scopes - /*This parameter decides whether the consent page will only be used to get consent for sharing claims with the - Service Provider. If this param is 'true' and user has already given consents for the OIDC scopes, we will be - hiding the scopes being displayed and the approve always button. - */ - boolean userClaimsConsentOnly = Boolean.parseBoolean(request.getParameter(Constants.USER_CLAIMS_CONSENT_ONLY)); - returnMaps.put("userClaimsConsentOnly", userClaimsConsentOnly); - - List oidScopes = new ArrayList<>(); - boolean displayScopes = (boolean) request.getSession().getAttribute("displayScopes"); - - if (userClaimsConsentOnly) { - // If we are getting consent for user claims only, we don't need to display OIDC scopes in the consent page - } else { - if (displayScopes) { - JSONArray openIdScopesArray = dataSet.getJSONArray("openid_scopes"); - if (openIdScopesArray != null) { - for (int scopeIndex = 0; scopeIndex < openIdScopesArray.length(); scopeIndex++) { - oidScopes.add(openIdScopesArray.getString(scopeIndex)); - } - returnMaps.put(Constants.OIDC_SCOPES, oidScopes); - } - } - } - - - // Strings - returnMaps.put("openidUserClaims", Utils.i18n(resourceBundle, "openid.user.claims")); - returnMaps.put("requestAccessProfile", Utils.i18n(resourceBundle, "request.access.profile")); - returnMaps.put("requestedAttributes", Utils.i18n(resourceBundle, "requested.attributes")); - returnMaps.put("bySelectingFollowingAttributes", - Utils.i18n(resourceBundle, "by.selecting.following.attributes")); - returnMaps.put("mandatoryClaimsRecommendation", - Utils.i18n(resourceBundle, "mandatory.claims.recommendation")); - returnMaps.put("continueDefault", Utils.i18n(resourceBundle, "continue")); - returnMaps.put("deny", Utils.i18n(resourceBundle, "deny")); - - return returnMaps; - - } - - @Override - public Map updateSessionAttribute(HttpServletRequest request, JSONObject dataSet, - ResourceBundle resourceBundle) { - return new HashMap<>(); - } - - @Override - public Map updateConsentData(HttpServletRequest request) { - return new HashMap<>(); - } - - @Override - public Map updateConsentMetaData(HttpServletRequest request) { - return new HashMap<>(); - } - - @Override - public String getJSPPath() { - return "/default_consent.jsp"; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/OBDefaultAuthServletImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/OBDefaultAuthServletImpl.java deleted file mode 100644 index 6e33d788..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/OBDefaultAuthServletImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Utils; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.model.OBAuthServletInterface; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; - -/** - * The default implementation for OB flow. - */ -public class OBDefaultAuthServletImpl implements OBAuthServletInterface { - - private String jspPath; - @Override - public Map updateRequestAttribute(HttpServletRequest request, JSONObject dataSet, - ResourceBundle resourceBundle) { - - String consentType = dataSet.getString("type"); - - //store consent type in a global variable to return required jsp file in getJSPPath() method - jspPath = consentType; - - switch (consentType) { - - case ConsentExtensionConstants.ACCOUNTS: - return Utils.populateAccountsData(request, dataSet); - case ConsentExtensionConstants.PAYMENTS: - return Utils.populatePaymentsData(request, dataSet); - case ConsentExtensionConstants.FUNDSCONFIRMATIONS: - return Utils.populateCoFData(request, dataSet); - case ConsentExtensionConstants.VRP: - return Utils.populateVRPDataRetrieval(request, dataSet); - default: - return new HashMap<>(); - } - } - - @Override - public Map updateSessionAttribute(HttpServletRequest request, JSONObject dataSet, - ResourceBundle resourceBundle) { - - return new HashMap<>(); - } - - @Override - public Map updateConsentData(HttpServletRequest request) { - - Map returnMaps = new HashMap<>(); - - String[] accounts = request.getParameter("accounts[]").split(":"); - returnMaps.put("accountIds", new JSONArray(accounts)); - return returnMaps; - } - - @Override - public Map updateConsentMetaData(HttpServletRequest request) { - - return new HashMap<>(); - } - - @Override - public String getJSPPath() { - - if (jspPath.equalsIgnoreCase(ConsentExtensionConstants.ACCOUNTS) || - jspPath.equalsIgnoreCase(ConsentExtensionConstants.VRP)) { - return "/ob_default.jsp"; - } else { - return "/default_displayconsent.jsp"; - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/util/Constants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/util/Constants.java deleted file mode 100644 index d94f25ca..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/util/Constants.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util; - -/** - * Constants required for auth servlet implementations. - */ -public class Constants { - - private Constants() { - // do not required to create instances - } - - public static final String REQUESTED_CLAIMS = "requestedClaims"; - public static final String MANDATORY_CLAIMS = "mandatoryClaims"; - public static final String CLAIM_SEPARATOR = ","; - public static final String USER_CLAIMS_CONSENT_ONLY = "userClaimsConsentOnly"; - public static final String OIDC_SCOPES = "OIDCScopes"; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/util/Utils.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/util/Utils.java deleted file mode 100644 index 73c6a91b..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/util/Utils.java +++ /dev/null @@ -1,296 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.json.JSONObject; -import org.owasp.encoder.Encode; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; - -/** - * Utility methods. - */ -public class Utils { - - private static final Log log = LogFactory.getLog(Utils.class); - - /** - * To get the property value for the given key from the ResourceBundle. - * Retrieve the value of property entry for key, return key if a value is not found for key - * - * @param resourceBundle ResourceBundle - * @param key Key - * @return Value of the property entry for key - */ - public static String i18n(ResourceBundle resourceBundle, String key) { - - try { - return Encode.forHtml((StringUtils.isNotBlank(resourceBundle.getString(key)) ? - resourceBundle.getString(key) : key)); - } catch (Exception e) { - // Intentionally catching Exception and if something goes wrong while finding the value for key, return - // default, not to break the UI - return Encode.forHtml(key); - } - } - - /** - * Split claims based on a deliminator and create map of claimID and displayName. - * - * @param requestedClaimList Requested claim list - * @return List of claims - */ - public static List> splitClaims(String[] requestedClaimList) { - - List> requestedClaims = new ArrayList<>(); - - for (String claim : requestedClaimList) { - String[] requestedClaimData = claim.split("_", 2); - if (requestedClaimData.length == 2) { - Map data = new HashMap<>(); - data.put("claimId", requestedClaimData[0]); - data.put("displayName", requestedClaimData[1]); - requestedClaims.add(data); - } - } - return requestedClaims; - } - - /** - * Method to populate accounts data to be sent to consent page. - * - * @param request HttpServletRequest - * @param dataSet Request payload JSONObject - * @return Map of Accounts data - */ - public static Map populateAccountsData(HttpServletRequest request, JSONObject dataSet) { - - Map returnMaps = new HashMap<>(); - - //Sets "data_requested" that contains the human-readable scope-requested information - JSONArray dataRequestedJsonArray = dataSet.getJSONArray(ConsentExtensionConstants.CONSENT_DATA); - Map> dataRequested = new LinkedHashMap<>(); - - for (int requestedDataIndex = 0; requestedDataIndex < dataRequestedJsonArray.length(); requestedDataIndex++) { - JSONObject dataObj = dataRequestedJsonArray.getJSONObject(requestedDataIndex); - String title = dataObj.getString(ConsentExtensionConstants.TITLE); - JSONArray dataArray = dataObj.getJSONArray(StringUtils.lowerCase(ConsentExtensionConstants.DATA)); - - ArrayList listData = new ArrayList<>(); - for (int dataIndex = 0; dataIndex < dataArray.length(); dataIndex++) { - listData.add(dataArray.getString(dataIndex)); - } - dataRequested.put(title, listData); - } - returnMaps.put(ConsentExtensionConstants.DATA_REQUESTED, dataRequested); - - // add accounts list - request.setAttribute(ConsentExtensionConstants.ACCOUNT_DATA, addAccList(dataSet)); - request.setAttribute(ConsentExtensionConstants.CONSENT_TYPE, ConsentExtensionConstants.ACCOUNTS); - - return returnMaps; - - } - - /** - * Method to populate payments data to be sent to consent page. - * - * @param request HttpServletRequest - * @param dataSet Request payload JSONObject - * @return Map of Payments data - */ - public static Map populatePaymentsData(HttpServletRequest request, JSONObject dataSet) { - - String selectedAccount = null; - Map returnMaps = new HashMap<>(); - - //Sets "data_requested" that contains the human-readable scope-requested information - JSONArray dataRequestedJsonArray = dataSet.getJSONArray(ConsentExtensionConstants.CONSENT_DATA); - Map> dataRequested = new LinkedHashMap<>(); - - for (int requestedDataIndex = 0; requestedDataIndex < dataRequestedJsonArray.length(); requestedDataIndex++) { - JSONObject dataObj = dataRequestedJsonArray.getJSONObject(requestedDataIndex); - String title = dataObj.getString(ConsentExtensionConstants.TITLE); - JSONArray dataArray = dataObj.getJSONArray(StringUtils.lowerCase(ConsentExtensionConstants.DATA)); - - ArrayList listData = new ArrayList<>(); - for (int dataIndex = 0; dataIndex < dataArray.length(); dataIndex++) { - listData.add(dataArray.getString(dataIndex)); - } - dataRequested.put(title, listData); - } - returnMaps.put(ConsentExtensionConstants.DATA_REQUESTED, dataRequested); - - //Assigning value of the "Debtor Account" key in the map to the variable "selectedAccount". - if (dataRequested.containsKey("Debtor Account")) { - selectedAccount = getDebtorAccFromConsentData(dataRequestedJsonArray); - } else { - // add accounts list - request.setAttribute(ConsentExtensionConstants.ACCOUNT_DATA, addAccList(dataSet)); - } - - request.setAttribute(ConsentExtensionConstants.SELECTED_ACCOUNT, selectedAccount); - request.setAttribute(ConsentExtensionConstants.CONSENT_TYPE, ConsentExtensionConstants.PAYMENTS); - - return returnMaps; - - } - /** - * Method to populate Confirmation of Funds data to be sent to consent page. - * - * @param httpServletRequest HttpServletRequest - * @param dataSet Request payload JSONObject - * @return Map of Confirmation of Funds data - */ - public static Map populateCoFData(HttpServletRequest httpServletRequest, JSONObject dataSet) { - - Map returnMaps = new HashMap<>(); - - //Sets "data_requested" that contains the human-readable scope-requested information - JSONArray dataRequestedJsonArray = dataSet.getJSONArray(ConsentExtensionConstants.CONSENT_DATA); - Map> dataRequested = new LinkedHashMap<>(); - - for (int requestedDataIndex = 0; requestedDataIndex < dataRequestedJsonArray.length(); requestedDataIndex++) { - JSONObject dataObj = dataRequestedJsonArray.getJSONObject(requestedDataIndex); - String title = dataObj.getString(ConsentExtensionConstants.TITLE); - JSONArray dataArray = dataObj.getJSONArray(StringUtils.lowerCase(ConsentExtensionConstants.DATA)); - - ArrayList listData = new ArrayList<>(); - for (int dataIndex = 0; dataIndex < dataArray.length(); dataIndex++) { - listData.add(dataArray.getString(dataIndex)); - } - dataRequested.put(title, listData); - - } - returnMaps.put(ConsentExtensionConstants.DATA_REQUESTED, dataRequested); - - //Assigning value of the "Debtor Account" key in the map to the variable "selectedAccount". - if (dataRequested.containsKey("Debtor Account")) { - httpServletRequest.setAttribute(ConsentExtensionConstants.DEBTOR_ACCOUNT_ID, - getDebtorAccFromConsentData(dataRequestedJsonArray)); - } - - httpServletRequest.setAttribute(ConsentExtensionConstants.CONSENT_TYPE, - ConsentExtensionConstants.FUNDSCONFIRMATIONS); - return returnMaps; - } - - /** - * Method to retrieve debtor account from consent data object. - * - * @param consentDataObject Object containing consent related data - * @return Debtor account - */ - public static String getDebtorAccFromConsentData(JSONArray consentDataObject) { - - for (int requestedDataIndex = 0; requestedDataIndex < consentDataObject.length(); requestedDataIndex++) { - JSONObject dataObj = consentDataObject.getJSONObject(requestedDataIndex); - String title = dataObj.getString(ConsentExtensionConstants.TITLE); - - if (ConsentExtensionConstants.DEBTOR_ACC_TITLE.equals(title)) { - JSONArray dataArray = dataObj.getJSONArray(StringUtils.lowerCase(ConsentExtensionConstants.DATA)); - - for (int dataIndex = 0; dataIndex < dataArray.length(); dataIndex++) { - String data = (String) dataArray.get(dataIndex); - if (data.contains(ConsentExtensionConstants.IDENTIFICATION_TITLE)) { - - //Values are set to the array as {name:value} Strings in Consent Retrieval step, - // hence splitting by : and getting the 2nd element to get the value - return (((String) dataArray.get(dataIndex)).split(":")[1]).trim(); - } - } - } - } - return null; - } - - private static List> addAccList (JSONObject dataSet) { - // add accounts list - List> accountData = new ArrayList<>(); - JSONArray accountsArray = dataSet.getJSONArray("accounts"); - for (int accountIndex = 0; accountIndex < accountsArray.length(); accountIndex++) { - JSONObject object = accountsArray.getJSONObject(accountIndex); - String accountId = object.getString(ConsentExtensionConstants.ACCOUNT_ID); - String displayName = object.getString(ConsentExtensionConstants.DISPLAY_NAME); - Map data = new HashMap<>(); - data.put(ConsentExtensionConstants.ACCOUNT_ID, accountId); - data.put(ConsentExtensionConstants.DISPLAY_NAME, displayName); - accountData.add(data); - } - - return accountData; - } - - /** - * Method to populate vrp data to be sent to consent page. - * - * @param request HttpServletRequest - * @param dataSet Request payload JSONObject - * @return Map of VRP data - */ - public static Map populateVRPDataRetrieval(HttpServletRequest request, JSONObject dataSet) { - - String selectedAccount = null; - Map returnMaps = new HashMap<>(); - - // Populates "consentDataArray" with the scope information in a readable format - JSONArray consentDataArray = dataSet.getJSONArray(ConsentExtensionConstants.CONSENT_DATA); - Map> dataRequested = new LinkedHashMap<>(); - - for (int requestedDataIndex = 0; requestedDataIndex < consentDataArray.length(); requestedDataIndex++) { - JSONObject dataObj = consentDataArray.getJSONObject(requestedDataIndex); - String title = dataObj.getString(ConsentExtensionConstants.TITLE); - JSONArray dataArray = dataObj.getJSONArray(StringUtils.lowerCase(ConsentExtensionConstants.DATA)); - - ArrayList listData = new ArrayList<>(); - for (int dataIndex = 0; dataIndex < dataArray.length(); dataIndex++) { - listData.add(dataArray.getString(dataIndex)); - } - dataRequested.put(title, listData); - } - returnMaps.put(ConsentExtensionConstants.DATA_REQUESTED, dataRequested); - - //Assigning value of the "Debtor Account" key in the map to the variable "selectedAccount". - if (dataRequested.containsKey("Debtor Account")) { - selectedAccount = getDebtorAccFromConsentData(consentDataArray); - } else { - // add accounts list - request.setAttribute(ConsentExtensionConstants.ACCOUNT_DATA, addAccList(dataSet)); - } - - request.setAttribute(ConsentExtensionConstants.SELECTED_ACCOUNT, selectedAccount); - request.setAttribute(ConsentExtensionConstants.CONSENT_TYPE, ConsentExtensionConstants.VRP); - - return returnMaps; - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/model/OBAuthServletInterface.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/model/OBAuthServletInterface.java deleted file mode 100644 index 2c41ffd8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/model/OBAuthServletInterface.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.model; - -import org.json.JSONObject; - -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; - -/** - * The interface to define how the servlet extension should be implemented. - */ -public interface OBAuthServletInterface { - - Map updateRequestAttribute(HttpServletRequest request, - JSONObject dataSet, ResourceBundle resourceBundle); - - Map updateSessionAttribute(HttpServletRequest request, - JSONObject dataSet, ResourceBundle resourceBundle); - - Map updateConsentData(HttpServletRequest request); - - Map updateConsentMetaData(HttpServletRequest request); - - String getJSPPath(); -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticator.java deleted file mode 100644 index 39f665d8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticator.java +++ /dev/null @@ -1,365 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.ciba.authenticator; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.builder.ConsentStepsBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.ciba.model.CIBAAuthenticationEndpointErrorResponse; -import com.wso2.openbanking.accelerator.consent.extensions.common.AuthErrorCode; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentCache; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationContextCache; -import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationContextCacheEntry; -import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationContextCacheKey; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; -import org.wso2.carbon.identity.application.authenticator.push.PushAuthenticator; -import org.wso2.carbon.identity.application.authenticator.push.common.PushAuthContextManager; -import org.wso2.carbon.identity.application.authenticator.push.common.impl.PushAuthContextManagerImpl; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; - -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLDecoder; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - - -/** - * CIBA Push Authenticator for sending push notifications to authentication device. - */ -public class CIBAPushAuthenticator extends PushAuthenticator { - - private static final Log log = LogFactory.getLog(CIBAPushAuthenticator.class); - private static final long serialVersionUID = 6106269076155338045L; - - private static List consentRetrievalSteps = null; - private static List consentPersistSteps = null; - - public CIBAPushAuthenticator() { - initializeConsentSteps(); - } - - @Override - public String getFriendlyName() { - - return CIBAPushAuthenticatorConstants.AUTHENTICATOR_FRIENDLY_NAME; - } - - @Override - public String getName() { - - return CIBAPushAuthenticatorConstants.AUTHENTICATOR_NAME; - } - - /** - * Initialize consent builder. - */ - public static synchronized void initializeConsentSteps() { - - if (consentRetrievalSteps == null || consentPersistSteps == null) { - ConsentStepsBuilder consentStepsBuilder = ConsentExtensionExporter.getConsentStepsBuilder(); - - if (consentStepsBuilder != null) { - consentRetrievalSteps = consentStepsBuilder.getConsentRetrievalSteps(); - consentPersistSteps = consentStepsBuilder.getConsentPersistSteps(); - } - - if (consentRetrievalSteps != null && !consentRetrievalSteps.isEmpty()) { - log.info("Consent retrieval steps are not null or empty"); - } else { - log.warn("Consent retrieval steps are null or empty"); - } - if (consentPersistSteps != null && !consentPersistSteps.isEmpty()) { - log.info("Consent persist steps are not null or empty"); - } else { - log.warn("Consent persist steps are null or empty"); - } - } else { - log.debug("Retrieval and persist steps are available"); - } - } - - /** - * Execute consent retrieval steps. - * - * @param consentData Consent Data - * @param jsonObject Json object to store consent data - * @throws ConsentException when an error occurs while executing retrieval steps - */ - protected void executeRetrieval(ConsentData consentData, JSONObject jsonObject) throws ConsentException { - - for (ConsentRetrievalStep step : consentRetrievalSteps) { - if (log.isDebugEnabled()) { - log.debug("Executing retrieval step " + step.getClass().toString()); - } - step.execute(consentData, jsonObject); - } - } - - /** - * Retrieve consent. - * - * @param request HTTP request - * @param response HTTP response - * @param sessionDataKey Session data key - * @return Consent data - * @throws ConsentException when an error occurs while retrieving consent - */ - protected JSONObject retrieveConsent(HttpServletRequest request, HttpServletResponse response, - String sessionDataKey) throws ConsentException { - - String loggedInUser; - String app; - String spQueryParams; - String scopeString; - - SessionDataCacheEntry cacheEntry = ConsentCache.getCacheEntryFromSessionDataKey(sessionDataKey); - OAuth2Parameters oAuth2Parameters = cacheEntry.getoAuth2Parameters(); - URI redirectURI; - try { - redirectURI = new URI(oAuth2Parameters.getRedirectURI()); - } catch (URISyntaxException e) { - //Unlikely to happen. In case it happens, error response is sent - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Invalid redirect URI"); - } - //Extracting client ID for regulatory identification and redirect URI for error redirects - String clientId = oAuth2Parameters.getClientId(); - String state = oAuth2Parameters.getState(); - - Map sensitiveDataMap = - ConsentExtensionUtils.getSensitiveDataWithConsentKey(sessionDataKey); - - if ("false".equals(sensitiveDataMap.get(CIBAPushAuthenticatorConstants.IS_ERROR))) { - loggedInUser = (String) sensitiveDataMap.get(CIBAPushAuthenticatorConstants.LOGGED_IN_USER); - app = (String) sensitiveDataMap.get(CIBAPushAuthenticatorConstants.APPLICATION); - spQueryParams = (String) sensitiveDataMap.get(CIBAPushAuthenticatorConstants.SP_QUERY_PARAMS); - scopeString = (String) sensitiveDataMap.get(CIBAPushAuthenticatorConstants.SCOPE); - } else { - String isError = (String) sensitiveDataMap.get(CIBAPushAuthenticatorConstants.IS_ERROR); - //Have to throw standard error because cannot access redirect URI with this error - log.error("Error while getting endpoint parameters. " + isError); - throw new ConsentException(redirectURI, AuthErrorCode.SERVER_ERROR, - CIBAPushAuthenticatorConstants.ERROR_SERVER_ERROR, state); - } - - JSONObject jsonObject = new JSONObject(); - ConsentData consentData = createConsentData(sessionDataKey, loggedInUser, spQueryParams, scopeString, app, - request); - consentData.setSensitiveDataMap(sensitiveDataMap); - consentData.setRedirectURI(redirectURI); - - if (clientId == null) { - log.error("Client Id not available"); - //Unlikely error. Included just in case. - throw new ConsentException(redirectURI, AuthErrorCode.SERVER_ERROR, - CIBAPushAuthenticatorConstants.ERROR_SERVER_ERROR, state); - } - consentData.setClientId(clientId); - consentData.setState(state); - - try { - consentData.setRegulatory(IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId)); - } catch (OpenBankingException e) { - log.error("Error while getting regulatory data", e); - throw new ConsentException(redirectURI, AuthErrorCode.SERVER_ERROR, "Error while obtaining regulatory data", - state); - } - - executeRetrieval(consentData, jsonObject); - if (consentData.getType() == null || consentData.getApplication() == null) { - log.error(CIBAPushAuthenticatorConstants.ERROR_NO_TYPE_AND_APP_DATA); - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - CIBAPushAuthenticatorConstants.ERROR_SERVER_ERROR, state); - } - ConsentExtensionUtils.setCommonDataToResponse(consentData, jsonObject); - try { - ConsentCache.addConsentDataToCache(sessionDataKey, consentData); - } catch (ConsentManagementException e) { - log.error("Error while adding consent data to cache", e); - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - CIBAPushAuthenticatorConstants.ERROR_SERVER_ERROR, state); - } - return jsonObject; - } - - @Generated(message = "This method is separated for unit testing purposes") - protected ConsentData createConsentData(String sessionDataKey, String loggedInUser, String spQueryParams, - String scopeString, String app, HttpServletRequest request) { - return new ConsentData(sessionDataKey, loggedInUser, spQueryParams, scopeString, app, - ConsentExtensionUtils.getHeaders(request)); - } - - /** - * Get the authenticated user. - * - * @param request Push authenticator HTTP request - * @return Authenticated User - */ - @Override - protected AuthenticatedUser getAuthenticatedUser(HttpServletRequest request) { - - // In OB CIBA, only this Push Authenticator IDP is expected to be executed during the CIBA auth flow - // Hence, the login_hint attribute in the CIBA request object is used to identify the user - return AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(request. - getParameter(CIBAPushAuthenticatorConstants.LOGIN_HINT)); - } - - @Generated(message = "This method is separated for unit testing purposes") - protected AuthenticationContext getAutenticationContext(String sessionDataKey) { - PushAuthContextManager contextManager = new PushAuthContextManagerImpl(); - - return contextManager.getContext(sessionDataKey); - } - - /** - * OB specific implementation to retrieve consent data. - * @param sessionDataKey Session data key - * @return consent data - * @throws AuthenticationFailedException Authentication failed exception - */ - @Override - protected Optional getAdditionalInfo(HttpServletRequest request, HttpServletResponse response, - String sessionDataKey) throws AuthenticationFailedException { - - AuthenticationContext context = getAutenticationContext(sessionDataKey); - - // update the authentication context with required values for OB specific requirements - try { - String queryParams = FrameworkUtils - .getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), - context.getContextIdentifier()); - Map params = splitQuery(queryParams); - handlePreConsent(context, params); - } catch (UnsupportedEncodingException e) { - throw new AuthenticationFailedException("Error occurred when processing the request object", e); - } - - SessionDataCacheKey cacheKey = ConsentCache.getCacheKey(sessionDataKey); - SessionDataCacheEntry cacheEntry = ConsentCache.getCacheEntryFromCacheKey(cacheKey); - - cacheEntry.setLoggedInUser(context.getSubject()); - SessionDataCache.getInstance().addToCache(cacheKey, cacheEntry); - - // Authentication context is added to cache as it is obtained from the cache in a later step by the Parameter - // Resolver object - AuthenticationContextCache.getInstance().addToCache( - new AuthenticationContextCacheKey(sessionDataKey), new AuthenticationContextCacheEntry(context)); - - JSONObject additionalInfo = retrieveConsent(request, response, sessionDataKey); - String bindingMessage = request.getParameter(CIBAPushAuthenticatorConstants.BINDING_MESSAGE); - if (StringUtils.isNotEmpty(bindingMessage)) { - additionalInfo.put(CIBAPushAuthenticatorConstants.BINDING_MESSAGE, bindingMessage); - } - return Optional.ofNullable(additionalInfo.toJSONString()); - } - - /** - * set attributes to context which will be required to prompt the consent page. - * - * @param context authentication context - * @param params query params - */ - protected void handlePreConsent(AuthenticationContext context, Map params) { - ServiceProvider serviceProvider = context.getSequenceConfig().getApplicationConfig().getServiceProvider(); - - context.addEndpointParam(CIBAPushAuthenticatorConstants.LOGGED_IN_USER, - params.get(CIBAPushAuthenticatorConstants.LOGIN_HINT)); - context.addEndpointParam(CIBAPushAuthenticatorConstants.USER_TENANT_DOMAIN, - "@carbon.super"); - context.addEndpointParam(CIBAPushAuthenticatorConstants.REQUEST, - params.get(CIBAPushAuthenticatorConstants.REQUEST_OBJECT)); - context.addEndpointParam(CIBAPushAuthenticatorConstants.SCOPE, - params.get(CIBAPushAuthenticatorConstants.SCOPE)); - context.addEndpointParam(CIBAPushAuthenticatorConstants.APPLICATION, serviceProvider.getApplicationName()); - context.addEndpointParam(CIBAPushAuthenticatorConstants.CONSENT_PROMPTED, true); - context.addEndpointParam(CIBAPushAuthenticatorConstants.AUTH_REQ_ID, - context.getAuthenticationRequest().getRequestQueryParams() - .get(CIBAPushAuthenticatorConstants.NONCE)[0]); - } - - /** - * Returns a map of query parameters from the given query param string. - * @param queryParamsString HTTP request query parameters - * @return Query parameter map - * @throws UnsupportedEncodingException Unsupported encoding exception - */ - protected Map splitQuery(String queryParamsString) throws UnsupportedEncodingException { - final Map queryParams = new HashMap<>(); - final String[] pairs = queryParamsString.split("&"); - for (String pair : pairs) { - final int idx = pair.indexOf("="); - final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; - final String value = - idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; - queryParams.put(key, value); - } - return queryParams; - } - - /** - * Extend this method to create error response on toolkits. Set necessary status codes and error payloads to - * CIBAAuthenticationEndpointErrorResponse. - * - * @param httpStatusCode Http status code - * @param errorCode Error code - * @param errorDescription Error description - * @return CIBAAuthenticationEndpointErrorResponse CIBA Authentication Endpoint Error Response - */ - public static CIBAAuthenticationEndpointErrorResponse createErrorResponse(int httpStatusCode, String errorCode, - String errorDescription) { - - CIBAAuthenticationEndpointErrorResponse cibaPushServletErrorResponse = - new CIBAAuthenticationEndpointErrorResponse(); - JSONObject errorResponse = new JSONObject(); - errorResponse.put(CIBAPushAuthenticatorConstants.ERROR_DESCRIPTION, errorDescription); - errorResponse.put(CIBAPushAuthenticatorConstants.ERROR, errorCode); - cibaPushServletErrorResponse.setPayload(errorResponse); - cibaPushServletErrorResponse.setHttpStatusCode(httpStatusCode); - - return cibaPushServletErrorResponse; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticatorConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticatorConstants.java deleted file mode 100644 index 76e4e491..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticatorConstants.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.ciba.authenticator; - -/** - * CIBA Push Authenticator Constants. - */ -public class CIBAPushAuthenticatorConstants { - - public static final String AUTHENTICATOR_NAME = "ciba"; - public static final String AUTHENTICATOR_FRIENDLY_NAME = "CIBA Authenticator"; - public static final String REQUEST = "request"; - public static final String REQUEST_OBJECT = "request_object"; - public static final String BINDING_MESSAGE = "binding_message"; - - //Consent Related constants - public static final String LOGGED_IN_USER = "loggedInUser"; - public static final String USER_TENANT_DOMAIN = "userTenantDomain"; - public static final String SCOPE = "scope"; - public static final String APPLICATION = "application"; - public static final String CONSENT_PROMPTED = "consentPrompted"; - public static final String AUTH_REQ_ID = "auth_req_id"; - public static final String NONCE = "nonce"; - public static final String LOGIN_HINT = "login_hint"; - public static final String SP_QUERY_PARAMS = "spQueryParams"; - - // error constants - public static final String IS_ERROR = "isError"; - public static final String ERROR_SERVER_ERROR = "Internal server error"; - public static final String ERROR_NO_TYPE_AND_APP_DATA = "Type and application data is unavailable"; - public static final String ERROR_DESCRIPTION = "error_description"; - public static final String ERROR = "error"; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/impl/CIBAAuthenticationEndpointDefaultImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/impl/CIBAAuthenticationEndpointDefaultImpl.java deleted file mode 100644 index cfa00001..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/impl/CIBAAuthenticationEndpointDefaultImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.ciba.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.ciba.model.CIBAAuthenticationEndpointInterface; -import net.minidev.json.JSONObject; - -/** - * Implementation to extend CIBA push servlet consent persistence data. - */ -public class CIBAAuthenticationEndpointDefaultImpl implements CIBAAuthenticationEndpointInterface { - - @Override - public JSONObject updateConsentData(JSONObject consentData) { - return consentData; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/model/CIBAAuthenticationEndpointErrorResponse.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/model/CIBAAuthenticationEndpointErrorResponse.java deleted file mode 100644 index 6c640b33..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/model/CIBAAuthenticationEndpointErrorResponse.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.ciba.model; - -import net.minidev.json.JSONObject; - -/** - * CIBA authentication endpoint error response. - */ -public class CIBAAuthenticationEndpointErrorResponse { - - private int httpStatusCode = 0; - private JSONObject payload = null; - - public int getHttpStatusCode() { - - return httpStatusCode; - } - public void setHttpStatusCode(int httpStatusCode) { - - this.httpStatusCode = httpStatusCode; - } - - public JSONObject getPayload() { - - return payload; - } - public void setPayload(JSONObject payload) { - - this.payload = payload; - } - -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/model/CIBAAuthenticationEndpointInterface.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/model/CIBAAuthenticationEndpointInterface.java deleted file mode 100644 index a84abdc2..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/model/CIBAAuthenticationEndpointInterface.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.ciba.model; - -import net.minidev.json.JSONObject; - -/** - * The interface to extend CIBA push servlet consent persistence data. - */ -public interface CIBAAuthenticationEndpointInterface { - - /** - * Set additional data to consent data. - * @param consentData consent data json object - * @return updated consent data json object - */ - JSONObject updateConsentData(JSONObject consentData); -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/AuthErrorCode.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/AuthErrorCode.java deleted file mode 100644 index 67234110..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/AuthErrorCode.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -/** - * Enum of the error redirect codes from both OAuth 2.0 and OIDC Core 1.0 specifications. - */ -public enum AuthErrorCode { - - /** - * invalid_request, see ... - */ - INVALID_REQUEST("invalid_request"), - /** - * unauthorized_client, see ... - */ - UNAUTHORIZED_CLIENT("unauthorized_client"), - /** - * access_denied, see ... - */ - ACCESS_DENIED("access_denied"), - /** - * unsupported_response_type, see ... - */ - UNSUPPORTED_RESPONSE_TYPE("unsupported_response_type"), - /** - * invalid_scope, see ... - */ - INVALID_SCOPE("invalid_scope"), - /** - * server_error, see ... - */ - SERVER_ERROR("server_error"), - /** - * temporarily_unavailable, see ... - */ - TEMPORARILY_UNAVAILABLE("temporarily_unavailable"), - /** - * interaction_required, see - * OpenID Connect Core 1.0}. - */ - INTERACTION_REQUIRED("interaction_required"), - /** - * login_required, see - * OpenID Connect Core 1.0}. - */ - LOGIN_REQUIRED("login_required"), - /** - * account_selection_required, see - * OpenID Connect Core 1.0}. - */ - ACCOUNT_SELECTION_REQUIRED("account_selection_required"), - /** - * consent_required, see - * OpenID Connect Core 1.0}. - */ - CONSENT_REQUIRED("consent_required"), - /** - * invalid_request_uri, see - * OpenID Connect Core 1.0}. - */ - INVALID_REQUEST_URI("invalid_request_uri"), - /** - * invalid_request_object, see - * OpenID Connect Core 1.0}. - */ - INVALID_REQUEST_OBJECT("invalid_request_object"), - /** - * request_not_supported, see - * OpenID Connect Core 1.0}. - */ - REQUEST_NOT_SUPPORTED("request_not_supported"), - /** - * request_uri_not_supported, see - * OpenID Connect Core 1.0}. - */ - REQUEST_URI_NOT_SUPPORTED("request_uri_not_supported"), - /** - * registration_not_supported, see - * OpenID Connect Core 1.0}. - */ - REGISTRATION_NOT_SUPPORTED("registration_not_supported"); - - private final String errorCode; - - AuthErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - - @Override - public String toString() { - - return errorCode; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentCache.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentCache.java deleted file mode 100644 index 7c9cbf35..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentCache.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.identity.cache.IdentityCache; -import com.wso2.openbanking.accelerator.identity.cache.IdentityCacheKey; -import net.minidev.json.JSONValue; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; - -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - - -/** - * Class for maintaining Consent Cache. - */ -public class ConsentCache { - - private static volatile IdentityCache consentCache; - - private static Log log = LogFactory.getLog(ConsentCache.class); - - private static ConsentCoreServiceImpl consentCoreService = new ConsentCoreServiceImpl(); - - private static final String preserveConsent = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(ConsentExtensionConstants.PRESERVE_CONSENT); - private static boolean storeConsent = preserveConsent == null ? false : Boolean.parseBoolean(preserveConsent); - - /** - * Get consent cache instance. - * @return consent cache instance - */ - public static IdentityCache getInstance() { - if (consentCache == null) { - synchronized (ConsentCache.class) { - if (consentCache == null) { - consentCache = new IdentityCache(); - } - } - } - - return consentCache; - } - - /** - * Add consent data to consent data cache. - * @param sessionDataKey session data key - * @param consentData consent data - * @throws ConsentManagementException if an error occurs while adding consent data to cache - */ - public static void addConsentDataToCache(String sessionDataKey, ConsentData consentData) - throws ConsentManagementException { - - ConsentCache.getInstance().addToCache(IdentityCacheKey.of(sessionDataKey), - consentData); - - storeConsent(consentData, sessionDataKey); - } - - /** - * Add consent data to database. - * @param sessionDataKey session data key - * @param consentData consent data - * @throws ConsentManagementException if an error occurs while storing consent data - */ - public static void storeConsent(ConsentData consentData, String sessionDataKey) throws ConsentManagementException { - - Gson gson = new Gson(); - if (storeConsent) { - String consent = gson.toJson(consentData); - Map authorizeData = new HashMap<>(); - authorizeData.put(consentData.getSessionDataKey(), consent); - if (consentCoreService.getConsentAttributesByName(sessionDataKey).isEmpty()) { - consentCoreService.storeConsentAttributes(consentData.getConsentId(), authorizeData); - } - } - } - - /** - * Get new session data cache key using session data key. - * @param sessionDataKey Session data key - * @return session data cache key - */ - public static SessionDataCacheKey getCacheKey(String sessionDataKey) { - - return new SessionDataCacheKey(sessionDataKey); - } - - /** - * Get session data cache entry by session data cache key. - * @param cacheKey session data cache key - * @return Session data cache entry - */ - public static SessionDataCacheEntry getCacheEntryFromCacheKey(SessionDataCacheKey cacheKey) { - - return SessionDataCache.getInstance().getValueFromCache(cacheKey); - } - - /** - * Get Consent data from the consent cache. - * @param sessionDataKey Session data key - * @return consent data - */ - public static ConsentData getConsentDataFromCache(String sessionDataKey) { - - ConsentData consentData = (ConsentData) ConsentCache.getInstance() - .getFromCache(IdentityCacheKey.of(sessionDataKey)); - if (consentData == null) { - if (storeConsent) { - Map consentDetailsMap = - null; - try { - consentDetailsMap = consentCoreService.getConsentAttributesByName(sessionDataKey); - if (consentDetailsMap.isEmpty()) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - Set keys = consentDetailsMap.keySet(); - String consentId = new ArrayList<>(keys).get(0); - JsonObject consentDetails = new JsonParser() - .parse(consentDetailsMap.get(consentId)).getAsJsonObject(); - consentData = ConsentExtensionUtils.getConsentDataFromAttributes(consentDetails, sessionDataKey); - - if (consentDetailsMap.isEmpty()) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - // remove all session data related to the consent from consent attributes - ArrayList keysToDelete = new ArrayList<>(); - - Map consentAttributes = consentCoreService. - getConsentAttributes(consentData.getConsentId()).getConsentAttributes(); - - consentAttributes.forEach((key, value) -> { - if (JSONValue.isValidJson(value) && value.contains(ConsentMgtDAOConstants.SESSION_DATA_KEY)) { - keysToDelete.add(key); - } - }); - consentCoreService.deleteConsentAttributes(consentData.getConsentId(), keysToDelete); - } catch (ConsentManagementException | URISyntaxException e) { - log.error("Error while retrieving consent data from cache", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - } else { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - } - return consentData; - } - - /** - * Get Cache Entry by Session Data Key. - * @param sessionDataKey Session Data Key - * @return Session data cache entry - */ - public static SessionDataCacheEntry getCacheEntryFromSessionDataKey(String sessionDataKey) { - - return ConsentCache.getCacheEntryFromCacheKey(ConsentCache.getCacheKey(sessionDataKey)); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentException.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentException.java deleted file mode 100644 index 8bad616d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentException.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -/** - * Consent exception class to be used in consent components and extensions. - */ -public class ConsentException extends RuntimeException { - - private static final Log log = LogFactory.getLog(ConsentException.class); - - private JSONObject payload; - private ResponseStatus status; - private URI errorRedirectURI; - - public ConsentException(ResponseStatus status, JSONObject payload, Throwable cause) { - - super(cause); - this.status = status; - this.payload = payload; - } - - public ConsentException(ResponseStatus status, JSONObject payload) { - - this.status = status; - this.payload = payload; - } - - public ConsentException(ResponseStatus status, String description) { - - this.status = status; - this.payload = createDefaultErrorObject(this.status, description); - } - - /** - * This method is created to send error redirects in in the authorization flow. The parameter validations are done - * in compliance with the OAuth2 and OIDC specifications. - * - * @param errorRedirectURI REQUIRED The base URI which the redirect should go to. - * @param error REQUIRED The error code of the error. Should be a supported value in OAuth2/OIDC - * @param errorDescription OPTIONAL The description of the error. - * @param state REQUIRED if a "state" parameter was present in the client authorization request. - */ - public ConsentException(URI errorRedirectURI, AuthErrorCode error, String errorDescription, String state) { - - if (errorRedirectURI != null && error != null) { - try { - //add 302 as error code since this will be a redirect - this.status = ResponseStatus.FOUND; - //set parameters as uri fragments - //https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#rfc.section.5 - String errorResponse = ConsentExtensionConstants.ERROR_URI_FRAGMENT - .concat(URLEncoder.encode(error.toString(), StandardCharsets.UTF_8.toString())); - if (errorDescription != null) { - errorResponse = errorResponse.concat(ConsentExtensionConstants.ERROR_DESCRIPTION_PARAMETER) - .concat(URLEncoder.encode(errorDescription, StandardCharsets.UTF_8.toString())); - } - if (state != null) { - errorResponse = errorResponse.concat(ConsentExtensionConstants.STATE_PARAMETER) - .concat(URLEncoder.encode(state, StandardCharsets.UTF_8.toString())); - } - this.errorRedirectURI = new URI(errorRedirectURI.toString().concat(errorResponse)); - - } catch (URISyntaxException | UnsupportedEncodingException e) { - log.error("Error while building the uri", e); - } - } - } - - public JSONObject createDefaultErrorObject(ResponseStatus status, String description) { - - JSONObject error = new JSONObject(); - JSONArray errorList = new JSONArray(); - JSONObject errorObj = new JSONObject(); - error.appendField("Code", String.valueOf(status.getStatusCode())); - error.appendField("Message", status.getReasonPhrase()); - errorObj.appendField("ErrorCode", String.valueOf(status.getStatusCode())); - errorObj.appendField("Message", description); - errorList.appendElement(errorObj); - error.appendField("Errors", errorList); - return error; - } - - public JSONObject getPayload() { - - return payload; - } - - public ResponseStatus getStatus() { - - return status; - } - - public URI getErrorRedirectURI() { - - return errorRedirectURI; - } - - public void setErrorRedirectURI(URI errorRedirectURI) { - - this.errorRedirectURI = errorRedirectURI; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionConstants.java deleted file mode 100644 index 4062a1bf..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionConstants.java +++ /dev/null @@ -1,227 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.common; - -/** - * Constant class for consent extension module. - */ -public class ConsentExtensionConstants { - - public static final String ERROR_URI_FRAGMENT = "#error="; - public static final String ERROR_DESCRIPTION_PARAMETER = "&error_description="; - public static final String STATE_PARAMETER = "&state="; - public static final String PRESERVE_CONSENT = "Consent.PreserveConsentLink"; - public static final String SENSITIVE_DATA_MAP = "sensitiveDataMap"; - public static final String LOGGED_IN_USER = "loggedInUser"; - public static final String SP_QUERY_PARAMS = "spQueryParams"; - public static final String SCOPES = "scopeString"; - public static final String APPLICATION = "application"; - public static final String REQUEST_HEADERS = "requestHeaders"; - public static final String REQUEST_URI = "redirectURI"; - public static final String USERID = "userId"; - public static final String CONSENT_ID = "ConsentId"; - public static final String CONSENT_ID_VALIDATION = "ConsentId"; - public static final String CLIENT_ID = "clientId"; - public static final String REGULATORY = "regulatory"; - public static final String CONSENT_RESOURCE = "consentResource"; - public static final String AUTH_RESOURCE = "authResource"; - public static final String META_DATA = "metaDataMap"; - public static final String TYPE = "type"; - public static final String X_IDEMPOTENCY_KEY = "x-idempotency-key"; - public static final String IS_VALID = "isValid"; - public static final String HTTP_CODE = "httpCode"; - public static final String ERRORS = "errors"; - public static final String PAYMENTS = "payments"; - public static final String VRP = "vrp"; - - public static final String DATA = "Data"; - public static final String INITIATION = "Initiation"; - public static final String STATUS = "Status"; - public static final String STATUS_UPDATE_TIME = "StatusUpdateDateTime"; - public static final String CREATION_DATE_TIME = "CreationDateTime"; - public static final String FUNDSCONFIRMATIONS = "fundsconfirmations"; - public static final String SCHEME_NAME = "SchemeName"; - public static final String IDENTIFICATION = "Identification"; - public static final String NAME = "Name"; - public static final String SECONDARY_IDENTIFICATION = "SecondaryIdentification"; - public static final String OB_SORT_CODE_ACCOUNT_NUMBER = "OB.SortCodeAccountNumber"; - public static final String SORT_CODE_ACCOUNT_NUMBER = "SortCodeAccountNumber"; - public static final int ACCOUNT_IDENTIFICATION_LENGTH = 14; - public static final String SORT_CODE_PATTERN = "^[0-9]{6}[0-9]{8}$"; - public static final String CUSTOM_LOCAL_INSTRUMENT_VALUES = "Consent.CustomLocalInstrumentValues"; - public static final String AMOUNT = "Amount"; - public static final String CREDITOR_ACC = "CreditorAccount"; - public static final String DEBTOR_ACC = "DebtorAccount"; - public static final String INSTRUCTED_AMOUNT = "InstructedAmount"; - public static final String LOCAL_INSTRUMENT = "LocalInstrument"; - public static final String ACCOUNT_CONSENT_GET_PATH = "account-access-consents"; - public static final String ACCOUNT_CONSENT_DELETE_PATH = "account-access-consents/"; - public static final String UUID_REGEX = - "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; - public static final String INTERACTION_ID_HEADER = "x-fapi-interaction-id"; - public static final String PERMISSIONS = "Permissions"; - public static final String COF_CONSENT_PATH = "funds-confirmation-consents"; - public static final String PAYMENT_CONSENT_PATH = "payment-consents"; - public static final String CONSENT_KEY = "OauthConsentKey"; - public static final String REQUEST_KEY = "AuthRequestKey"; - public static final String CUTOFF_DATE_ENABLED = "Consent.PaymentRestrictions.CutOffDateTime.Enabled"; - public static final String MAX_INSTRUCTED_AMOUNT = "Consent.PaymentRestrictions" + - ".MaximumInstructedAmount"; - public static final String DAILY_CUTOFF = "Consent.PaymentRestrictions.CutOffDateTime" + - ".DailyCutOffTime"; - public static final String REJECT = "REJECT"; - public static final String CUTOFF_DATE_POLICY = "Consent.PaymentRestrictions.CutOffDateTime" + - ".CutOffDateTimePolicy"; - public static final String ACCEPT = "ACCEPT"; - public static final String ZONE_ID = "ZoneId"; - public static final String IS_ERROR = "isError"; - public static final String ACCOUNTS = "accounts"; - public static final String CONSENT_DATA = "consentData"; - public static final String TITLE = "title"; - public static final String DEBTOR_ACCOUNT_ID = "AccountId"; - public static final String ACCOUNT_ID = "account_id"; - public static final String DATA_REQUESTED = "data_requested"; - public static final String PAYMENT_ACCOUNT = "paymentAccount"; - public static final String COF_ACCOUNT = "cofAccount"; - public static final String AWAITING_AUTH_STATUS = "awaitingAuthorisation"; - public static final String CUT_OFF_DATE_TIME = "CutOffDateTime"; - public static final String IDEMPOTENCY_KEY = "IdempotencyKey"; - public static final int NUMBER_OF_PARTS_IN_JWS = 3; - public static final String CLAIMS = "claims"; - public static final String[] CLAIM_FIELDS = new String[]{"userinfo", "id_token"}; - public static final String OPENBANKING_INTENT_ID = "openbanking_intent_id"; - public static final String VALUE = "value"; - public static final String AUTHORIZED_STATUS = "authorised"; - public static final String EXPIRATION_DATE = "ExpirationDateTime"; - public static final String EXPIRATION_DATE_TITLE = "Expiration Date Time"; - public static final String INSTRUCTED_AMOUNT_TITLE = "Instructed Amount"; - public static final String CURRENCY_TITLE = "Currency"; - public static final String CURRENCY = "Currency"; - public static final String AMOUNT_TITLE = "Amount"; - public static final String END_TO_END_IDENTIFICATION_TITLE = "End to End Identification"; - public static final String END_TO_END_IDENTIFICATION = "EndToEndIdentification"; - public static final String INSTRUCTION_IDENTIFICATION_TITLE = "Instruction Identification"; - public static final String INSTRUCTION_IDENTIFICATION = "InstructionIdentification"; - public static final String REJECTED_STATUS = "rejected"; - public static final String OPEN_ENDED_AUTHORIZATION = "Open Ended Authorization Requested"; - public static final String DEBTOR_ACC_TITLE = "Debtor Account"; - public static final String SCHEME_NAME_TITLE = "Scheme Name"; - public static final String IDENTIFICATION_TITLE = "Identification"; - public static final String NAME_TITLE = "Name"; - public static final String SECONDARY_IDENTIFICATION_TITLE = "Secondary Identification"; - public static final String CREDITOR_ACC_TITLE = "Creditor Account"; - public static final String CONSENT_TYPE = "consent_type"; - public static final String TRANSACTION_FROM_DATE = "TransactionFromDateTime"; - public static final String TRANSACTION_TO_DATE = "TransactionToDateTime"; - public static final String TRANSACTION_FROM_DATE_TITLE = "Transaction From Date Time"; - public static final String TRANSACTION_TO_DATE_TITLE = "Transaction To Date Time"; - public static final String PAYMENT_TYPE_TITLE = "Payment Type"; - public static final String CURRENCY_OF_TRANSFER_TITLE = "Currency of Transfer"; - public static final String CURRENCY_OF_TRANSFER = "CurrencyOfTransfer"; - public static final String INTERNATIONAL_PAYMENTS = "International Payments"; - public static final String DOMESTIC_PAYMENTS = "Domestic Payments"; - public static final String CREATED_STATUS = "created"; - public static final String IS_VALID_PAYLOAD = "isValidPayload"; - public static final String ERROR_CODE = "errorCode"; - public static final String ERROR_MESSAGE = "errorMessage"; - public static final String RISK = "Risk"; - public static final String COF_CONSENT_INITIATION_PATH = "/funds-confirmation-consents"; - public static final String COF_CONSENT_CONSENT_ID_PATH = "/funds-confirmation-consents/{ConsentId}"; - public static final String COF_SUBMISSION_PATH = "/funds-confirmations"; - public static final String ACCOUNT_ID_LIST = "AccountIds"; - public static final String CREATION_TIME = "CreationDateTime"; - public static final String LINKS = "Links"; - public static final String SELF = "Self"; - public static final String META = "Meta"; - public static final String ACCOUNTS_SELF_LINK = "Consent.AccountAPIURL"; - public static final String PAYMENT_SELF_LINK = "Consent.PaymentAPIURL"; - public static final String COF_SELF_LINK = "Consent.FundsConfirmationAPIURL"; - public static final String VRP_SELF_LINK = "Consent.VRPAPIURL"; - public static final String REVOKED_STATUS = "revoked"; - public static final String DISPLAY_NAME = "display_name"; - public static final String ACCOUNT_DATA = "account_data"; - public static final String SELECTED_ACCOUNT = "selectedAccount"; - public static final String PAYMENT_COF_PATH = "funds-confirmation"; - public static final String AWAITING_UPLOAD_STATUS = "awaitingUpload"; - public static final String OB_REVOKED_STATUS = "Revoked"; - public static final String OB_REJECTED_STATUS = "Rejected"; - public static final String OB_AUTHORIZED_STATUS = "Authorised"; - public static final String OB_AWAITING_AUTH_STATUS = "AwaitingAuthorisation"; - public static final String OB_AWAITING_UPLOAD_STATUS = "AwaitingUpload"; - - //VRP Constants - public static final String VRP_CONSENT_PATH = "domestic-vrp-consents"; - public static final String VRP_PAYMENT = "vrp-payment"; - public static final String PAID_AMOUNT = "paid-amount"; - public static final String LAST_PAYMENT_DATE = "last-payment-date"; - public static final String AUTH_TYPE_AUTHORIZATION = "authorization"; - public static final String CONTROL_PARAMETERS = "ControlParameters"; - public static final String MAXIMUM_INDIVIDUAL_AMOUNT = "MaximumIndividualAmount"; - public static final String MAXIMUM_INDIVIDUAL_AMOUNT_CURRENCY = "MaximumIndividualAmount.Amount.Currency"; - public static final String PERIODIC_LIMITS = "PeriodicLimits"; - public static final String PERIODIC_TYPES = "PeriodicTypes"; - public static final String PERIOD_AMOUNT_LIMIT = "Amount"; - public static final String PERIOD_LIMIT_CURRENCY = "PeriodicLimits.Currency"; - public static final String CYCLIC_EXPIRY_TIME = "cyclicExpiryTime"; - public static final String CYCLIC_REMAINING_AMOUNT = "cyclicRemainingAmount"; - - //vrp period alignment - public static final String PERIOD_ALIGNMENT = "PeriodAlignment"; - - // vrp periodic alignment types - public static final String CONSENT = "Consent"; - public static final String CALENDAR = "Calendar"; - - //vrp periodicLimits - public static final String PERIOD_TYPE = "PeriodType"; - - //vrp periodic types - public static final String DAY = "Day"; - public static final String WEEK = "Week"; - public static final String FORTNIGHT = "Fortnight"; - public static final String MONTH = "Month"; - public static final String HALF_YEAR = "Half-year"; - public static final String YEAR = "Year"; - public static final String VALID_TO_DATE_TIME = "ValidToDateTime"; - public static final String VALID_FROM_DATE_TIME = "ValidFromDateTime"; - public static final String VRP_RESPONSE_PROCESS_PATH = "vrp-response-process"; - - // vrp authorization flow constants - public static final String DOMESTIC_VRP = "Domestic VRP"; - public static final String CONTROL_PARAMETER_MAX_INDIVIDUAL_AMOUNT_TITLE = "Maximum amount per payment"; - public static final String CONTROL_PARAMETER_VALID_TO_DATE_TITLE = "Valid to date and time"; - public static final String CONTROL_PARAMETER_PERIOD_ALIGNMENT_TITLE = "Period Alignment"; - public static final String CONTROL_PARAMETER_PERIOD_TYPE_TITLE = "Period Type"; - public static final Object CONTROL_PARAMETER_AMOUNT_TITLE = "Maximum payment amount per "; - public static final String VRP_ACCOUNT = "vrpAccount"; - public static final Object CONTROL_PARAMETER_VALID_FROM_DATE_TITLE = "Valid from date and time"; - - // VRP submission flow - public static final String ACCOUNT_IDS = "accountIds"; - public static final String INSTRUCTION = "Instruction"; - public static final String REMITTANCE_INFO = "RemittanceInformation"; - public static final String REFERENCE = "Reference"; - public static final String UNSTRUCTURED = "Unstructured"; - public static final String CONTEXT_CODE = "PaymentContextCode"; - public static final String PAYMENT_TYPE = "PaymentType"; - public static final String VRP_PATH = "/domestic-vrps"; - public static final String PREVIOUS_PAID_AMOUNT = "prevPaidAmount"; - public static final String PREVIOUS_LAST_PAYMENT_DATE = "prevLastPaymentDate"; - - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionExporter.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionExporter.java deleted file mode 100644 index 5988299c..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionExporter.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -import com.wso2.openbanking.accelerator.consent.extensions.admin.builder.ConsentAdminBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.builder.ConsentStepsBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.builder.ConsentManageBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.validate.builder.ConsentValidateBuilder; - -/** - * Exporter service to facilitate access to loaded builder classes in data holder from other modules. - */ -public class ConsentExtensionExporter { - - private static volatile ConsentExtensionExporter consentExtExporter; - private static ConsentAdminBuilder consentAdminBuilder; - private static ConsentManageBuilder consentManageBuilder; - private static ConsentStepsBuilder consentStepsBuilder; - private static ConsentValidateBuilder consentValidateBuilder; - - public static ConsentExtensionExporter getInstance() { - if (consentExtExporter == null) { - synchronized (ConsentExtensionExporter.class) { - if (consentExtExporter == null) { - consentExtExporter = new ConsentExtensionExporter(); - } - } - } - - return consentExtExporter; - } - - public static ConsentValidateBuilder getConsentValidateBuilder() { - return consentValidateBuilder; - } - - public static void setConsentValidateBuilder(ConsentValidateBuilder consentValidateBuilder) { - ConsentExtensionExporter.consentValidateBuilder = consentValidateBuilder; - } - - public static ConsentStepsBuilder getConsentStepsBuilder() { - return consentStepsBuilder; - } - - public static void setConsentStepsBuilder(ConsentStepsBuilder consentStepsBuilder) { - ConsentExtensionExporter.consentStepsBuilder = consentStepsBuilder; - } - - public static ConsentManageBuilder getConsentManageBuilder() { - return consentManageBuilder; - } - - public static void setConsentManageBuilder(ConsentManageBuilder consentManageBuilder) { - ConsentExtensionExporter.consentManageBuilder = consentManageBuilder; - } - - public static ConsentAdminBuilder getConsentAdminBuilder() { - return consentAdminBuilder; - } - - public static void setConsentAdminBuilder(ConsentAdminBuilder consentAdminBuilder) { - ConsentExtensionExporter.consentAdminBuilder = consentAdminBuilder; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionUtils.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionUtils.java deleted file mode 100644 index 141410ab..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentExtensionUtils.java +++ /dev/null @@ -1,417 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.local.auth.api.core.ParameterResolverService; - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - - -import javax.servlet.http.HttpServletRequest; - -/** - * Util class for consent extensions. - */ -public class ConsentExtensionUtils { - - private static final Log log = LogFactory.getLog(ConsentExtensionUtils.class); - private static Gson gson = new Gson(); - public static void setCommonDataToResponse(ConsentData consentData, JSONObject jsonObject) throws ConsentException { - - if (!jsonObject.containsKey(ConsentExtensionConstants.TYPE)) { - jsonObject.appendField(ConsentExtensionConstants.TYPE, consentData.getType()); - } - if (!jsonObject.containsKey(ConsentExtensionConstants.APPLICATION)) { - jsonObject.appendField(ConsentExtensionConstants.APPLICATION, consentData.getApplication()); - } - } - - public static JSONObject detailedConsentToJSON(DetailedConsentResource detailedConsentResource) { - JSONObject consentResource = new JSONObject(); - - consentResource.appendField("consentId", detailedConsentResource.getConsentID()); - consentResource.appendField("clientId", detailedConsentResource.getClientID()); - try { - consentResource.appendField("receipt", (new JSONParser(JSONParser.MODE_PERMISSIVE)). - parse(detailedConsentResource.getReceipt())); - } catch (ParseException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Exception occurred while parsing" + - " receipt"); - } - consentResource.appendField("consentType", detailedConsentResource.getConsentType()); - consentResource.appendField("currentStatus", detailedConsentResource.getCurrentStatus()); - consentResource.appendField("consentFrequency", detailedConsentResource.getConsentFrequency()); - consentResource.appendField("validityPeriod", detailedConsentResource.getValidityPeriod()); - consentResource.appendField("createdTimestamp", detailedConsentResource.getCreatedTime()); - consentResource.appendField("updatedTimestamp", detailedConsentResource.getUpdatedTime()); - consentResource.appendField("recurringIndicator", detailedConsentResource.isRecurringIndicator()); - JSONObject attributes = new JSONObject(); - Map attMap = detailedConsentResource.getConsentAttributes(); - for (Map.Entry entry : attMap.entrySet()) { - attributes.appendField(entry.getKey(), entry.getValue()); - } - consentResource.appendField("consentAttributes", attributes); - JSONArray authorizationResources = new JSONArray(); - ArrayList authArray = detailedConsentResource.getAuthorizationResources(); - for (AuthorizationResource resource : authArray) { - JSONObject resourceJSON = new JSONObject(); - resourceJSON.appendField("authorizationId", resource.getAuthorizationID()); - resourceJSON.appendField("consentId", resource.getConsentID()); - resourceJSON.appendField("userId", resource.getUserID()); - resourceJSON.appendField("authorizationStatus", resource.getAuthorizationStatus()); - resourceJSON.appendField("authorizationType", resource.getAuthorizationType()); - resourceJSON.appendField("updatedTime", resource.getUpdatedTime()); - authorizationResources.add(resourceJSON); - } - consentResource.appendField("authorizationResources", authorizationResources); - JSONArray consentMappingResources = new JSONArray(); - ArrayList mappingArray = detailedConsentResource.getConsentMappingResources(); - for (ConsentMappingResource resource : mappingArray) { - JSONObject resourceJSON = new JSONObject(); - resourceJSON.appendField("mappingId", resource.getMappingID()); - resourceJSON.appendField("authorizationId", resource.getAuthorizationID()); - resourceJSON.appendField("accountId", resource.getAccountID()); - resourceJSON.appendField("permission", resource.getPermission()); - resourceJSON.appendField("mappingStatus", resource.getMappingStatus()); - consentMappingResources.add(resourceJSON); - } - consentResource.appendField("consentMappingResources", consentMappingResources); - return consentResource; - } - - public static JSONObject getRequestObjectPayload(String requestObject) { - try { - - // validate request object and get the payload - String requestObjectPayload; - String[] jwtTokenValues = requestObject.split("\\."); - if (jwtTokenValues.length == 3) { - requestObjectPayload = new String(Base64.getUrlDecoder().decode(jwtTokenValues[1]), - StandardCharsets.UTF_8); - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "request object is not signed JWT"); - } - Object payload = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(requestObjectPayload); - if (!(payload instanceof JSONObject)) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Payload is not a JSON object"); - } - return (JSONObject) payload; - - } catch (ParseException e) { - log.error("Exception occurred while getting consent data. Caused by : ", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } - - - /** - * Extract headers from a request object. - * - * @param request The request object - * @return Map of header key value pairs - */ - public static Map getHeaders(HttpServletRequest request) { - Map headers = new HashMap<>(); - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - headers.put(headerName, request.getHeader(headerName)); - } - return headers; - } - - /** - * Get the sensitive data corresponding to the session data consent key. - * - * @param sessionDataKeyConsent The session data key corresponding to the data hidden from redirect URLs - * @return The hidden sensitive data as key-value pairs. - */ - public static Map getSensitiveDataWithConsentKey(String sessionDataKeyConsent) { - - return getSensitiveData(sessionDataKeyConsent); - } - - /** - * Get the sensitive data corresponding to the session data key or the session data consent key. - * - * @param key The session data key or session data consent key corresponding to the data hidden from redirect URLs - * @return The hidden sensitive data as key-value pairs. - */ - public static Map getSensitiveData(String key) { - - Map sensitiveDataSet = new HashMap<>(); - - Object serviceObj = PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(ParameterResolverService.class, null); - if (serviceObj instanceof ParameterResolverService) { - ParameterResolverService resolverService = (ParameterResolverService) serviceObj; - - Set filter = Collections.emptySet(); - - sensitiveDataSet.putAll((resolverService) - .resolveParameters(ConsentExtensionConstants.CONSENT_KEY, key, filter)); - - if (sensitiveDataSet.isEmpty()) { - sensitiveDataSet.putAll((resolverService) - .resolveParameters(ConsentExtensionConstants.REQUEST_KEY, key, filter)); - } - - if (sensitiveDataSet.isEmpty()) { - log.error("No available data for key provided"); - sensitiveDataSet.put(ConsentExtensionConstants.IS_ERROR, "No available data for key provided"); - return sensitiveDataSet; - } - - sensitiveDataSet.put(ConsentExtensionConstants.IS_ERROR, "false"); - return sensitiveDataSet; - - } else { - log.error("Could not retrieve ParameterResolverService OSGi service"); - sensitiveDataSet.put(ConsentExtensionConstants.IS_ERROR, "Could not retrieve parameter service"); - return sensitiveDataSet; - } - } - - /** - * @param consentDetails json object of consent data - * @param sessionDataKey session data key - * @return ConsentData object - * @throws URISyntaxException if the URI is invalid - */ - public static ConsentData getConsentDataFromAttributes(JsonObject consentDetails, String sessionDataKey) - throws URISyntaxException { - - JsonObject sensitiveDataMap = consentDetails.get(ConsentExtensionConstants.SENSITIVE_DATA_MAP) - .getAsJsonObject(); - ConsentData consentData = new ConsentData(sessionDataKey, - sensitiveDataMap.get(ConsentExtensionConstants.LOGGED_IN_USER).getAsString(), - sensitiveDataMap.get(ConsentExtensionConstants.SP_QUERY_PARAMS).getAsString(), - consentDetails.get(ConsentExtensionConstants.SCOPES).getAsString(), - sensitiveDataMap.get(ConsentExtensionConstants.APPLICATION).getAsString(), - gson.fromJson(consentDetails.get(ConsentExtensionConstants.REQUEST_HEADERS), Map.class)); - consentData.setSensitiveDataMap(gson.fromJson(sensitiveDataMap, Map.class)); - URI redirectURI = new URI(consentDetails.get(ConsentExtensionConstants.REQUEST_URI).getAsString()); - consentData.setRedirectURI(redirectURI); - consentData.setUserId(consentDetails.get(ConsentExtensionConstants.USERID).getAsString()); - consentData.setConsentId(consentDetails.get(ConsentExtensionConstants.CONSENT_ID).getAsString()); - consentData.setClientId(consentDetails.get(ConsentExtensionConstants.CLIENT_ID).getAsString()); - consentData.setRegulatory(Boolean.parseBoolean(consentDetails.get(ConsentExtensionConstants.REGULATORY) - .getAsString())); - ConsentResource consentResource = gson.fromJson(consentDetails.get(ConsentExtensionConstants.CONSENT_RESOURCE), - ConsentResource.class); - consentData.setConsentResource(consentResource); - AuthorizationResource authorizationResource = - gson.fromJson(consentDetails.get(ConsentExtensionConstants.AUTH_RESOURCE), AuthorizationResource.class); - consentData.setAuthResource(authorizationResource); - consentData.setMetaDataMap(gson.fromJson(consentDetails.get(ConsentExtensionConstants.META_DATA), Map.class)); - consentData.setType(consentDetails.get(ConsentExtensionConstants.TYPE).getAsString()); - return consentData; - } - - /** - * Validates whether Cutoffdatetime is enabled, if the request is arriving past the cut off time and if it - * should be rejected by policy. - * - * @return if the request should be rejected, or not. - */ - public static boolean shouldInitiationRequestBeRejected() { - - return Boolean.parseBoolean((String) OpenBankingConfigParser.getInstance().getConfiguration().get( - ConsentExtensionConstants.CUTOFF_DATE_ENABLED)) && isCutOffTimeElapsed() - && ConsentExtensionConstants.REJECT.equals(OpenBankingConfigParser.getInstance().getConfiguration() - .get(ConsentExtensionConstants.CUTOFF_DATE_POLICY)); - } - - /** - * Validates whether the CutOffTime for the day has elapsed. - * - * @return has elapsed - */ - public static boolean isCutOffTimeElapsed() { - - OffsetTime dailyCutOffTime = OffsetTime.parse((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(ConsentExtensionConstants.DAILY_CUTOFF)); - OffsetTime currentTime = LocalTime.now().atOffset(dailyCutOffTime.getOffset()); - if (log.isDebugEnabled()) { - log.debug("Request received at" + currentTime + " daily cut off time set to " + dailyCutOffTime); - } - return currentTime.isAfter(dailyCutOffTime); - } - /** - * validate whether Cutoffdatetime is enabled, if the request is arriving past the cut off time - * and if it was accepted by policy.git a. - * - * @return if request is accepted and cut off date time has passed, or not - */ - - public static boolean isRequestAcceptedPastElapsedTime() { - - if (Boolean.parseBoolean((String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.CUTOFF_DATE_ENABLED)) && - isCutOffTimeElapsed() && ConsentExtensionConstants.ACCEPT - .equals(OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.CUTOFF_DATE_POLICY))) { - - log.debug("Request Accepted but CutOffDateTime has elapsed."); - return true; - } - return false; - } - /** - * Returns the DateTime by adding given number of days and the with the given Time. - * - * @param daysToAdd Number of days to add - * @param time Time to add - * @return DateTime value for the day - */ - public static String constructDateTime(long daysToAdd, String time) { - - String configuredZoneId = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.ZONE_ID); - String dateValue = LocalDate.now(ZoneId.of(configuredZoneId)).plusDays(daysToAdd) + "T" + - (OffsetTime.parse(time)); - - OffsetDateTime offSetDateVal = OffsetDateTime.parse(dateValue); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"); - return dateTimeFormatter.format(offSetDateVal); - } - - /** - * Validates whether Cutoffdatetime is enabled, if the request is arriving past the cut off date and if it - * should be rejected by policy. - * - * @param timeStamp Initiation timestamp - * @return if the request should be rejected, or not. - */ - public static boolean shouldSubmissionRequestBeRejected(String timeStamp) { - - String isCutOffDateEnabled = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.CUTOFF_DATE_ENABLED); - String cutOffDatePolicy = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.CUTOFF_DATE_POLICY); - - if (Boolean.parseBoolean(isCutOffDateEnabled) && ConsentExtensionConstants.REJECT.equals(cutOffDatePolicy)) { - if (isCutOffTimeElapsed()) { - log.debug("Request Rejected as CutOffTime has elapsed."); - return true; - } - - if (hasCutOffDateElapsed(timeStamp)) { - log.debug("Request Rejected as CutOffDate has elapsed."); - return true; - } - } - return false; - } - /** - * Validates whether the cutOffDate and the initiation date are the same. - * - * @return if the request should be rejected, or not. - */ - private static boolean hasCutOffDateElapsed(String initiationTimestamp) { - - OffsetDateTime initiationDateTime = OffsetDateTime.parse(initiationTimestamp); - OffsetDateTime currentDateTime = OffsetDateTime.parse(getCurrentCutOffDateTime()); - return initiationDateTime.getMonth() != currentDateTime.getMonth() || - initiationDateTime.getDayOfMonth() != currentDateTime.getDayOfMonth(); - } - /** - * Returns the CutOffDateTime from the CutOffTime. - * - * @return CutOffDateTime value for the day - */ - public static String getCurrentCutOffDateTime() { - - return LocalDate.now() + "T" + (OffsetTime.parse((String) OpenBankingConfigParser.getInstance() - .getConfiguration() - .get(OpenBankingConstants.DAILY_CUTOFF))); - } - /** - * Convert long date values to ISO 8601 format. - * @param dateValue Date value in long - * @return ISO 8601 formatted date - */ - public static String convertToISO8601(long dateValue) { - - DateFormat simple = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - Date simpleDateVal = new Date(dateValue * 1000); - return simple.format(simpleDateVal); - } - public static ConsentCoreServiceImpl getConsentService() { - return new ConsentCoreServiceImpl(); - } - - /** - * Get the mapping status. - * - * @param defaultStatus Default status returned from the accelerator - * @return Mapping UK status - */ - public static String getConsentStatus(String defaultStatus) { - - switch (defaultStatus) { - case ConsentExtensionConstants.AUTHORIZED_STATUS: - return ConsentExtensionConstants.OB_AUTHORIZED_STATUS; - case ConsentExtensionConstants.REVOKED_STATUS: - return ConsentExtensionConstants.OB_REVOKED_STATUS; - case ConsentExtensionConstants.REJECTED_STATUS: - return ConsentExtensionConstants.OB_REJECTED_STATUS; - case ConsentExtensionConstants.AWAITING_UPLOAD_STATUS: - return ConsentExtensionConstants.OB_AWAITING_UPLOAD_STATUS; - default: - return ConsentExtensionConstants.OB_AWAITING_AUTH_STATUS; - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentServiceUtil.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentServiceUtil.java deleted file mode 100644 index 0713e4ff..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ConsentServiceUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; - -/** - * Common Util Class for accessing external services. - */ -public class ConsentServiceUtil { - - @Generated(message = "Excluded from coverage since this is used for testing purposes") - public static ConsentCoreServiceImpl getConsentService() { - return new ConsentCoreServiceImpl(); - } -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ResponseStatus.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ResponseStatus.java deleted file mode 100644 index 396599a4..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/ResponseStatus.java +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common; - -/** - * Enum of the supported response status in accelerator. - * HTTP/1.1 documentation - ... - */ -public enum ResponseStatus { - - /** - * 200 OK, see ... - */ - OK(200, "OK"), - /** - * 201 Created, see ... - */ - CREATED(201, "Created"), - /** - * 202 Accepted, see ... - */ - ACCEPTED(202, "Accepted"), - /** - * 204 No Content, see ... - */ - NO_CONTENT(204, "No Content"), - /** - * 205 Reset Content, see ... - * - * @since 2.0 - */ - RESET_CONTENT(205, "Reset Content"), - /** - * 206 Reset Content, see ... - * - * @since 2.0 - */ - PARTIAL_CONTENT(206, "Partial Content"), - /** - * 301 Moved Permanently, see ... - */ - MOVED_PERMANENTLY(301, "Moved Permanently"), - /** - * 302 Found, see ... - * - * @since 2.0 - */ - FOUND(302, "Found"), - /** - * 303 See Other, see ... - */ - SEE_OTHER(303, "See Other"), - /** - * 304 Not Modified, see ... - */ - NOT_MODIFIED(304, "Not Modified"), - /** - * 305 Use Proxy, see link - "..." of - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - USE_PROXY(305, "Use Proxy"), - /** - * 307 Temporary Redirect, see ... - */ - TEMPORARY_REDIRECT(307, "Temporary Redirect"), - /** - * 400 Bad Request, see ... - */ - BAD_REQUEST(400, "Bad Request"), - /** - * 401 Unauthorized, see ... - */ - UNAUTHORIZED(401, "Unauthorized"), - /** - * 402 Payment Required, see ... - * - * @since 2.0 - */ - PAYMENT_REQUIRED(402, "Payment Required"), - /** - * 403 Forbidden, see ... - */ - FORBIDDEN(403, "Forbidden"), - /** - * 404 Not Found, see ... - */ - NOT_FOUND(404, "Not Found"), - /** - * 405 Method Not Allowed, see ... - * - * @since 2.0 - */ - METHOD_NOT_ALLOWED(405, "Method Not Allowed"), - /** - * 406 Not Acceptable, see ... - */ - NOT_ACCEPTABLE(406, "Not Acceptable"), - /** - * 409 Conflict, see ... - */ - CONFLICT(409, "Conflict"), - /** - * 410 Gone, see ... - */ - GONE(410, "Gone"), - /** - * 411 Length Required, see ... - * - * @since 2.0 - */ - LENGTH_REQUIRED(411, "Length Required"), - /** - * 412 Precondition Failed, see ... - */ - PRECONDITION_FAILED(412, "Precondition Failed"), - /** - * 413 Request Entity Too Large, - * see ... - * - * @since 2.0 - */ - REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"), - /** - * 414 Request-URI Too Long, see ... - * - * @since 2.0 - */ - REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"), - /** - * 415 Unsupported Media Type, - * see ... - */ - UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), - /** - * 416 Requested Range Not Satisfiable, - * see ... - * - * @since 2.0 - */ - REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), - /** - * 417 Expectation Failed, - * see ... - * - * @since 2.0 - */ - EXPECTATION_FAILED(417, "Expectation Failed"), - /** - * 422 Unprocessable Entity. - */ - UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"), - /** - * 429 Too Many Requests. - */ - TOO_MANY_REQUESTS(429, "Too Many Requests"), - /** - * 500 Internal Server Error, see ... - */ - INTERNAL_SERVER_ERROR(500, "Internal Server Error"), - /** - * 501 Not Implemented, see ... - * - * @since 2.0 - */ - NOT_IMPLEMENTED(501, "Not Implemented"), - /** - * 502 Bad Gateway, see ..." - * - * @since 2.0 - */ - BAD_GATEWAY(502, "Bad Gateway"), - /** - * 503 Service Unavailable, see ... - */ - SERVICE_UNAVAILABLE(503, "Service Unavailable"), - /** - * 504 Gateway Timeout, see ... - * - * @since 2.0 - */ - GATEWAY_TIMEOUT(504, "Gateway Timeout"), - /** - * 505 HTTP Version Not Supported, - * see ... - * - * @since 2.0 - */ - HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"); - - private final int code; - private final String reason; - - ResponseStatus(final int statusCode, final String reasonPhrase) { - this.code = statusCode; - this.reason = reasonPhrase; - } - - /** - * Get the associated status code. - * - * @return the status code. - */ - public int getStatusCode() { - return code; - } - - /** - * Get the reason phrase. - * - * @return the reason phrase. - */ - public String getReasonPhrase() { - return toString(); - } - - /** - * Get the reason phrase. - * - * @return the reason phrase. - */ - @Override - public String toString() { - return reason; - } - - /** - * Convert a numerical status code into the corresponding Status. - * - * @param statusCode the numerical status code. - * @return the matching Status or null is no matching Status is defined. - */ - public static ResponseStatus fromStatusCode(final int statusCode) { - for (ResponseStatus s : ResponseStatus.values()) { - if (s.code == statusCode) { - return s; - } - } - return null; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/factory/AcceleratorConsentExtensionFactory.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/factory/AcceleratorConsentExtensionFactory.java deleted file mode 100644 index 0c15cb9d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/factory/AcceleratorConsentExtensionFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.common.factory; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.manage.impl.AccountConsentManageRequestHandler; -import com.wso2.openbanking.accelerator.consent.extensions.manage.impl.CofConsentRequestHandler; -import com.wso2.openbanking.accelerator.consent.extensions.manage.impl.ConsentManageRequestHandler; -import com.wso2.openbanking.accelerator.consent.extensions.manage.impl.PaymentConsentRequestHandler; -import com.wso2.openbanking.accelerator.consent.extensions.manage.impl.VRPConsentRequestHandler; - -/** - * Factory class to get the class based in request type. - */ -public class AcceleratorConsentExtensionFactory { - /** - * Method to get the Consent Manage Request Validator. - * - * @param requestPath Request path of the request - * @return ConsentManageRequestValidator - */ - public static ConsentManageRequestHandler getConsentManageRequestValidator(String requestPath) { - - ConsentManageRequestHandler consentManageRequestHandler = null; - - switch (requestPath) { - case ConsentExtensionConstants.ACCOUNT_CONSENT_GET_PATH: - consentManageRequestHandler = new AccountConsentManageRequestHandler(); - break; - case ConsentExtensionConstants.COF_CONSENT_PATH: - consentManageRequestHandler = new CofConsentRequestHandler(); - break; - case ConsentExtensionConstants.PAYMENT_CONSENT_PATH: - consentManageRequestHandler = new PaymentConsentRequestHandler(); - break; - case ConsentExtensionConstants.VRP_CONSENT_PATH: - consentManageRequestHandler = new VRPConsentRequestHandler(); - break; - default: - return null; - } - return consentManageRequestHandler; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyConstants.java deleted file mode 100644 index e9866c25..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyConstants.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.common.idempotency; - -/** - * Constants related to idempotency operations. - */ -public class IdempotencyConstants { - - public static final String CONTENT_TYPE_TAG = "content-type"; - public static final String X_IDEMPOTENCY_KEY = "x-idempotency-key"; - public static final String IDEMPOTENCY_KEY_NAME = "IdempotencyKey"; - public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX"; - public static final String EMPTY_OBJECT = "{}"; - public static final String ERROR_PAYLOAD_NOT_SIMILAR = "Payloads are not similar. Hence this is not a valid" + - " idempotent request"; - public static final String ERROR_AFTER_ALLOWED_TIME = "Request received after the allowed time., Hence this is" + - " not a valid idempotent request"; - public static final String ERROR_MISMATCHING_CLIENT_ID = "Client ID sent in the request does not match with the" + - " client ID in the retrieved consent. Hence this is not a valid idempotent request"; - public static final String ERROR_NO_CONSENT_DETAILS = "No consent details found for the consent ID %s, Hence this" + - " is not a valid idempotent request"; - public static final String JSON_COMPARING_ERROR = "Error occurred while comparing JSON payloads"; - public static final String CONSENT_RETRIEVAL_ERROR = "Error while retrieving detailed consent data"; - public static final String SAME_CONSENT_ID_ERROR = "Cannot use different unique identifier for the same" + - " consent ID when the request does not contain a payload."; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationException.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationException.java deleted file mode 100644 index 821287ca..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationException.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common.idempotency; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * Used for handling exceptions in Idempotency Validation. - */ -public class IdempotencyValidationException extends OpenBankingException { - - public IdempotencyValidationException(String message) { - super(message); - } - - public IdempotencyValidationException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationResult.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationResult.java deleted file mode 100644 index a67f6694..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationResult.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common.idempotency; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; - -/** - * Class to hold idempotency validation result. - */ -public class IdempotencyValidationResult { - - private boolean isIdempotent; - private boolean isValid; - private DetailedConsentResource consent; - private String consentId; - - public IdempotencyValidationResult() { - } - - public IdempotencyValidationResult(boolean isIdempotent, boolean isValid, DetailedConsentResource consent, - String consentId) { - this.isIdempotent = isIdempotent; - this.isValid = isValid; - this.consent = consent; - this.consentId = consentId; - } - - public IdempotencyValidationResult(boolean isIdempotent, boolean isValid) { - this.isIdempotent = isIdempotent; - this.isValid = isValid; - this.consent = null; - this.consentId = null; - } - - public boolean isIdempotent() { - return isIdempotent; - } - - public void setIsIdempotent(boolean isIdempotent) { - this.isIdempotent = isIdempotent; - } - - public boolean isValid() { - return isValid; - } - - public void setValid(boolean isValid) { - this.isValid = isValid; - } - - public DetailedConsentResource getConsent() { - return consent; - } - - public void setConsent(DetailedConsentResource consent) { - this.consent = consent; - } - - public String getConsentId() { - return consentId; - } - - public void setConsentID(String consentId) { - this.consentId = consentId; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationUtils.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationUtils.java deleted file mode 100644 index 19639519..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidationUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common.idempotency; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.Duration; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Class to hold idempotency validation utils. - */ -public class IdempotencyValidationUtils { - - private static final Log log = LogFactory.getLog(IdempotencyValidationUtils.class); - private static final ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance() - .getConsentCoreService(); - - /** - * Method to retrieve the consent ids that have the idempotency key name and value as attribute. - * - * @param idempotencyKeyName Idempotency Key Name - * @param idempotencyKeyValue Idempotency Key Value - * @return List of consent ids if available, else an empty list will be returned - */ - static List getConsentIdsFromIdempotencyKey(String idempotencyKeyName, - String idempotencyKeyValue) { - try { - return consentCoreService.getConsentIdByConsentAttributeNameAndValue( - idempotencyKeyName, idempotencyKeyValue); - } catch (ConsentManagementException e) { - log.debug("No consent ids found for the idempotency key value"); - return new ArrayList<>(); - } - } - - /** - * Method to retrieve the consent ids and idempotency key value using the idempotency key. - * - * @param idempotencyKeyName Idempotency Key Name - * @return Map of consent ids and idempotency key vallue if available, else an empty map will be returned - */ - static Map getAttributesFromIdempotencyKey(String idempotencyKeyName) { - try { - return consentCoreService.getConsentAttributesByName(idempotencyKeyName); - } catch (ConsentManagementException e) { - log.debug("No consent ids found for the idempotency key value"); - return new HashMap<>(); - } - } - - /** - * Method to compare the client ID sent in the request and client id retrieved from the database. - * - * @param requestClientID Client ID sent in the request - * @param dbClientID client ID retrieved from the database - * @return true if the client ID sent in the request and client id retrieved from the database are equal - */ - static boolean isClientIDEqual(String requestClientID, String dbClientID) { - if (requestClientID == null) { - return false; - } - return requestClientID.equals(dbClientID); - } - - /** - * Method to check whether difference between two dates is less than the configured time. - * - * @param createdTime Created Time of the request - * @return true if the request is received within allowed time - */ - static boolean isRequestReceivedWithinAllowedTime(long createdTime) { - - if (createdTime == 0L) { - log.debug("Created time is of the previous request is not correctly set. Hence returning false"); - return false; - } - String allowedTimeDuration = OpenBankingConfigParser.getInstance().getIdempotencyAllowedTime(); - if (StringUtils.isNotBlank(allowedTimeDuration)) { - OffsetDateTime createdDate = OffsetDateTime.parse(toISO8601DateTime(createdTime)); - OffsetDateTime currDate = OffsetDateTime.now(createdDate.getOffset()); - - long diffInMinutes = Duration.between(createdDate, currDate).toMinutes(); - return diffInMinutes <= Long.parseLong(allowedTimeDuration); - } else { - log.error("Idempotency allowed duration is not configured in the system. Hence returning false"); - return false; - } - } - - /** - * Convert long date values to ISO 8601 format. ISO 8601 format - "yyyy-MM-dd'T'HH:mm:ssXXX" - * @param epochDate Date value in epoch format - * @return ISO 8601 formatted date - */ - private static String toISO8601DateTime(long epochDate) { - - DateFormat simple = new SimpleDateFormat(IdempotencyConstants.ISO_FORMAT); - Date simpleDateVal = new Date(epochDate * 1000); - return simple.format(simpleDateVal); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidator.java deleted file mode 100644 index 0e6ed237..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidator.java +++ /dev/null @@ -1,301 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common.idempotency; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * Class to handle idempotency related operations. - */ -public class IdempotencyValidator { - - private static final Log log = LogFactory.getLog(IdempotencyValidator.class); - private static final ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance() - .getConsentCoreService(); - - /** - * Method to check whether the request is idempotent. - * This method will first check whether idempotency validation is enabled. After that it will validate whether - * required parameters for validation is present. - * For validation, need to check whether the idempotency key values is present as a consent attribute, if present - * the consent will be retrieved. Finally following conditions will be validated. - * - Whether the client id sent in the request and client id retrieved from the database are equal - * - Whether the difference between two dates is less than the configured time - * - Whether payloads are equal - * - * @param consentManageData Consent Manage Data - * @return IdempotencyValidationResult - * @throws IdempotencyValidationException If an error occurs while validating idempotency - */ - public IdempotencyValidationResult validateIdempotency(ConsentManageData consentManageData) - throws IdempotencyValidationException { - - if (!OpenBankingConfigParser.getInstance().isIdempotencyValidationEnabled()) { - return new IdempotencyValidationResult(false, false); - } - // If request is empty then cannot proceed with idempotency validation - if (consentManageData.getPayload() == null) { - log.error("Request payload is empty. Hence cannot proceed with idempotency validation"); - return new IdempotencyValidationResult(false, false); - } - // If client id is empty then cannot proceed with idempotency validation - if (StringUtils.isBlank(consentManageData.getClientId())) { - log.error("Client ID is empty. Hence cannot proceed with idempotency validation"); - return new IdempotencyValidationResult(false, false); - } - String idempotencyKeyValue = consentManageData.getHeaders().get(getIdempotencyHeaderName()); - // If idempotency key value is empty then cannot proceed with idempotency validation - if (StringUtils.isBlank(idempotencyKeyValue)) { - log.error("Idempotency Key Valueis empty. Hence cannot proceed with idempotency validation"); - return new IdempotencyValidationResult(false, false); - } - try { - String idempotencyKeyName = getIdempotencyAttributeName(consentManageData.getRequestPath()); - if (!IdempotencyConstants.EMPTY_OBJECT.equals(consentManageData.getPayload().toString())) { - // Retrieve consent ids that have the idempotency key name and value as attribute - List consentIds = IdempotencyValidationUtils - .getConsentIdsFromIdempotencyKey(idempotencyKeyName, idempotencyKeyValue); - // Check whether the consent id list is not empty. If idempotency key exists in the database then - // the consent Id list will be not empty. - if (!consentIds.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug(String.format("Idempotency Key %s exists in the database. Hence this is an" + - " idempotent request", idempotencyKeyValue)); - } - for (String consentId : consentIds) { - DetailedConsentResource consentResource = consentCoreService.getDetailedConsent(consentId); - if (consentResource != null) { - return validateIdempotencyConditions(consentManageData, consentResource); - } else { - String errorMsg = String.format(IdempotencyConstants.ERROR_NO_CONSENT_DETAILS, consentId); - log.error(errorMsg); - throw new IdempotencyValidationException(errorMsg); - } - } - } - } else { - return validateIdempotencyWithoutPayload(consentManageData, idempotencyKeyName, idempotencyKeyValue); - } - } catch (IOException e) { - log.error(IdempotencyConstants.JSON_COMPARING_ERROR, e); - throw new IdempotencyValidationException(IdempotencyConstants.JSON_COMPARING_ERROR); - } catch (ConsentManagementException e) { - log.error(IdempotencyConstants.CONSENT_RETRIEVAL_ERROR, e); - return new IdempotencyValidationResult(true, false); - } - return new IdempotencyValidationResult(false, false); - } - - /** - * Method to check whether the idempotency conditions are met for requests without payload. - * This method will validate the following conditions. - * - Whether the idempotency key value is different for the same consent id - * - Whether the client id sent in the request and client id retrieved from the database are equal - * - Whether the difference between two dates is less than the configured time - * - Whether payloads are equal - * - * @param consentManageData Consent Manage Data - * @param idempotencyKeyName Idempotency Key Name - * @param idempotencyKeyValue Idempotency Key value - * @return IdempotencyValidationResult - */ - private IdempotencyValidationResult validateIdempotencyWithoutPayload(ConsentManageData consentManageData, - String idempotencyKeyName, - String idempotencyKeyValue) - throws IdempotencyValidationException, IOException, ConsentManagementException { - - // Retrieve consent ids and idempotency key values that have the idempotency key name - Map attributes = IdempotencyValidationUtils.getAttributesFromIdempotencyKey(idempotencyKeyName); - // Check whether the attributes map is not empty. If idempotency key exists in the database then - // the consent Id list will be not empty. - if (!attributes.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug(String.format("Idempotency Key %s exists in the database. Hence this is an" + - " idempotent request", idempotencyKeyValue)); - } - for (Map.Entry entry : attributes.entrySet()) { - // If the idempotency key value is different for the same consent id then it is not a valid idempotent - if (consentManageData.getRequestPath().contains(entry.getKey()) && - !idempotencyKeyValue.equals(entry.getValue())) { - throw new IdempotencyValidationException(IdempotencyConstants.SAME_CONSENT_ID_ERROR); - } - DetailedConsentResource consentRequest = consentCoreService.getDetailedConsent(entry.getKey()); - if (consentRequest != null) { - return validateIdempotencyConditions(consentManageData, consentRequest); - } else { - String errorMsg = String.format(IdempotencyConstants.ERROR_NO_CONSENT_DETAILS, entry.getKey()); - log.error(errorMsg); - throw new IdempotencyValidationException(errorMsg); - } - } - - } - return new IdempotencyValidationResult(false, false); - } - - /** - * Method to check whether the idempotency conditions are met. - * This method will validate the following conditions. - * - Whether the client id sent in the request and client id retrieved from the database are equal - * - Whether the difference between two dates is less than the configured time - * - Whether payloads are equal - * - * @param consentManageData Consent Manage Data - * @param consentResource Detailed Consent Resource - * @return IdempotencyValidationResult - */ - private IdempotencyValidationResult validateIdempotencyConditions(ConsentManageData consentManageData, - DetailedConsentResource consentResource) - throws IdempotencyValidationException, IOException { - // Compare the client ID sent in the request and client id retrieved from the database - // to validate whether the request is received from the same client - if (IdempotencyValidationUtils.isClientIDEqual(consentResource.getClientID(), - consentManageData.getClientId())) { - // Check whether difference between two dates is less than the configured time - if (IdempotencyValidationUtils.isRequestReceivedWithinAllowedTime(getCreatedTimeOfPreviousRequest( - consentManageData.getRequestPath(), consentResource.getConsentID()))) { - // Compare whether JSON payloads are equal - if (isPayloadSimilar(consentManageData, getPayloadOfPreviousRequest( - consentManageData.getRequestPath(), consentResource.getConsentID()))) { - log.debug("Payloads are similar and request received within allowed" + - " time. Hence this is a valid idempotent request"); - return new IdempotencyValidationResult(true, true, - consentResource, consentResource.getConsentID()); - } else { - log.error(IdempotencyConstants.ERROR_PAYLOAD_NOT_SIMILAR); - throw new IdempotencyValidationException(IdempotencyConstants - .ERROR_PAYLOAD_NOT_SIMILAR); - } - } else { - log.error(IdempotencyConstants.ERROR_AFTER_ALLOWED_TIME); - throw new IdempotencyValidationException(IdempotencyConstants - .ERROR_AFTER_ALLOWED_TIME); - } - } else { - log.error(IdempotencyConstants.ERROR_MISMATCHING_CLIENT_ID); - throw new IdempotencyValidationException(IdempotencyConstants.ERROR_MISMATCHING_CLIENT_ID); - } - } - - /** - * Method to get the Idempotency Attribute Name store in consent Attributes. - * - * @param resourcePath Resource Path - * @return idempotency Attribute Name. - */ - public String getIdempotencyAttributeName(String resourcePath) { - return IdempotencyConstants.IDEMPOTENCY_KEY_NAME; - } - - /** - * Method to get the Idempotency Header Name according to the request. - * - * @return idempotency Header Name. - */ - public String getIdempotencyHeaderName() { - return IdempotencyConstants.X_IDEMPOTENCY_KEY; - } - - /** - * Method to get created time from the Detailed Consent Resource. - * - * @param resourcePath Resource Path - * @param consentId ConsentId - * @return Created Time. - */ - public long getCreatedTimeOfPreviousRequest(String resourcePath, String consentId) { - DetailedConsentResource consentRequest = null; - try { - consentRequest = consentCoreService.getDetailedConsent(consentId); - } catch (ConsentManagementException e) { - log.error(IdempotencyConstants.CONSENT_RETRIEVAL_ERROR, e); - return 0L; - } - if (consentRequest == null) { - return 0L; - } - return consentRequest.getCreatedTime(); - } - - /** - * Method to get payload from previous request. - * - * @param resourcePath Resource Path - * @param consentId ConsentId - * @return Map containing the payload. - */ - public String getPayloadOfPreviousRequest(String resourcePath, String consentId) { - DetailedConsentResource consentRequest = null; - try { - consentRequest = consentCoreService.getDetailedConsent(consentId); - } catch (ConsentManagementException e) { - log.error(IdempotencyConstants.CONSENT_RETRIEVAL_ERROR, e); - return null; - } - if (consentRequest == null) { - return null; - } - return consentRequest.getReceipt(); - } - - /** - * Method to compare whether payloads are equal. - * - * @param consentManageData Consent Manage Data Object - * @param consentReceipt Payload received from database - * @return Whether payloads are equal - */ - public boolean isPayloadSimilar(ConsentManageData consentManageData, String consentReceipt) { - - if (consentManageData.getPayload() == null || consentReceipt == null) { - return false; - } - - JsonNode expectedNode = null; - JsonNode actualNode = null; - try { - ObjectMapper mapper = new ObjectMapper(); - expectedNode = mapper.readTree(consentManageData.getPayload().toString()); - actualNode = mapper.readTree(consentReceipt); - if (log.isDebugEnabled()) { - log.debug(String.format("Expected payload for idempotent request is: %s. But actual payload " + - "received is %s", expectedNode.toString(), actualNode.toString())); - } - } catch (JsonProcessingException e) { - log.error(IdempotencyConstants.JSON_COMPARING_ERROR, e); - return false; - } - return expectedNode.equals(actualNode); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/ConsentAmendmentHistoryEventExecutor.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/ConsentAmendmentHistoryEventExecutor.java deleted file mode 100644 index 178fc3d4..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/ConsentAmendmentHistoryEventExecutor.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.event.executors; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.event.executor.OBEventExecutor; -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Map; - -/** - * Open banking event executor for Consent Amendment History Asynchronous Persistence. - */ -public class ConsentAmendmentHistoryEventExecutor implements OBEventExecutor { - - private static final Log log = LogFactory.getLog(ConsentAmendmentHistoryEventExecutor.class); - - @Override - public void processEvent(OBEvent obEvent) { - - String eventType = obEvent.getEventType(); - if (OpenBankingConfigParser.getInstance().isConsentAmendmentHistoryEnabled() && - (ConsentCoreServiceConstants.CONSENT_AMENDED_STATUS.equalsIgnoreCase(eventType) || - OpenBankingConstants.DEFAULT_STATUS_FOR_REVOKED_CONSENTS.equalsIgnoreCase(eventType))) { - - ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance().getConsentCoreService(); - try { - Map eventData = obEvent.getEventData(); - String consentID = eventData.get("ConsentId").toString(); - - Map consentDataMap = (Map) eventData.get("ConsentDataMap"); - DetailedConsentResource detailedCurrentConsent = (DetailedConsentResource) - consentDataMap.get(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE); - DetailedConsentResource detailedHistoryConsent = (DetailedConsentResource) - consentDataMap.get(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE); - long amendedTimestamp = (long) - consentDataMap.get(ConsentCoreServiceConstants.CONSENT_AMENDMENT_TIME) / 1000; - - String amendmentReason; - if (ConsentCoreServiceConstants.CONSENT_AMENDED_STATUS.equalsIgnoreCase(eventType)) { - amendmentReason = ConsentCoreServiceConstants.AMENDMENT_REASON_CONSENT_AMENDMENT_FLOW; - } else { - amendmentReason = ConsentCoreServiceConstants.AMENDMENT_REASON_CONSENT_REVOCATION; - } - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setDetailedConsentResource(detailedHistoryConsent); - consentHistoryResource.setReason(amendmentReason); - consentHistoryResource.setTimestamp(amendedTimestamp); - - boolean result = consentCoreService.storeConsentAmendmentHistory(consentID, consentHistoryResource, - detailedCurrentConsent); - - if (result) { - if (log.isDebugEnabled()) { - log.debug(String.format("Consent Amendment History of consentID: %s persisted successfully.", - consentID)); - } - } else { - log.error(String.format("Failed to persist Consent Amendment History of consentID : %s. " + - consentID)); - } - } catch (ConsentManagementException e) { - log.error("An error occurred while persisting consent amendment history data.", e); - } - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/VRPEventExecutor.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/VRPEventExecutor.java deleted file mode 100644 index 126ad48a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/VRPEventExecutor.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.event.executors; - -import com.wso2.openbanking.accelerator.common.event.executor.OBEventExecutor; -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.PeriodicLimit; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * This class is responsible for executing Variable Recurring Payments (VRP) events. - * It implements the OBEventExecutor interface and overrides its methods to provide - * specific implementations for VRP events. - */ -public class VRPEventExecutor implements OBEventExecutor { - - public static List validateInstructedAmountWithControlParameters(BigDecimal instructedAmount, - JSONObject controlParameters) { - - /** - * Validates the instructed amount with control parameters and returns a list of PeriodicLimit objects. - * If the instructed amount is greater than the maximum individual amount or the cyclic remaining amount, - * an empty list is returned. If the JSON parsing fails, an empty list is also returned. - * - * @param instructedAmount The instructed amount to be validated - * @param controlParameters The control parameters to be used for validation - * @return A list of PeriodicLimit objects - */ - List periodicLimitsList = new ArrayList<>(); - - BigDecimal maxIndividualAmount = BigDecimal.valueOf(Double.parseDouble(controlParameters. - getAsString(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT))); - - if (instructedAmount.compareTo(maxIndividualAmount) > 0) { - return periodicLimitsList; - } - - JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE); - JSONArray periodicLimits; - - try { - periodicLimits = (JSONArray) parser.parse(controlParameters. - getAsString(ConsentExtensionConstants.PERIODIC_LIMITS)); - } catch (ParseException e) { - // Log the error or handle it as needed - return periodicLimitsList; - } - - long currentMoment = System.currentTimeMillis() / 1000; - - for (Object obj : periodicLimits) { - JSONObject limit = (JSONObject) obj; - BigDecimal amount = BigDecimal. - valueOf(Double.parseDouble(limit.getAsString(ConsentExtensionConstants.AMOUNT))); - long cyclicExpiryTime = Long.parseLong(limit.getAsString(ConsentExtensionConstants.CYCLIC_EXPIRY_TIME)); - BigDecimal cyclicRemainingAmount = BigDecimal. - valueOf(Double.parseDouble(limit.getAsString(ConsentExtensionConstants.CYCLIC_REMAINING_AMOUNT))); - - String periodType = limit.getAsString(ConsentExtensionConstants.PERIOD_TYPE); - String periodAlignment = limit.getAsString(ConsentExtensionConstants.PERIOD_ALIGNMENT); - - PeriodicLimit periodicLimit = new PeriodicLimit(periodType, amount, periodAlignment); - - if (currentMoment <= cyclicExpiryTime) { - if (instructedAmount.compareTo(cyclicRemainingAmount) > 0) { - return periodicLimitsList; - } else { - cyclicRemainingAmount = cyclicRemainingAmount.subtract(instructedAmount); - } - } else { - while (currentMoment > periodicLimit.getCyclicExpiryTime()) { - periodicLimit.setCyclicExpiryTime(); - } - cyclicRemainingAmount = amount; - if (instructedAmount.compareTo(cyclicRemainingAmount) > 0) { - return periodicLimitsList; - } else { - cyclicRemainingAmount = cyclicRemainingAmount.subtract(instructedAmount); - } - } - periodicLimitsList.add(periodicLimit); - } - - return periodicLimitsList; - } - - /** - * Processes the given OBEvent. This method is part of the OBEventExecutor interface and needs to be implemented. - * - * @param obEvent The OBEvent to be processed - */ - @Override - public void processEvent(OBEvent obEvent) { - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/internal/ConsentExtensionsComponent.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/internal/ConsentExtensionsComponent.java deleted file mode 100644 index 0c9e6e95..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/internal/ConsentExtensionsComponent.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.consent.extensions.ciba.authenticator.CIBAPushAuthenticator; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.util.PeriodicalConsentJobActivator; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator; - -/** - * The Component class for activating consent extensions osgi service. - */ -@Component( - name = "com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsComponent", - immediate = true) -public class ConsentExtensionsComponent { - private static Log log = LogFactory.getLog(ConsentExtensionsComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - context.getBundleContext().registerService(ConsentExtensionExporter.class.getName(), - ConsentExtensionExporter.getInstance(), null); - if (log.isDebugEnabled()) { - log.debug("Consent extensions are registered successfully."); - } - new PeriodicalConsentJobActivator().activate(); - if (log.isDebugEnabled()) { - log.debug("Periodical Consent Status Updater Started"); - } - CIBAPushAuthenticator authenticator = new CIBAPushAuthenticator(); - context.getBundleContext().registerService(ApplicationAuthenticator.class.getName(), - authenticator, null); - if (log.isDebugEnabled()) { - log.debug("CIBA Push authenticator bundle is activated"); - } - - } - - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - ConsentExtensionsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - - ConsentExtensionsDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - - } - - @Deactivate - protected void deactivate(ComponentContext context) { - - log.debug("Open banking Consent Extensions component is deactivated"); - } - - @Reference( - service = com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConsentCoreService" - ) - public void setConsentCoreService(ConsentCoreService consentCoreService) { - - log.debug("Setting the Consent Core Service"); - ConsentExtensionsDataHolder.getInstance().setConsentCoreService(consentCoreService); - } - - public void unsetConsentCoreService(ConsentCoreService consentCoreService) { - - log.debug("UnSetting the Consent Core Service"); - ConsentExtensionsDataHolder.getInstance().setConsentCoreService(null); - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/internal/ConsentExtensionsDataHolder.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/internal/ConsentExtensionsDataHolder.java deleted file mode 100644 index 553d2d0d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/internal/ConsentExtensionsDataHolder.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.consent.extensions.admin.builder.ConsentAdminBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.builder.ConsentStepsBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.manage.builder.ConsentManageBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.validate.builder.ConsentValidateBuilder; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Contains Data holder class for consent extensions. - */ -public class ConsentExtensionsDataHolder { - - private static Log log = LogFactory.getLog(ConsentExtensionsDataHolder.class); - private static volatile ConsentExtensionsDataHolder instance; - private OpenBankingConfigurationService openBankingConfigurationService; - private ConsentCoreService consentCoreService; - - private ConsentStepsBuilder consentStepsBuilder; - private ConsentAdminBuilder consentAdminBuilder; - private ConsentManageBuilder consentManageBuilder; - private ConsentValidateBuilder consentValidateBuilder; - - // Prevent instantiation - private ConsentExtensionsDataHolder() {} - - /** - * Return a singleton instance of the data holder. - * - * @return A singleton instance of the data holder - */ - public static synchronized ConsentExtensionsDataHolder getInstance() { - if (instance == null) { - synchronized (ConsentExtensionsDataHolder.class) { - if (instance == null) { - instance = new ConsentExtensionsDataHolder(); - } - } - } - return instance; - } - - public OpenBankingConfigurationService getOpenBankingConfigurationService() { - - return openBankingConfigurationService; - } - - public void setOpenBankingConfigurationService( - OpenBankingConfigurationService openBankingConfigurationService) { - - this.openBankingConfigurationService = openBankingConfigurationService; - - ConsentStepsBuilder consentStepsBuilder = new ConsentStepsBuilder(); - consentStepsBuilder.build(); - this.setConsentStepsBuilder(consentStepsBuilder); - ConsentExtensionExporter.setConsentStepsBuilder(consentStepsBuilder); - - ConsentAdminBuilder consentAdminBuilder = new ConsentAdminBuilder(); - consentAdminBuilder.build(); - this.setConsentAdminBuilder(consentAdminBuilder); - ConsentExtensionExporter.setConsentAdminBuilder(consentAdminBuilder); - - ConsentManageBuilder consentManageBuilder = new ConsentManageBuilder(); - consentManageBuilder.build(); - this.setConsentManageBuilder(consentManageBuilder); - ConsentExtensionExporter.setConsentManageBuilder(consentManageBuilder); - - ConsentValidateBuilder consentValidateBuilder = new ConsentValidateBuilder(); - consentValidateBuilder.build(); - this.setConsentValidateBuilder(consentValidateBuilder); - ConsentExtensionExporter.setConsentValidateBuilder(consentValidateBuilder); - } - - public ConsentStepsBuilder getConsentStepsBuilder() { - return consentStepsBuilder; - } - - public void setConsentStepsBuilder(ConsentStepsBuilder consentStepsBuilder) { - this.consentStepsBuilder = consentStepsBuilder; - } - - public ConsentAdminBuilder getConsentAdminBuilder() { - return consentAdminBuilder; - } - - public void setConsentAdminBuilder(ConsentAdminBuilder consentAdminBuilder) { - this.consentAdminBuilder = consentAdminBuilder; - } - - public ConsentManageBuilder getConsentManageBuilder() { - return consentManageBuilder; - } - - public void setConsentManageBuilder(ConsentManageBuilder consentManageBuilder) { - this.consentManageBuilder = consentManageBuilder; - } - - public ConsentValidateBuilder getConsentValidateBuilder() { - return consentValidateBuilder; - } - - public void setConsentValidateBuilder(ConsentValidateBuilder consentValidateBuilder) { - this.consentValidateBuilder = consentValidateBuilder; - } - - public ConsentCoreService getConsentCoreService() { - return consentCoreService; - } - - public void setConsentCoreService(ConsentCoreService consentCoreService) { - this.consentCoreService = consentCoreService; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/builder/ConsentManageBuilder.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/builder/ConsentManageBuilder.java deleted file mode 100644 index 9e2295a5..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/builder/ConsentManageBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.builder; - -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Builder class for consent manage handler. - */ -public class ConsentManageBuilder { - - private static final Log log = LogFactory.getLog(ConsentManageBuilder.class); - private ConsentManageHandler consentManageHandler = null; - private static String manageHandlerConfigPath = "Consent.ManageHandler"; - - public void build() { - - String handlerConfig = (String) ConsentExtensionsDataHolder.getInstance().getOpenBankingConfigurationService(). - getConfigurations().get(manageHandlerConfigPath); - consentManageHandler = (ConsentManageHandler) OpenBankingUtils.getClassInstanceFromFQN(handlerConfig); - - log.debug("Manage handler loaded successfully"); - } - - public ConsentManageHandler getConsentManageHandler() { - return consentManageHandler; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/AccountConsentManageRequestHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/AccountConsentManageRequestHandler.java deleted file mode 100644 index 83d7d0f2..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/AccountConsentManageRequestHandler.java +++ /dev/null @@ -1,343 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.impl; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventNotificationPersistenceServiceHandler; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Consent Manage request handler class for Account Request Validation. - */ -public class AccountConsentManageRequestHandler implements ConsentManageRequestHandler { - - private static final Log log = LogFactory.getLog(AccountConsentManageRequestHandler.class); - private static final String ACCOUNT_CONSENT_GET_PATH = "account-access-consents"; - private static final String UUID_REGEX = - "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; - private static final String REVOKED_STATUS = "revoked"; - private static final List validPermissions = Arrays.asList( - "ReadAccountsDetail", - "ReadTransactionsDetail", - "ReadBalances"); - private static final String ACCOUNT_CONSENT_CREATE_PATH = "account-access-consents"; - private static final String CREATED_STATUS = "created"; - private static final String AUTH_TYPE_AUTHORIZATION = "authorization"; - - - /** - * Method to handle Account Consent Manage Post Request. - * - * @param consentManageData Object containing request details - */ - @Override - public void handleConsentManagePost(ConsentManageData consentManageData) { - - //Get the request payload from the ConsentManageData - Object request = consentManageData.getPayload(); - - if (request == null || request instanceof JSONArray) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.NOT_JSON_OBJECT_ERROR); - } - - JSONObject requestObject; - if (consentManageData.getRequestPath().equals(ACCOUNT_CONSENT_CREATE_PATH)) { - //Validate Account Initiation request - requestObject = (JSONObject) request; - if (!validateInitiation(requestObject)) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PAYLOAD_INVALID); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Request path invalid"); - } - - ConsentResource requestedConsent = new ConsentResource(consentManageData.getClientId(), - requestObject.toJSONString(), ConsentExtensionConstants.ACCOUNTS, - ConsentExtensionConstants.AWAITING_AUTH_STATUS); - - //Set request object to the response - JSONObject response = requestObject; - - DetailedConsentResource createdConsent; - - appendConsentExpirationTimestampAttribute(requestedConsent); - - //create consent - try { - createdConsent = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .createAuthorizableConsent(requestedConsent, null, - CREATED_STATUS, AUTH_TYPE_AUTHORIZATION, true); - consentManageData.setResponsePayload(ConsentManageUtil.getInitiationResponse(response, createdConsent, - consentManageData, ConsentExtensionConstants.ACCOUNTS)); - consentManageData.setResponseStatus(ResponseStatus.CREATED); - } catch (ConsentManagementException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } - - @Override - public void handleConsentManageGet(ConsentManageData consentManageData) { - - if (consentManageData.getRequestPath().startsWith(ACCOUNT_CONSENT_GET_PATH)) { - String consentId = consentManageData.getRequestPath().split("/")[1]; - if (ConsentManageUtil.isConsentIdValid(consentId)) { - try { - ConsentResource consent = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .getConsent(consentId, false); - if (consent == null) { - log.error("No valid consent found for given information"); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NO_CONSENT_FOR_CLIENT_ERROR); - } - if (!consent.getClientID().equals(consentManageData.getClientId())) { - //Throwing same error as null scenario since client will not be able to identify if consent - // exists if consent does not belong to them - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NO_CONSENT_FOR_CLIENT_ERROR); - } - JSONObject receiptJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE). - parse(consent.getReceipt()); - JSONObject data = (JSONObject) receiptJSON.get("Data"); - data.appendField("ConsentId", consent.getConsentID()); - data.appendField("CreationDateTime", convertEpochDateTime(consent.getCreatedTime())); - data.appendField("StatusUpdateDateTime", convertEpochDateTime(consent.getUpdatedTime())); - receiptJSON.put("Data", data); - consentManageData.setResponsePayload(receiptJSON); - consentManageData.setResponseStatus(ResponseStatus.OK); - } catch (ConsentManagementException | ParseException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Consent ID invalid"); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PATH_INVALID); - } - - } - - @Override - public void handleConsentManageDelete(ConsentManageData consentManageData) { - - if (consentManageData.getRequestPath().startsWith(ConsentExtensionConstants.ACCOUNT_CONSENT_DELETE_PATH)) { - String consentId = consentManageData.getRequestPath().split( - ConsentExtensionConstants.ACCOUNT_CONSENT_DELETE_PATH)[1]; - if (ConsentManageUtil.isConsentIdValid(consentId)) { - try { - ConsentResource consentResource = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .getConsent(consentId, false); - - if (!consentResource.getClientID().equals(consentManageData.getClientId())) { - //Throwing this error in a generic manner since client will not be able to identify if consent - // exists if consent does not belong to them - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NO_CONSENT_FOR_CLIENT_ERROR); - } - - if (REVOKED_STATUS.equals(consentResource.getCurrentStatus())) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, - "Consent already in revoked state"); - } - - boolean success = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .revokeConsentWithReason(consentId, REVOKED_STATUS, - ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - if (!success) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Token revocation unsuccessful"); - } - consentManageData.setResponseStatus(ResponseStatus.NO_CONTENT); - if (success) { - // persist a new notification to the DB - // This is a sample event notification persisting. This can be modified in the Toolkit level - if (OpenBankingConfigParser.getInstance().isRealtimeEventNotificationEnabled()) { - JSONObject notificationInfo = new JSONObject(); - notificationInfo.put("consentID", consentId); - notificationInfo.put("status", "Consent Revocation"); - notificationInfo.put("timeStamp", System.currentTimeMillis()); - EventNotificationPersistenceServiceHandler.getInstance().persistRevokeEvent( - consentResource.getClientID(), consentId, - "Consent Revocation", notificationInfo); - } - } - } catch (ConsentManagementException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Consent ID invalid"); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Request path invalid"); - } - } - - private boolean validateInitiation(JSONObject initiation) { - - if (!initiation.containsKey("Data") || !(initiation.get("Data") instanceof JSONObject)) { - return false; - } - - JSONObject data = (JSONObject) initiation.get("Data"); - - if (!data.containsKey("Permissions") || !(data.get("Permissions") instanceof JSONArray)) { - return false; - } - - JSONArray permissions = (JSONArray) data.get("Permissions"); - for (Object permission : permissions) { - if (!(permission instanceof String)) { - return false; - } - String permissionString = (String) permission; - if (!validPermissions.contains(permissionString)) { - return false; - } - } - - if (!data.containsKey("ExpirationDateTime") || !(data.get("ExpirationDateTime") instanceof String)) { - return false; - } - - if (!isConsentExpirationTimeValid(data.getAsString("ExpirationDateTime"))) { - return false; - } - - if (!data.containsKey("TransactionFromDateTime") || !(data.get("TransactionFromDateTime") instanceof String)) { - return false; - } - - if (!data.containsKey("TransactionToDateTime") || !(data.get("TransactionToDateTime") instanceof String)) { - return false; - } - - if (!isTransactionFromToTimeValid(data.getAsString("TransactionFromDateTime"), - data.getAsString("TransactionToDateTime"))) { - return false; - } - - return true; - } - - private static boolean isConsentExpirationTimeValid(String expDateVal) { - - if (expDateVal == null) { - return true; - } - try { - OffsetDateTime expDate = OffsetDateTime.parse(expDateVal); - OffsetDateTime currDate = OffsetDateTime.now(expDate.getOffset()); - - if (log.isDebugEnabled()) { - log.debug("Provided expiry date is: " + expDate + " current date is: " + currDate); - } - - return expDate.compareTo(currDate) > 0; - } catch (DateTimeParseException e) { - return false; - } - } - - private static boolean isTransactionFromToTimeValid(String fromDateVal, String toDateVal) { - - if (fromDateVal == null || toDateVal == null) { - return true; - } - try { - OffsetDateTime fromDate = OffsetDateTime.parse(fromDateVal); - OffsetDateTime toDate = OffsetDateTime.parse(toDateVal); - - // From date is earlier than To date - return (fromDate.compareTo(toDate) <= 0); - } catch (DateTimeParseException e) { - return false; - } - } - - /** - * Method to append the consent expiration time (UTC) as a consent attribute. - * @param requestedConsent Consent Resource - */ - public static void appendConsentExpirationTimestampAttribute(ConsentResource requestedConsent) { - - Map consentAttributes = requestedConsent.getConsentAttributes(); - JSONObject receiptJSON = null; - try { - receiptJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE). - parse(requestedConsent.getReceipt()); - JSONObject data = null; - if (receiptJSON.containsKey(ConsentExtensionConstants.DATA)) { - data = (JSONObject) receiptJSON.get(ConsentExtensionConstants.DATA); - } - if (data != null && data.containsKey(ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE)) { - String expireTime = data.get(ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE).toString(); - ZonedDateTime zonedDateTime = ZonedDateTime.parse(expireTime); - // Retrieve the UTC timestamp in long from expiry time. - long expireTimestamp = Instant.from(zonedDateTime).getEpochSecond(); - if (consentAttributes == null) { - consentAttributes = new HashMap(); - } - consentAttributes.put(ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE, - Long.toString(expireTimestamp)); - requestedConsent.setConsentAttributes(consentAttributes); - } - } catch (ParseException e) { - log.error("Invalid consent receipt received to append expiration time. : " - + requestedConsent.getConsentID()); - } - } - - private static String convertEpochDateTime(long epochTime) { - - int nanoOfSecond = 0; - ZoneOffset offset = ZoneOffset.UTC; - LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochTime, nanoOfSecond, offset); - return DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").format(ldt); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/CofConsentRequestHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/CofConsentRequestHandler.java deleted file mode 100644 index 7599b2d5..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/CofConsentRequestHandler.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.impl; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.manage.validator.CofConsentRequestValidator; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * Consent Manage request handler class for Confirmation of Funds Request Validation. - */ -public class CofConsentRequestHandler implements ConsentManageRequestHandler { - - private static final Log log = LogFactory.getLog(CofConsentRequestHandler.class); - private static final String CREATED_STATUS = "created"; - private static final String AUTH_TYPE_AUTHORIZATION = "authorization"; - @Override - public void handleConsentManagePost(ConsentManageData consentManageData) { - - //Get the request payload from the ConsentManageData - Object request = consentManageData.getPayload(); - if (!(request instanceof JSONObject)) { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.INVALID_REQ_PAYLOAD); - } - - JSONObject requestObject = (JSONObject) request; - - //Validate COF Initiation request - JSONObject validationResponse = CofConsentRequestValidator.validateCOFInitiation(requestObject); - if (validationResponse.containsKey(ConsentExtensionConstants.IS_VALID) && - !((boolean) validationResponse.get(ConsentExtensionConstants.IS_VALID))) { - log.error(ErrorConstants.PAYLOAD_INVALID); - throw new ConsentException((ResponseStatus) validationResponse.get(ConsentExtensionConstants.HTTP_CODE), - (JSONObject) validationResponse.get(ConsentExtensionConstants.ERRORS)); - } - ConsentResource requestedConsent = new ConsentResource(consentManageData.getClientId(), - requestObject.toJSONString(), ConsentExtensionConstants.FUNDSCONFIRMATIONS, - ConsentExtensionConstants.AWAITING_AUTH_STATUS); - - //Set request object to the response - JSONObject response = requestObject; - - DetailedConsentResource createdConsent; - try { - createdConsent = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .createAuthorizableConsent(requestedConsent, null, - CREATED_STATUS, AUTH_TYPE_AUTHORIZATION, true); - consentManageData.setResponsePayload(ConsentManageUtil.getInitiationResponse(response, createdConsent, - consentManageData, ConsentExtensionConstants.FUNDSCONFIRMATIONS)); - consentManageData.setResponseStatus(ResponseStatus.CREATED); - } catch (ConsentManagementException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - - } - - @Override - public void handleConsentManageGet(ConsentManageData consentManageData) { - - String consentId = consentManageData.getRequestPath().split("/")[1]; - if (ConsentManageUtil.isConsentIdValid(consentId)) { - try { - ConsentResource consent = ConsentServiceUtil.getConsentService().getConsent(consentId, - false); - if (consent == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.RESOURCE_CONSENT_MISMATCH); - } - // Check whether the client id is matching - if (!consent.getClientID().equals(consentManageData.getClientId())) { - //Throwing same error as null scenario since client will not be able to identify if consent - // exists if consent does not belong to them - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NO_CONSENT_FOR_CLIENT_ERROR); - } - JSONObject receiptJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE). - parse(consent.getReceipt()); - consentManageData.setResponsePayload(ConsentManageUtil - .getInitiationRetrievalResponse(receiptJSON, consent, consentManageData, - ConsentExtensionConstants.FUNDSCONFIRMATIONS)); - consentManageData.setResponseStatus(ResponseStatus.OK); - } catch (ConsentManagementException | ParseException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.ACC_INITIATION_RETRIEVAL_ERROR); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.INVALID_CONSENT_ID); - } - } - - @Override - public void handleConsentManageDelete(ConsentManageData consentManageData) { - ConsentManageUtil.handleConsentManageDelete(consentManageData); - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/ConsentManageRequestHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/ConsentManageRequestHandler.java deleted file mode 100644 index c09419dc..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/ConsentManageRequestHandler.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; - -/** - * Abstract Consent Manage Request Handler class. - */ -public interface ConsentManageRequestHandler { - - /** - * Method to handle Account Consent Manage Post Request. - * - * @param consentManageData Object containing request details - */ - void handleConsentManagePost(ConsentManageData consentManageData); - - /** - * Method to handle Consent Manage GET Request. - * - * @param consentManageData Object containing request details - */ - void handleConsentManageGet(ConsentManageData consentManageData); - - /** - * Method to handle Account Consent Manage Post Request. - * - * @param consentManageData Object containing request details - */ - void handleConsentManageDelete(ConsentManageData consentManageData); -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/DefaultConsentManageHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/DefaultConsentManageHandler.java deleted file mode 100644 index d3f26464..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/DefaultConsentManageHandler.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.impl; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.common.factory.AcceleratorConsentExtensionFactory; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageHandler; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.UUID; - -/** - * Consent manage handler default implementation. - */ - -public class DefaultConsentManageHandler implements ConsentManageHandler { - - private static final Log log = LogFactory.getLog(DefaultConsentManageHandler.class); - private static final String INTERACTION_ID_HEADER = "x-fapi-interaction-id"; - private ConsentManageRequestHandler consentManageRequestHandler; - - @Override - public void handleGet(ConsentManageData consentManageData) throws ConsentException { - - if (consentManageData.getHeaders().containsKey(INTERACTION_ID_HEADER)) { - consentManageData.setResponseHeader(INTERACTION_ID_HEADER, - consentManageData.getHeaders().get(INTERACTION_ID_HEADER)); - } else { - consentManageData.setResponseHeader(INTERACTION_ID_HEADER, - UUID.randomUUID().toString()); - } - - //Check whether client ID exists - if (StringUtils.isEmpty(consentManageData.getClientId())) { - log.error(ErrorConstants.MSG_MISSING_CLIENT_ID); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.MSG_MISSING_CLIENT_ID); - } - - String[] requestPathArray; - - if (consentManageData.getRequestPath() == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.RESOURCE_NOT_FOUND); - } else { - requestPathArray = consentManageData.getRequestPath().split("/"); - } - - if (requestPathArray != null && !requestPathArray[0].isEmpty()) { - //Get consent manage request validator according to the request path - consentManageRequestHandler = AcceleratorConsentExtensionFactory - .getConsentManageRequestValidator(requestPathArray[0]); - - if (consentManageRequestHandler != null) { - consentManageRequestHandler.handleConsentManageGet(consentManageData); - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PATH_INVALID); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PATH_INVALID); - } - } - - @Override - public void handlePost(ConsentManageData consentManageData) throws ConsentException { - - //set consent id aa response header - String consentID = UUID.randomUUID().toString(); - if (consentManageData.getHeaders().containsKey(INTERACTION_ID_HEADER)) { - consentManageData.setResponseHeader(INTERACTION_ID_HEADER, - consentManageData.getHeaders().get(INTERACTION_ID_HEADER)); - } else { - consentManageData.setResponseHeader(INTERACTION_ID_HEADER, consentID); - } - - //Get consent manage request validator according to the request path - consentManageRequestHandler = AcceleratorConsentExtensionFactory - .getConsentManageRequestValidator(consentManageData.getRequestPath()); - - if (consentManageRequestHandler != null) { - consentManageRequestHandler.handleConsentManagePost(consentManageData); - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PATH_INVALID); - } - } - - @Override - public void handleDelete(ConsentManageData consentManageData) throws ConsentException { - - if (consentManageData.getHeaders().containsKey(ConsentExtensionConstants.INTERACTION_ID_HEADER)) { - consentManageData.setResponseHeader(ConsentExtensionConstants.INTERACTION_ID_HEADER, - consentManageData.getHeaders().get(ConsentExtensionConstants.INTERACTION_ID_HEADER)); - } else { - consentManageData.setResponseHeader(ConsentExtensionConstants.INTERACTION_ID_HEADER, - UUID.randomUUID().toString()); - } - - String[] requestPathArray; - if (consentManageData.getRequestPath() == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.RESOURCE_NOT_FOUND); - } else { - requestPathArray = consentManageData.getRequestPath().split("/"); - } - - if (requestPathArray != null && !requestPathArray[0].isEmpty()) { - - //Get consent manage request validator according to the request path - consentManageRequestHandler = AcceleratorConsentExtensionFactory - .getConsentManageRequestValidator(requestPathArray[0]); - - if (consentManageRequestHandler != null) { - consentManageRequestHandler.handleConsentManageDelete(consentManageData); - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PATH_INVALID); - } - } - } - - @Override - public void handlePut(ConsentManageData consentManageData) throws ConsentException { - - throw new ConsentException(ResponseStatus.METHOD_NOT_ALLOWED, "Method PUT is not supported"); - } - - @Override - public void handlePatch(ConsentManageData consentManageData) throws ConsentException { - - throw new ConsentException(ResponseStatus.METHOD_NOT_ALLOWED, "Method PATCH is not supported"); - } - - @Override - public void handleFileUploadPost(ConsentManageData consentManageData) throws ConsentException { - - throw new ConsentException(ResponseStatus.METHOD_NOT_ALLOWED, "File upload is not supported"); - } - - @Override - public void handleFileGet(ConsentManageData consentManageData) throws ConsentException { - - throw new ConsentException(ResponseStatus.METHOD_NOT_ALLOWED, "File retrieval is not supported"); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/PaymentConsentRequestHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/PaymentConsentRequestHandler.java deleted file mode 100644 index b8040a50..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/PaymentConsentRequestHandler.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.impl; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.manage.validator.PaymentsConsentRequestValidator; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.HashMap; -import java.util.Map; - - -/** - * Consent Manage request handler class for Payment Request Validation. - */ -public class PaymentConsentRequestHandler implements ConsentManageRequestHandler { - private static final Log log = LogFactory.getLog(PaymentConsentRequestHandler.class); - private static final String CREATED_STATUS = "created"; - private static final String AUTH_TYPE_AUTHORIZATION = "authorization"; - - @Override - public void handleConsentManagePost(ConsentManageData consentManageData) { - - try { - //Validate cutoff datetime - if (ConsentExtensionUtils.shouldInitiationRequestBeRejected()) { - log.error(ErrorConstants.MSG_ELAPSED_CUT_OFF_DATE_TIME); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.PAYMENT_INITIATION_HANDLE_ERROR); - } - - //Get the request payload from the ConsentManageData - Object request = consentManageData.getPayload(); - if (!(request instanceof JSONObject)) { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.INVALID_REQ_PAYLOAD); - } - - JSONObject requestObject = (JSONObject) request; - - //Set request object to the response - JSONObject response = requestObject; - - //Check Idempotency key exists - if (StringUtils.isEmpty(consentManageData.getHeaders() - .get(ConsentExtensionConstants.X_IDEMPOTENCY_KEY))) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.IDEMPOTENCY_KEY_NOT_FOUND); - } - - //Handle payment initiation flows - handlePaymentPost(consentManageData, requestObject, response); - - } catch (ConsentManagementException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.PAYMENT_INITIATION_HANDLE_ERROR); - } - - } - - @Override - public void handleConsentManageGet(ConsentManageData consentManageData) { - String consentId = consentManageData.getRequestPath().split("/")[1]; - if (ConsentManageUtil.isConsentIdValid(consentId)) { - try { - ConsentResource consent = ConsentServiceUtil.getConsentService().getConsent(consentId, - false); - if (consent == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.RESOURCE_CONSENT_MISMATCH); - } - // Check whether the client id is matching - if (!consent.getClientID().equals(consentManageData.getClientId())) { - //Throwing same error as null scenario since client will not be able to identify if consent - // exists if consent does not belong to them - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NO_CONSENT_FOR_CLIENT_ERROR); - } - JSONObject receiptJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE). - parse(consent.getReceipt()); - consentManageData.setResponsePayload(ConsentManageUtil - .getInitiationRetrievalResponse(receiptJSON, consent, consentManageData, - ConsentExtensionConstants.PAYMENTS)); - consentManageData.setResponseStatus(ResponseStatus.OK); - } catch (ConsentManagementException | ParseException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.ACC_INITIATION_RETRIEVAL_ERROR); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.INVALID_CONSENT_ID); - } - } - - @Override - public void handleConsentManageDelete(ConsentManageData consentManageData) { - - } - private void handlePaymentPost(ConsentManageData consentManageData, JSONObject requestObject, JSONObject response) - throws ConsentManagementException { - - DetailedConsentResource createdConsent; - - //Validate Payment Initiation request - JSONObject validationResponse = PaymentsConsentRequestValidator - .validatePaymentInitiation(consentManageData.getRequestPath(), requestObject); - if (validationResponse.containsKey(ConsentExtensionConstants.IS_VALID) && - !((boolean) validationResponse.get(ConsentExtensionConstants.IS_VALID))) { - log.error(ErrorConstants.PAYLOAD_INVALID); - throw new ConsentException((ResponseStatus) validationResponse - .get(ConsentExtensionConstants.HTTP_CODE), - (JSONObject) validationResponse.get(ConsentExtensionConstants.ERRORS)); - } - - ConsentResource requestedConsent = new ConsentResource(consentManageData.getClientId(), - requestObject.toJSONString(), ConsentExtensionConstants.PAYMENTS, - ConsentExtensionConstants.AWAITING_AUTH_STATUS); - - createdConsent = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .createAuthorizableConsent(requestedConsent, null, - CREATED_STATUS, AUTH_TYPE_AUTHORIZATION, true); - - Map consentAttributes = new HashMap(); - consentAttributes.put(ConsentExtensionConstants.IDEMPOTENCY_KEY, consentManageData.getHeaders() - .get(ConsentExtensionConstants.X_IDEMPOTENCY_KEY)); - ConsentServiceUtil.getConsentService().storeConsentAttributes(createdConsent.getConsentID(), - consentAttributes); - consentManageData.setResponsePayload(ConsentManageUtil.getInitiationResponse(response, createdConsent, - consentManageData, ConsentExtensionConstants.PAYMENTS)); - - Map headers = consentManageData.getHeaders(); - //Setting response headers - //Setting created time and idempotency to headers to handle idempotency in Gateway - consentManageData.setResponseHeader(ConsentExtensionConstants.X_IDEMPOTENCY_KEY, - headers.get(ConsentExtensionConstants.X_IDEMPOTENCY_KEY)); - consentManageData.setResponseStatus(ResponseStatus.CREATED); - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/VRPConsentRequestHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/VRPConsentRequestHandler.java deleted file mode 100644 index 9ff83ac1..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/impl/VRPConsentRequestHandler.java +++ /dev/null @@ -1,342 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.impl; - -import com.google.gson.Gson; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.PeriodicLimit; -import com.wso2.openbanking.accelerator.consent.extensions.manage.validator.VRPConsentRequestValidator; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static com.wso2.openbanking.accelerator.consent.extensions.common. - ConsentExtensionConstants.AUTH_TYPE_AUTHORIZATION; -import static com.wso2.openbanking.accelerator.consent.extensions. - common.ConsentExtensionConstants.CREATED_STATUS; - -/** - * Consent Manage request handler class for VRP Payment Request Validation. - */ -public class VRPConsentRequestHandler implements ConsentManageRequestHandler { - - private static final Log log = LogFactory.getLog(VRPConsentRequestHandler.class); - - - /** - * This method is responsible for processing a Variable Recurring Payment Consent Manage POST request. - * It validates the payment request, checks for the existence of an idempotency key. - * - * @param consentManageData Object - */ - @Override - public void handleConsentManagePost(ConsentManageData consentManageData) { - - try { - Object request = consentManageData.getPayload(); - - JSONObject validationResponse = VRPConsentRequestValidator.validateVRPPayload(request); - - if (!(Boolean.parseBoolean(validationResponse.getAsString(ConsentExtensionConstants.IS_VALID)))) { - log.error(validationResponse.get(ConsentExtensionConstants.ERRORS)); - throw new ConsentException((ResponseStatus) validationResponse - .get(ConsentExtensionConstants.HTTP_CODE), - String.valueOf(validationResponse.get(ConsentExtensionConstants.ERRORS))); - } - - if (StringUtils.isEmpty(consentManageData.getHeaders() - .get(ConsentExtensionConstants.X_IDEMPOTENCY_KEY))) { - log.error(ErrorConstants.IDEMPOTENCY_KEY_NOT_FOUND); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.IDEMPOTENCY_KEY_NOT_FOUND); - } - - //Handle payment initiation flows - handlePaymentPost(consentManageData, request); - - } catch (ConsentManagementException e) { - log.error("Error occurred while handling the initiation request", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.VRP_INITIATION_HANDLE_ERROR); - } - } - - /** - * This method is responsible for handling the GET request for retrieving consent initiation details. - * It validates the consent ID, checks if the consent exists,verifies if the consent belongs to the - * client making the request. - * - * @param consentManageData Object - */ - @Override - public void handleConsentManageGet(ConsentManageData consentManageData) { - - String consentId = consentManageData.getRequestPath().split("/")[1]; - if (ConsentManageUtil.isConsentIdValid(consentId)) { - try { - ConsentResource consent = ConsentServiceUtil.getConsentService().getConsent(consentId, - false); - // Check whether the client id is matching - if (!consent.getClientID().equals(consentManageData.getClientId())) { - // Throws the error if the client Ids mismatch - if (log.isDebugEnabled()) { - log.debug(String.format("ClientIds missmatch. " + - "Retrieved client id: %s, ConsentmanageData client id: %s", - consent.getClientID(), consentManageData.getClientId())); - } - - throw new ConsentException(ResponseStatus.BAD_REQUEST, - "Invalid client id passed"); - } - - JSONObject receiptJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE). - parse(consent.getReceipt()); - consentManageData.setResponsePayload(ConsentManageUtil - .getInitiationRetrievalResponse(receiptJSON, consent, consentManageData, - ConsentExtensionConstants.VRP)); - consentManageData.setResponseStatus(ResponseStatus.OK); - } catch (ConsentManagementException | ParseException e) { - log.error(ErrorConstants.INVALID_CLIENT_ID_MATCH, e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.VRP_INITIATION_RETRIEVAL_ERROR); - } - } else { - log.error(ErrorConstants.INVALID_CONSENT_ID); - throw new ConsentException(ResponseStatus.BAD_REQUEST, ErrorConstants.INVALID_CONSENT_ID); - } - } - - /** - * Handles the DELETE request for revoking or deleting a consent. - * - * @param consentManageData Object containing request details - */ - @Override - public void handleConsentManageDelete(ConsentManageData consentManageData) { - - ConsentManageUtil.handleConsentManageDelete(consentManageData); - } - - /** - * Method to handle Variable Recurring Payment POST requests. - * This private method processes Variable Recurring Payment POST requests, creating a new consent - * based on the provided request payload. It performs the following actions: - * - Creates a DetailedConsentResource representing the consent initiation. - * - Stores consent attributes, including the idempotency key. - * - Constructs the response payload containing initiation details and sets appropriate headers. - * - Sets the response status to Created. - * - * @param consentManageData Object containing request details, including client ID, request payload, headers. - * @param request Object - * @throws ConsentManagementException if an error occurs while creating the consent or storing consent attributes. - */ - public void handlePaymentPost(ConsentManageData consentManageData, Object request) - throws ConsentManagementException { - - // Check if the request is a JSONObject - if (!(request instanceof JSONObject)) { - log.error("Invalid request type. Expected JSONObject."); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.PAYLOAD_FORMAT_ERROR); - } - - JSONObject requestObject = (JSONObject) request; - - // Create a ConsentResource representing the requested consent - ConsentResource requestedConsent = createRequestedConsent(consentManageData, requestObject); - - // Create the consent - DetailedConsentResource createdConsent = createConsent(requestedConsent); - - // Set consent attributes for storing - Map consentAttributes = createConsentAttributes(consentManageData); - - // Store consent attributes - ConsentServiceUtil.getConsentService().storeConsentAttributes(createdConsent.getConsentID(), - consentAttributes); - - // Set response payload and headers - setResponse(consentManageData, requestObject, createdConsent); - } - - /** - * Method to Create a ConsentResource object using the provided ConsentManageData and requestObject. - * - * @param consentManageData Object containing request details - * @param requestObject JSON object representing the request - * @return ConsentResource object - */ - private ConsentResource createRequestedConsent(ConsentManageData consentManageData, JSONObject requestObject) { - return new ConsentResource(consentManageData.getClientId(), - requestObject.toJSONString(), ConsentExtensionConstants.VRP, - ConsentExtensionConstants.AWAITING_AUTH_STATUS); - } - - /** - * Method to create a DetailedConsentResource object using the provided ConsentResource. - * - * @param requestedConsent ConsentResource object - * @return DetailedConsentResource object - * @throws ConsentManagementException if an error occurs while creating the consent - */ - private DetailedConsentResource createConsent(ConsentResource requestedConsent) throws ConsentManagementException { - return ConsentServiceUtil.getConsentService() - .createAuthorizableConsent(requestedConsent, null, - CREATED_STATUS, AUTH_TYPE_AUTHORIZATION, true); - } - - /** - * Method to Create a map of consent attributes using the provided ConsentManageData. - * - * @param consentManageData Object containing request details - * @return Map of consent attributes - */ - private Map createConsentAttributes(ConsentManageData consentManageData) { - Map consentAttributes = new HashMap<>(); - consentAttributes.put(ConsentExtensionConstants.IDEMPOTENCY_KEY, consentManageData.getHeaders() - .get(ConsentExtensionConstants.X_IDEMPOTENCY_KEY)); - - JSONObject controlParameters = getControlParameters(consentManageData); - JSONArray periodicLimitsArray = (JSONArray) controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - - List periodicLimitsList = createPeriodicLimitsList(periodicLimitsArray); - - JSONObject controlParams = createControlParameters(controlParameters, periodicLimitsList); - - // Convert the JSONObject to a string - String consentAttributesJson = controlParams.toJSONString(); - - // Add the consentAttributesJson to the consentAttributes - consentAttributes.put(ConsentExtensionConstants.CONTROL_PARAMETERS, consentAttributesJson); - - return consentAttributes; - } - - /** - * Method to retrieve control parameters from the provided ConsentManageData. - * - * @param consentManageData Object containing request details - * @return JSONObject of control parameters - */ - private JSONObject getControlParameters(ConsentManageData consentManageData) { - return (JSONObject) ((JSONObject) ((JSONObject) consentManageData.getPayload()) - .get(ConsentExtensionConstants.DATA)).get(ConsentExtensionConstants.CONTROL_PARAMETERS); - } - - /** - * Method to create a list of PeriodicLimit objects from the provided JSONArray. - * - * @param periodicLimitsArray JSONArray of periodic limits - * @return List of PeriodicLimit objects - */ - private List createPeriodicLimitsList(JSONArray periodicLimitsArray) { - List periodicLimitsList = new ArrayList<>(); - - for (Object periodicLimit : periodicLimitsArray) { - JSONObject jsonObject = (JSONObject) periodicLimit; - String periodType = (String) jsonObject.get(ConsentExtensionConstants.PERIOD_TYPE); - BigDecimal amount = BigDecimal.valueOf(Double.parseDouble((String) jsonObject.get(ConsentExtensionConstants. - AMOUNT))); - String periodAlignment = (String) jsonObject.get(ConsentExtensionConstants.PERIOD_ALIGNMENT); - - PeriodicLimit periodicLimits = new PeriodicLimit(periodType, amount, periodAlignment); - periodicLimitsList.add(periodicLimits); - } - - return periodicLimitsList; - } - - /** - * Method to create JSONObject of control parameters using the provided JSONObject and - * list of PeriodicLimit objects. - * - * @param controlParameters JSONObject of control parameters - * @param periodicLimitsList List of PeriodicLimit objects - * @return JSONObject of control parameters - */ - private JSONObject createControlParameters(JSONObject controlParameters, List periodicLimitsList) { - Gson gson = new Gson(); - - // Get MaximumIndividualAmount from controlParameters - JSONObject maximumIndividualAmountObject = (JSONObject) controlParameters. - get(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT); - double maximumIndividualAmount = Double.parseDouble(maximumIndividualAmountObject - .get(ConsentExtensionConstants.AMOUNT).toString()); - - // Create a new JSONObject - JSONObject jsonObject = new JSONObject(); - - // Add MaximumIndividualAmount to the JSONObject - jsonObject.put(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT, maximumIndividualAmount); - - // Convert the periodicLimitsList to a JSON string - String periodicLimitsJson = gson.toJson(periodicLimitsList); - - // Parse the JSON string back to a JSONArray - JSONArray newPeriodicLimitsArray; - try { - newPeriodicLimitsArray = (JSONArray) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(periodicLimitsJson); - } catch (ParseException e) { - throw new RuntimeException("Error parsing JSON", e); - } - - // Add the PeriodicLimits array to the JSONObject - jsonObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, newPeriodicLimitsArray); - - return jsonObject; - } - - /** - * Method to set the response payload, headers, and status for the provided ConsentManageData using the - * provided requestObject and createdConsent. - * - * @param consentManageData Object containing request details - * @param requestObject JSON object representing the request - * @param createdConsent DetailedConsentResource object representing the created consent - */ - private void setResponse(ConsentManageData consentManageData, - JSONObject requestObject, DetailedConsentResource createdConsent) { - consentManageData.setResponsePayload(ConsentManageUtil.getInitiationResponse(requestObject, createdConsent, - consentManageData, ConsentExtensionConstants.VRP)); - - // Get request headers - Map headers = consentManageData.getHeaders(); - - consentManageData.setResponseHeader(ConsentExtensionConstants.X_IDEMPOTENCY_KEY, - headers.get(ConsentExtensionConstants.X_IDEMPOTENCY_KEY)); - consentManageData.setResponseStatus(ResponseStatus.CREATED); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/ConsentManageData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/ConsentManageData.java deleted file mode 100644 index d6df4a6a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/ConsentManageData.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Data wrapper for consent manage data. - */ -public class ConsentManageData { - - private Map headers; - //Payload can either be a JSONObject or a JSONArray - private Object payload; - private Map queryParams; - private String requestPath; - private String clientId; - private HttpServletRequest request; - private HttpServletResponse response; - private ResponseStatus responseStatus; - private Object responsePayload; - - public ConsentManageData(Map headers, Object payload, Map queryParams, - String requestPath, HttpServletRequest request, HttpServletResponse response) { - this.headers = headers; - this.payload = payload; - this.queryParams = queryParams; - this.requestPath = requestPath; - this.request = request; - this.response = response; - } - - public ConsentManageData(Map headers, Map queryParams, - String requestPath, HttpServletRequest request, HttpServletResponse response) { - this.headers = headers; - this.requestPath = requestPath; - payload = null; - this.queryParams = queryParams; - this.request = request; - this.response = response; - } - - public HttpServletRequest getRequest() { - return request; - } - - public HttpServletResponse getResponse() { - return response; - } - - public Map getQueryParams() { - return queryParams; - } - - public Object getPayload() { - return payload; - } - - public Map getHeaders() { - return headers; - } - - public void setResponseStatus(ResponseStatus responseStatus) { - this.responseStatus = responseStatus; - } - - public void setResponsePayload(Object responsePayload) { - this.responsePayload = responsePayload; - } - - public Object getResponsePayload() { - return responsePayload; - } - - public ResponseStatus getResponseStatus() { - return responseStatus; - } - - public void setResponseHeader(String key, String value) { - response.setHeader(key, value); - } - - public void setResponseHeaders(Map headers) { - for (Map.Entry header : headers.entrySet()) { - setResponseHeader(header.getKey(), header.getValue()); - } - } - - public String getRequestPath() { - return requestPath; - } - - public void setRequestPath(String requestPath) { - this.requestPath = requestPath; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/ConsentManageHandler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/ConsentManageHandler.java deleted file mode 100644 index a3850e99..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/ConsentManageHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; - -/** - * Consent manage handler interface. - */ -public interface ConsentManageHandler { - - /** - * Function to handle GET requests received to the consent manage endpoint. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - public void handleGet(ConsentManageData consentManageData) throws ConsentException; - - /** - * Function to handle POST requests received to the consent manage endpoint. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - public void handlePost(ConsentManageData consentManageData) throws ConsentException; - - /** - * Function to handle DELETE requests received to the consent manage endpoint. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - public void handleDelete(ConsentManageData consentManageData) throws ConsentException; - - /** - * Function to handle PUT requests received to the consent manage endpoint. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - public void handlePut(ConsentManageData consentManageData) throws ConsentException; - - /** - * Function to handle PATCH requests received to the consent manage endpoint. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - public void handlePatch(ConsentManageData consentManageData) throws ConsentException; - - /** - * Function to handle file upload POST requests received to the consent manage endpoint. - * Added as a default method to overcome the issues of existing customers since this was added as an update. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - default void handleFileUploadPost(ConsentManageData consentManageData) throws ConsentException { - - throw new ConsentException(ResponseStatus.METHOD_NOT_ALLOWED, "File upload is not supported"); - } - - /** - * Function to handle file GET requests received to the consent manage endpoint. - * Added as a default method to overcome the issues of existing customers since this was added as an update. - * - * @param consentManageData Object containing data regarding the request - * @throws ConsentException Error object with data required for the error response - */ - default void handleFileGet(ConsentManageData consentManageData) throws ConsentException { - - throw new ConsentException(ResponseStatus.METHOD_NOT_ALLOWED, "File retrieval is not supported"); - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/PeriodicLimit.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/PeriodicLimit.java deleted file mode 100644 index 6bce52bb..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/model/PeriodicLimit.java +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.util.PeriodicTypesEnum; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.DayOfWeek; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.Month; -import java.time.Period; -import java.time.ZoneId; -import java.time.temporal.ChronoUnit; -import java.time.temporal.TemporalAdjusters; - -/** - * This class represents a periodic limit for a VRP consent. - * It includes the period type, amount, period alignment, cyclic expiry time, and cyclic paid amount. - */ -public class PeriodicLimit { - - private final String periodType; - private BigDecimal amount; - private String periodAlignment; - private long cyclicExpiryTime; - private BigDecimal cyclicRemainingAmount; - - /** - * Constructs a new PeriodicLimit with the specified period type, amount, and period alignment. - * It also calculates and sets the cyclic expiry time and cyclic paid amount. - * - * @param periodType the period type - * @param amount the amount - * @param periodAlignment the period alignment - */ - public PeriodicLimit(String periodType, BigDecimal amount, String periodAlignment) { - this.periodType = periodType; - this.amount = amount; - this.periodAlignment = periodAlignment; - setCyclicExpiryTime(); - calculateCyclicPaidAmount(); - } - - public BigDecimal getAmount() { - return amount; - } - - public void setAmount(BigDecimal amount) { - this.amount = amount; - } - - public String getPeriodAlignment() { - return periodAlignment; - } - - public void setPeriodAlignment(String periodAlignment) { - this.periodAlignment = periodAlignment; - } - - public long getCyclicExpiryTime() { - return cyclicExpiryTime; - } - - public BigDecimal getCyclicRemainingAmount() { - return cyclicRemainingAmount; - } - - public void setCyclicRemainingAmount(BigDecimal cyclicRemainingAmount) { - this.cyclicRemainingAmount = cyclicRemainingAmount; - } - - /** - * Calculates and sets the cyclic expiry time based on the period type and period alignment. - */ - public void setCyclicExpiryTime() { - Instant now = Instant.now(); - Instant expiryTime; - - if (periodAlignment.equals(ConsentExtensionConstants.CONSENT)) { - expiryTime = calculateExpiryTimeForConsent(now); - } else if (periodAlignment.equals(ConsentExtensionConstants.CALENDAR)) { - expiryTime = calculateExpiryTimeForCalendar(now); - } else { - throw new IllegalArgumentException("Invalid PeriodAlignment"); - } - - cyclicExpiryTime = expiryTime.getEpochSecond(); - } - - - /** - * Calculates the expiry time for a consent based on the period type. - * - * @param now the current time - * @return the expiry time for a consent - */ - private Instant calculateExpiryTimeForConsent(Instant now) { - PeriodicTypesEnum periodType = PeriodicTypesEnum.valueOf(this.periodType.toUpperCase()); - switch (periodType) { - case DAY: - return now.plus(Duration.ofDays(1)); - case WEEK: - return now.plus(Duration.ofDays(7)); - case FORTNIGHT: - return now.plus(Duration.ofDays(14)); - case MONTH: - return now.plus(Period.ofMonths(1)); - case HALF_YEAR: - return now.plus(Period.ofMonths(6)); - case YEAR: - return now.plus(Period.ofYears(1)); - default: - throw new IllegalArgumentException("Invalid PeriodType"); - } - } - - /** - * Calculates the expiry time for a calendar based on the period type. - * - * @param now the current time - * @return the expiry time for a calendar - */ - private Instant calculateExpiryTimeForCalendar(Instant now) { - LocalDate localDate = now.atZone(ZoneId.systemDefault()).toLocalDate(); - PeriodicTypesEnum periodType = PeriodicTypesEnum.valueOf(this.periodType.toUpperCase()); - switch (periodType) { - case DAY: - return localDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant(); - case WEEK: - return localDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).atStartOfDay(ZoneId.systemDefault()) - .toInstant(); - case FORTNIGHT: - return now.plus(Duration.ofDays(14)); - case MONTH: - return localDate.with(TemporalAdjusters.firstDayOfNextMonth()). - atStartOfDay(ZoneId.systemDefault()).toInstant(); - case HALF_YEAR: - return calculateHalfYearExpiry(localDate); - case YEAR: - return localDate.with(TemporalAdjusters.firstDayOfNextYear()).atStartOfDay(ZoneId.systemDefault()) - .toInstant(); - default: - throw new IllegalArgumentException("Invalid PeriodType"); - } - } - - /** - * Calculates the expiry time for a half year. - * - * @param localDate the current date - * @return the expiry time for a half year - */ - private Instant calculateHalfYearExpiry(LocalDate localDate) { - Month currentMonth = localDate.getMonth(); - if (currentMonth.getValue() < 7) { - return localDate.withMonth(6).with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay(ZoneId.systemDefault()) - .toInstant(); - } else { - return localDate.withMonth(12).with(TemporalAdjusters.lastDayOfMonth()) - .atStartOfDay(ZoneId.systemDefault()) - .toInstant(); - } - } - - /** - * Calculates and sets the cyclic paid amount based on the period alignment. - */ - private void calculateCyclicPaidAmount() { - - if (periodAlignment.equalsIgnoreCase(ConsentExtensionConstants.CONSENT)) { - cyclicRemainingAmount = BigDecimal.valueOf(0); - } else if (periodAlignment.equalsIgnoreCase(ConsentExtensionConstants.CALENDAR)) { - LocalDate now = LocalDate.now(); - LocalDate expiryDate = Instant.ofEpochSecond(cyclicExpiryTime).atZone(ZoneId.systemDefault()) - .toLocalDate(); - BigDecimal divisor = BigDecimal.valueOf(PeriodicTypesEnum.valueOf(this.periodType.toUpperCase()) - .getDivisor()); - BigDecimal days = BigDecimal.valueOf(ChronoUnit.DAYS.between(now, expiryDate)); - cyclicRemainingAmount = amount.divide(divisor, RoundingMode.HALF_UP).multiply(days) - .setScale(2, RoundingMode.HALF_UP); - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/CofConsentRequestValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/CofConsentRequestValidator.java deleted file mode 100644 index 9007ace6..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/CofConsentRequestValidator.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.validator; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Consent Manage validator class for Confirmation of Funds Request Validation. - */ -public class CofConsentRequestValidator { - - private static final Log log = LogFactory.getLog(CofConsentRequestValidator.class); - - /** - * Method to validate COF initiation request. - * @param initiation Initiation Object - * @return JSONObject Validation Response - */ - public static JSONObject validateCOFInitiation(JSONObject initiation) { - - JSONObject validationResponse = new JSONObject(); - - //Check request body is valid and not empty - if (!initiation.containsKey(ConsentExtensionConstants.DATA) || - !(initiation.get(ConsentExtensionConstants.DATA) instanceof JSONObject)) { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR); - return ConsentManageUtil.getValidationResponse(ErrorConstants.RESOURCE_INVALID_FORMAT, - ErrorConstants.PAYLOAD_FORMAT_ERROR, ErrorConstants.PATH_REQUEST_BODY); - } - - JSONObject data = (JSONObject) initiation.get(ConsentExtensionConstants.DATA); - - //Validate json payload expirationDateTime is a future date - if (data.containsKey(ConsentExtensionConstants.EXPIRATION_DATE) && !ConsentManageUtil - .isConsentExpirationTimeValid(data.getAsString(ConsentExtensionConstants.EXPIRATION_DATE))) { - log.error(ErrorConstants.EXPIRED_DATE_ERROR); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID_DATE, - ErrorConstants.EXPIRED_DATE_ERROR, ErrorConstants.PATH_EXPIRATION_DATE); - } - - - if (data.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) { - - Object debtorAccountObj = data.get(ConsentExtensionConstants.DEBTOR_ACC); - //Check whether debtor account is a JsonObject - if (!(debtorAccountObj instanceof JSONObject)) { - log.error(ErrorConstants.MSG_INVALID_DEBTOR_ACC); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_MISSING, - ErrorConstants.MSG_INVALID_DEBTOR_ACC, ErrorConstants.PATH_DEBTOR_ACCOUNT); - } - - JSONObject debtorAccount = (JSONObject) data.get(ConsentExtensionConstants.DEBTOR_ACC); - //Check whether debtor account is not empty - if (debtorAccount.isEmpty()) { - log.error(ErrorConstants.MSG_INVALID_DEBTOR_ACC); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_MISSING, - ErrorConstants.MSG_INVALID_DEBTOR_ACC, ErrorConstants.PATH_DEBTOR_ACCOUNT); - } - - //Check Debtor Account Scheme name exists - if (!debtorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) || - StringUtils.isEmpty(debtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - log.error(ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_MISSING, - ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME, ErrorConstants.COF_PATH_DEBTOR_ACCOUNT_SCHEME); - } - - //Validate Debtor Account Scheme name - if (debtorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) && - (!(debtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME) instanceof String) || - !ConsentManageUtil.isDebtorAccSchemeNameValid(debtorAccount - .getAsString(ConsentExtensionConstants.SCHEME_NAME)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_SCHEME_NAME); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_DEBTOR_ACC_SCHEME_NAME, ErrorConstants.COF_PATH_DEBTOR_ACCOUNT_SCHEME); - } - - //Check Debtor Account Identification existing - if (!debtorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION) || - StringUtils.isEmpty(debtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION))) { - log.error(ErrorConstants.MISSING_DEBTOR_ACC_IDENTIFICATION); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_MISSING, - ErrorConstants.MISSING_DEBTOR_ACC_IDENTIFICATION, - ErrorConstants.COF_PATH_DEBTOR_ACCOUNT_IDENTIFICATION); - } - - //Validate Debtor Account Identification - if (debtorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION) && - (!(debtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION) instanceof String) || - !ConsentManageUtil.isDebtorAccIdentificationValid(debtorAccount - .getAsString(ConsentExtensionConstants.IDENTIFICATION)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_IDENTIFICATION); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_DEBTOR_ACC_IDENTIFICATION, - ErrorConstants.COF_PATH_DEBTOR_ACCOUNT_IDENTIFICATION); - } - - //Validate Debtor Account Name - if (debtorAccount.containsKey(ConsentExtensionConstants.NAME) && - (!(debtorAccount.getAsString(ConsentExtensionConstants.NAME) instanceof String) || - !ConsentManageUtil.isDebtorAccNameValid(debtorAccount - .getAsString(ConsentExtensionConstants.NAME)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_NAME); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_DEBTOR_ACC_NAME, ErrorConstants.COF_PATH_DEBTOR_ACCOUNT_NAME); - } - - //Validate Debtor Account Secondary Identification - if (debtorAccount.containsKey(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) && - (!(debtorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) - instanceof String) || - !ConsentManageUtil.isDebtorAccSecondaryIdentificationValid(debtorAccount - .getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_SEC_IDENTIFICATION); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_DEBTOR_ACC_SEC_IDENTIFICATION, - ErrorConstants.COF_PATH_DEBTOR_ACCOUNT_SECOND_IDENTIFICATION); - } - } else { - log.error(ErrorConstants.MSG_MISSING_DEBTOR_ACC); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_MISSING, - ErrorConstants.MSG_MISSING_DEBTOR_ACC, ErrorConstants.PATH_DEBTOR_ACCOUNT); - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - - } -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/PaymentsConsentRequestValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/PaymentsConsentRequestValidator.java deleted file mode 100644 index 2653591e..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/PaymentsConsentRequestValidator.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.validator; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import com.wso2.openbanking.accelerator.consent.extensions.util.PaymentPayloadValidator; -import net.minidev.json.JSONObject; - -/** - * Consent Manage validator class for Payment Request Validation. - */ -public class PaymentsConsentRequestValidator { - - /** - * Method to validate payment initiation request. - * - * @param requestPath Request Path of the request - * @param initiation Initiation Object - * @return JSONObject Validation Response - */ - public static JSONObject validatePaymentInitiation(String requestPath, JSONObject initiation) { - - JSONObject validationResponse = new JSONObject(); - - //Check request body is valid and not empty - JSONObject dataValidationResult = ConsentManageUtil.validateInitiationDataBody(initiation); - if (!(boolean) dataValidationResult.get(ConsentExtensionConstants.IS_VALID)) { - return dataValidationResult; - } - - JSONObject data = (JSONObject) initiation.get(ConsentExtensionConstants.DATA); - - if (data.containsKey(ConsentExtensionConstants.INITIATION)) { - JSONObject initiationValidationResult = PaymentPayloadValidator - .validatePaymentInitiationPayload(requestPath, - (JSONObject) data.get(ConsentExtensionConstants.INITIATION)); - if (!(boolean) initiationValidationResult.get(ConsentExtensionConstants.IS_VALID)) { - return initiationValidationResult; - } - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/VRPConsentRequestValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/VRPConsentRequestValidator.java deleted file mode 100644 index 0c4f1847..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/manage/validator/VRPConsentRequestValidator.java +++ /dev/null @@ -1,815 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.validator; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - - -/** - * Consent Manage validator class for Variable Recurring Payment Request Validation. - */ -public class VRPConsentRequestValidator { - - private static final Log log = LogFactory.getLog(VRPConsentRequestValidator.class); - - /** - * Method to validate a variable recurring payment request. - * This method performs validation on the variable recurring payment request. - * It checks the validity of the data body, the initiation payload, control parameters, - * and ensures that the risk information is present. If any validation fails, the method returns a detailed - * validation response indicating the error. If all validations pass, the returned validation response - * indicates that the initiation request is valid. - * - * @param request The initiation object containing the variable recurring payment initiation request. - * @return A validation response object indicating whether the initiation request is valid. - */ - public static JSONObject validateVRPPayload(Object request) { - - JSONObject validationResponse = new JSONObject(); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - - //Get the request payload from the ConsentManageData - if (!(request instanceof JSONObject)) { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR); - return ConsentManageUtil.getValidationResponse(ErrorConstants.PAYLOAD_FORMAT_ERROR); - } - - JSONObject requestBody = (JSONObject) request; - //Check request body is valid and not empty - JSONObject dataValidationResult = ConsentManageUtil.validateInitiationDataBody(requestBody); - - if (!(Boolean.parseBoolean(dataValidationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - return dataValidationResult; - } - - //Check consent initiation is valid and not empty - JSONObject initiationValidationResult = VRPConsentRequestValidator.validateConsentInitiation(requestBody); - - if (!(Boolean.parseBoolean(initiationValidationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - return initiationValidationResult; - } - - JSONObject controlParameterValidationResult = VRPConsentRequestValidator. - validateConsentControlParameters(requestBody); - - if (!(Boolean.parseBoolean(controlParameterValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return controlParameterValidationResult; - } - - JSONObject riskValidationResult = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - if (!(Boolean.parseBoolean(riskValidationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - return riskValidationResult; - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Method to validate control parameters for variable recurring payments. - * This method performs validation on the control parameters for variable recurring payments. - * It checks the validity of maximum individual amount, requested execution date-time, and periodic limits. - * If any validation fails, the method returns a detailed validation response indicating the error. - * If all validations pass, the returned validation response indicates that the control parameters are valid. - * - * @param controlParameters The initiation object containing control parameters for variable recurring payments. - * @return A validation response object indicating whether the control parameters are valid. - */ - public static JSONObject validateControlParameters(JSONObject controlParameters) { - JSONObject validationResponse = new JSONObject(); - - JSONObject maximumIndividualAmountResult = validateMaximumIndividualAmount(controlParameters); - if (!(Boolean.parseBoolean(maximumIndividualAmountResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - return maximumIndividualAmountResult; - } - - JSONObject maximumIndividualAmountCurrencyValidationResult = validateMaximumIndividualAmountCurrency - (controlParameters); - if (!(Boolean.parseBoolean(maximumIndividualAmountCurrencyValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return maximumIndividualAmountCurrencyValidationResult; - } - - JSONObject parameterDateTimeValidationResult = validateParameterDateTime(controlParameters); - if (!(Boolean.parseBoolean(parameterDateTimeValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return parameterDateTimeValidationResult; - } - - // Validate Periodic Limits - JSONObject periodicLimitsValidationResult = validatePeriodicLimits(controlParameters); - if (!(Boolean.parseBoolean(periodicLimitsValidationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - return periodicLimitsValidationResult; - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Checks whether the given object is a valid JSONArray. - * This method verifies if the provided object is not null and is an instance of JSONArray. - * It is commonly used to validate whether a given object represents a valid JSON array. - * - * @param value The object to be checked for being a valid JSONArray. - * @return true if the object is a valid JSONArray, false otherwise. - */ - public static boolean isValidJSONArray(Object value) { - String errorMessage = String.format(ErrorConstants.INVALID_PARAMETER_MESSAGE, "periodic limit", - "JSONObject"); - return value instanceof JSONArray; - } - - /** - * Validates the Maximum Individual Amount in the control parameters of a consent request. - * - * @param controlParameters The JSON object representing the control parameters of the consent request. - * @return A JSON object containing the validation response. - */ - public static JSONObject validateMaximumIndividualAmount(JSONObject controlParameters) { - - JSONObject validationResponse = new JSONObject(); - - //Validate Maximum individual amount in control parameters - if (controlParameters.containsKey(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT)) { - - Object maximumIndividualAmount = controlParameters. - get(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT); - - String errorMessage = String.format(ErrorConstants.INVALID_PARAMETER_MESSAGE, - "maximum individual amount", "JSONObject"); - - // Check if the control parameter is valid - if (!isValidJSONObject(maximumIndividualAmount)) { - return ConsentManageUtil.getValidationResponse(errorMessage); - } - - JSONObject maximumIndividualAmountResult = validateJsonObjectKey((JSONObject) maximumIndividualAmount, - ConsentExtensionConstants.AMOUNT, String.class); - if (!(Boolean.parseBoolean(maximumIndividualAmountResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return maximumIndividualAmountResult; - } - } else { - log.error(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT); - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT); - - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the Currency in Maximum Individual Amount in the control parameters of a consent request. - * - * @param controlParameters The JSON object representing the control parameters of the consent request. - * @return A JSON object containing the validation response. - */ - public static JSONObject validateMaximumIndividualAmountCurrency(JSONObject controlParameters) { - // Retrieve the maximum individual amount from the control parameters - Object maximumIndividualAmount = controlParameters.get(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT); - - // Validate the currency of the maximum individual amount - JSONObject maximumIndividualAmountValidationResult = validateJsonObjectKey((JSONObject) maximumIndividualAmount, - ConsentExtensionConstants.CURRENCY, String.class); - if (!(Boolean.parseBoolean(maximumIndividualAmountValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return maximumIndividualAmountValidationResult; - } - String maximumIndividualAmountCurrency; - maximumIndividualAmountCurrency = ((JSONObject) maximumIndividualAmount). - getAsString(ConsentExtensionConstants.CURRENCY); - - // Retrieve the periodic limits from the control parameters - JSONArray periodicLimits = (JSONArray) controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - - // Iterate over the periodic limits and check if the currency of the limit is the same as the currency - // of maximum individual amount - for (Object limitObj : periodicLimits) { - if (limitObj instanceof JSONObject) { - JSONObject limit = (JSONObject) limitObj; - String limitCurrency = limit.getAsString(ConsentExtensionConstants.CURRENCY); - if (!maximumIndividualAmountCurrency.equals(limitCurrency)) { - log.error(ErrorConstants.CURRENCY_MISMATCH); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.CURRENCY_MISMATCH, - ErrorConstants.PATH_PERIOD_LIMIT_CURRENCY); - } - } - } - - // If all validations pass, return a valid response - JSONObject validationResponse = new JSONObject(); - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Method to validate variable recurring payment periodic limits. - * This method validates the periodic limits specified in the control parameters for variable recurring payments. - * It checks if the provided JSON array of periodic limits is valid and then iterates through each limit - * to ensure that required fields such as amount, currency, period alignment, and period type are present and - * meet the specified criteria. - * - * @param controlParameters Initiation Object containing periodic limits - * @return validation response object indicating whether the provided periodic limits are valid - */ - public static JSONObject validatePeriodicLimits(JSONObject controlParameters) { - JSONObject validationResponse = new JSONObject(); - - // Check if the periodic limits key is present - if (controlParameters.containsKey(ConsentExtensionConstants.PERIODIC_LIMITS)) { - - // Retrieve the periodic limits from the control parameters - Object periodicLimit = controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - - // Check if the control parameter is a valid JSON array - if (!isValidJSONArray(periodicLimit)) { - return ConsentManageUtil.getValidationResponse(ErrorConstants.INVALID_PARAMETER_PERIODIC_LIMITS); - } - JSONArray periodicLimits = (JSONArray) controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - // Create a set to store the periodTypes - Set periodTypes = new HashSet<>(); - Iterator parameters = periodicLimits.iterator(); - - while (parameters.hasNext()) { - JSONObject limit = (JSONObject) parameters.next(); - JSONObject amountValidationResult = validateAmountPeriodicLimit(controlParameters); - if (!(Boolean.parseBoolean(amountValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return amountValidationResult; - } - - JSONObject currencyValidationResult = validateCurrencyPeriodicLimit(controlParameters); - if (!(Boolean.parseBoolean(currencyValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return currencyValidationResult; - } - - JSONObject periodAlignmentValidationResult = validatePeriodAlignment(limit); - if (!(Boolean.parseBoolean(periodAlignmentValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return periodAlignmentValidationResult; - } - - JSONObject periodTypeValidationResult = validatePeriodType(limit); - if (!(Boolean.parseBoolean(periodTypeValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return periodTypeValidationResult; - } - - //Check if periodicLimits size exceeds 6 - if (periodicLimits.size() > ErrorConstants.MAXIMUM_PERIODIC_LIMITS) { - log.error(ErrorConstants.INVALID_PERIODIC_LIMIT_SIZE); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_PERIODIC_LIMIT_SIZE, - ErrorConstants.PATH_PERIOD_LIMIT); - } - - // Get the periodType from the limit - String periodType = limit.getAsString(ConsentExtensionConstants.PERIOD_TYPE); - - // If the periodType is already in the set, log an error and return a validation response - if (!periodTypes.add(periodType)) { - log.error(ErrorConstants.DUPLICATE_PERIOD_TYPE); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.DUPLICATE_PERIOD_TYPE, - ErrorConstants.PATH_PERIOD_TYPE); - } - } - } else { - // If periodic limits key is missing, return an error - log.error(ErrorConstants.MISSING_PERIOD_LIMITS); - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_PERIOD_LIMITS); - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the Currency in periodic limits in the control parameters of a consent request. - * - * @param controlParameters The JSON object representing the control parameters of the consent request. - * @return A JSON object containing the validation response. - */ - public static JSONObject validateCurrencyPeriodicLimit(JSONObject controlParameters) { - - JSONObject validationResponse = new JSONObject(); - - JSONArray periodicLimits = (JSONArray) controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - JSONObject currencyValidationResponse = validateAmountCurrencyPeriodicLimits((JSONArray) periodicLimits, - ConsentExtensionConstants.CURRENCY, String.class); - if (!(Boolean.parseBoolean(currencyValidationResponse. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return currencyValidationResponse; - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the Amount in periodic limits in the control parameters of a consent request. - * - * @param controlParameters The JSON object representing the control parameters of the consent request. - * @return A JSON object containing the validation response. - */ - public static JSONObject validateAmountPeriodicLimit(JSONObject controlParameters) { - - JSONObject validationResponse = new JSONObject(); - - JSONArray periodicLimits = (JSONArray) controlParameters.get(ConsentExtensionConstants.PERIODIC_LIMITS); - - JSONObject amountValidationResponse = validateAmountCurrencyPeriodicLimits((JSONArray) periodicLimits, - ConsentExtensionConstants.AMOUNT, String.class); - if (!(Boolean.parseBoolean(amountValidationResponse. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return amountValidationResponse; - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the date-time parameters in the control parameters of a consent request. - * - * @param controlParameters The JSON object representing the control parameters of the consent request. - * @return A JSON object containing the validation response. If the date-time parameters are valid, - * it sets the "IS_VALID" field to true; otherwise, it contains an error response. - */ - public static JSONObject validateParameterDateTime(JSONObject controlParameters) { - JSONObject validationResponse = new JSONObject(); - - if (controlParameters.containsKey(ConsentExtensionConstants.VALID_TO_DATE_TIME)) { - - if (!ConsentManageUtil.isValid8601(controlParameters - .getAsString(ConsentExtensionConstants.VALID_TO_DATE_TIME))) { - log.error(" Date and Time is not in valid ISO 8601 format"); - return ConsentManageUtil.getValidationResponse(ErrorConstants.INVALID_VALID_TO_DATE_TIME); - } - - Object validToDateTimeRetrieval = controlParameters.get(ConsentExtensionConstants.VALID_TO_DATE_TIME); - JSONObject validToDateTimeValidationResponse = isValidDateTimeObject(validToDateTimeRetrieval); - if (!(Boolean.parseBoolean(validToDateTimeValidationResponse. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return validToDateTimeValidationResponse; - } - - String validToDateTimeString = controlParameters.getAsString(ConsentExtensionConstants.VALID_TO_DATE_TIME); - OffsetDateTime validToDateTime = OffsetDateTime.parse(validToDateTimeString); - - if (controlParameters.containsKey(ConsentExtensionConstants.VALID_FROM_DATE_TIME)) { - - if (!ConsentManageUtil.isValid8601(controlParameters - .getAsString(ConsentExtensionConstants.VALID_FROM_DATE_TIME))) { - log.error("Date and Time is not in valid ISO 8601 format"); - return ConsentManageUtil.getValidationResponse(ErrorConstants.INVALID_VALID_FROM_DATE_TIME); - } - - - Object validFromDateTimeRetrieval = controlParameters.get - (ConsentExtensionConstants.VALID_FROM_DATE_TIME); - JSONObject validFromDateTimeValidationResponse = isValidDateTimeObject(validFromDateTimeRetrieval); - if (!(Boolean.parseBoolean(validFromDateTimeValidationResponse. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return validFromDateTimeValidationResponse; - } - - String validFromoDateTimeString = controlParameters.getAsString - (ConsentExtensionConstants.VALID_FROM_DATE_TIME); - - OffsetDateTime validFromDateTime = OffsetDateTime.parse(validFromoDateTimeString); - OffsetDateTime currentDateTime = OffsetDateTime.now(validToDateTime.getOffset()); - - // If ValidToDateTime is older than current date OR ValidToDateTime is older than ValidFromDateTime, - // return error - if (!validFromDateTime.isBefore(currentDateTime) || !currentDateTime.isBefore(validToDateTime)) { - log.error(String.format("Invalid date-time range, " + - "validToDateTime: %s, validFromDateTime: %s, currentDateTime: %s", - validToDateTime, validFromDateTime, currentDateTime)); - - String errorMessage = String.format(ErrorConstants.DATE_INVALID_PARAMETER_MESSAGE); - - return ConsentManageUtil.getValidationResponse(errorMessage); - } - } else { - log.error("validFromDateTime parameter is missing in the payload"); - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_VALID_FROM_DATE_TIME); - } - } else { - log.error("Missing validToDateTime parameter is missing in the payload"); - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_VALID_TO_DATE_TIME); - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validator class to validate the payload of a variable recurring payment initiation. - * This method performs validation on the initiation payload for a variable recurring payment. - * It checks and validates the debtor account and creditor account information if present in the payload. - * If any validation fails, it returns a JSON object with details about the validation error. - * If the initiation payload passes all validations, the returned JSON object indicates a valid initiation. - * - * @param initiation The JSON object representing the variable recurring payment initiation payload. - * @return validationResponse - */ - public static JSONObject validateVRPInitiationPayload(JSONObject initiation) { - - JSONObject validationResponse = new JSONObject(); - - //Validate DebtorAccount - if (initiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) { - - Object debtorAccount = initiation.get(ConsentExtensionConstants.DEBTOR_ACC); - - if (!isValidJSONObject(debtorAccount)) { - String errorMessage = String.format(ErrorConstants.INVALID_PARAMETER_MESSAGE, - "debtor account", "JSONObject"); - - return ConsentManageUtil.getValidationResponse(errorMessage); - } - - JSONObject validationResult = ConsentManageUtil.validateDebtorAccount((JSONObject) debtorAccount); - - if (!(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - log.error(validationResult.get(ConsentExtensionConstants.ERRORS)); - return validationResult; - } - - } else { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC); - return ConsentManageUtil.getValidationResponse(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC); - } - - //Validate CreditorAccount - if (initiation.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) { - - Object creditorAccount = initiation.get(ConsentExtensionConstants.CREDITOR_ACC); - - if (!isValidJSONObject(creditorAccount)) { - String errorMessage = String.format(ErrorConstants.INVALID_PARAMETER_MESSAGE, - "creditor account", "JSONObject"); - - return ConsentManageUtil.getValidationResponse(errorMessage); - } - - JSONObject validationResult = ConsentManageUtil.validateCreditorAccount((JSONObject) creditorAccount); - - if (!(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - log.error(validationResult.get(ConsentExtensionConstants.ERRORS)); - return validationResult; - } - - } else { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR_CREDITOR_ACC); - return ConsentManageUtil.getValidationResponse(ErrorConstants.PAYLOAD_FORMAT_ERROR); - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - - /** - * Validates the presence of a specified key in a JSONObject (either the amount or the currency) - * and checks if the associated value is a non-empty string. - * - * @param parentObj The JSONObject to be validated. - * @param key The key to be checked for presence in the parentObj. - * @param expectedType The expected type of the value associated with the key. - * @param The expected type of the value associated with the key. - * @return true if the specified key is present in the parentObj and the associated value is a - * non-empty string. - */ - public static JSONObject validateJsonObjectKey(JSONObject parentObj, String key, Class expectedType) { - JSONObject validationResponse = new JSONObject(); - //Refractor removing passing class - if (parentObj != null) { - if (parentObj.containsKey(key)) { - Object value = parentObj.get(key); - - if (expectedType.isInstance(value)) { - if (value instanceof String && !((String) value).isEmpty()) { - if ("Amount".equals(key)) { - // For the "amount" key, try parsing as Double allowing letters - if (isDouble((String) value)) { - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } else { - String errorMessage = "The value of '" + key + "' is not a valid number"; - return ConsentManageUtil.getValidationResponse(errorMessage); - } - } else { - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - } else { - String errorMessage = "The value of '" + key + "' is not a " + expectedType.getSimpleName() - + " or the value is empty"; - return ConsentManageUtil.getValidationResponse(errorMessage); - } - } else { - String errorMessage = "The value of '" + key + "' is not of type " + expectedType.getSimpleName(); - return ConsentManageUtil.getValidationResponse(errorMessage); - } - } else { - String errorMessage = "Mandatory parameter '" + key + "' is not present in payload"; - return ConsentManageUtil.getValidationResponse(errorMessage); - } - } else { - String errorMessage = "parameter passed in is null"; - return ConsentManageUtil.getValidationResponse(errorMessage); - } - } - - /** - * Validates the presence of a specified key in a JSONArray (either the amount or the currency) - * in periodiclimits and checks if the associated value is a non-empty string. - * - * @param parentArray The JSONObject to be validated. - * @param key The key to be checked for presence in the parentObj. - * @param expectedType The expected type of the value associated with the key. - * @param The expected type of the value associated with the key. - * @return A JSONObject containing validation results for the entire array. - */ - public static JSONObject validateAmountCurrencyPeriodicLimits(JSONArray parentArray, String key, - Class expectedType) { - JSONObject validationResponse = new JSONObject(); - - if (parentArray != null) { - for (Object obj : parentArray) { - if (obj instanceof JSONObject) { - - JSONObject jsonObject = (JSONObject) obj; - JSONObject elementValidationResult = validateJsonObjectKey(jsonObject, key, expectedType); - - if (!(Boolean.parseBoolean(elementValidationResult.getAsString - (ConsentExtensionConstants.IS_VALID)))) { - return elementValidationResult; - } - } - } - } else { - String errorMessage = "parameter passed in is null"; - return ConsentManageUtil.getValidationResponse(errorMessage); - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - - /** - Checks if a given string can be parsed into a double value. - @param str The string to be checked. - @return True if the string can be parsed into a double value, false otherwise. - */ - private static boolean isDouble(String str) { - try { - Double.parseDouble(str); - return true; - } catch (NumberFormatException e) { - return false; - } - } - - /** - * Validates the consent initiation payload in the VRP request. - * - * @param request The JSONObject representing the VRP request. - * @return A JSONObject containing the validation response. - */ - public static JSONObject validateConsentInitiation(JSONObject request) { - - JSONObject validationResponse = new JSONObject(); - - JSONObject requestBody = (JSONObject) request; - JSONObject data = (JSONObject) requestBody.get(ConsentExtensionConstants.DATA); - - //Validate initiation in the VRP payload - if (data.containsKey(ConsentExtensionConstants.INITIATION)) { - - Object initiation = data.get(ConsentExtensionConstants.INITIATION); - - if (!isValidJSONObject(initiation)) { - String errorMessage = String.format(ErrorConstants.INVALID_PARAMETER_MESSAGE, - "initiation", "JSONObject"); - - return ConsentManageUtil.getValidationResponse(errorMessage); - } - - JSONObject initiationValidationResult = VRPConsentRequestValidator - .validateVRPInitiationPayload((JSONObject) initiation); - - if (!(Boolean.parseBoolean(initiationValidationResult.getAsString(ConsentExtensionConstants.IS_VALID)))) { - return initiationValidationResult; - } - } else { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR_INITIATION); - return ConsentManageUtil.getValidationResponse(ErrorConstants.PAYLOAD_FORMAT_ERROR_INITIATION); - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the consent control parameters in the VRP request payload. - * - * @param request The JSONObject representing the VRP request. - * @return A JSONObject containing the validation response. - */ - public static JSONObject validateConsentControlParameters(JSONObject request) { - - JSONObject validationResponse = new JSONObject(); - - JSONObject requestBody = (JSONObject) request; - JSONObject data = (JSONObject) requestBody.get(ConsentExtensionConstants.DATA); - - //Validate the ControlParameter in the payload - if (data.containsKey(ConsentExtensionConstants.CONTROL_PARAMETERS)) { - - Object controlParameters = data.get(ConsentExtensionConstants.CONTROL_PARAMETERS); - - if (!isValidJSONObject(controlParameters)) { - String errorMessage = String.format(ErrorConstants.INVALID_PARAMETER_MESSAGE, - "control parameters", "JSONObject"); - - return ConsentManageUtil.getValidationResponse(errorMessage); - } - - JSONObject controlParameterValidationResult = - VRPConsentRequestValidator.validateControlParameters((JSONObject) - data.get(ConsentExtensionConstants.CONTROL_PARAMETERS)); - - if (!(Boolean.parseBoolean(controlParameterValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID)))) { - return controlParameterValidationResult; - } - } else { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR_CONTROL_PARAMETER); - return ConsentManageUtil.getValidationResponse(ErrorConstants.PAYLOAD_FORMAT_ERROR_CONTROL_PARAMETER); - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the risk information in the VRP request payload. - * - * @param request The JSONObject representing the VRP request. - * @return A JSONObject containing the validation response. - */ - public static JSONObject validateConsentRisk(JSONObject request) { - - JSONObject validationResponse = new JSONObject(); - - JSONObject requestBody = (JSONObject) request; - JSONObject data = (JSONObject) requestBody.get(ConsentExtensionConstants.DATA); - - // Check Risk key is mandatory - if (!requestBody.containsKey(ConsentExtensionConstants.RISK) || - !(requestBody.get(ConsentExtensionConstants.RISK) instanceof JSONObject - || ((JSONObject) requestBody.get(ConsentExtensionConstants.DATA)).isEmpty())) { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK); - return ConsentManageUtil.getValidationResponse(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK); - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Validates the periodic alignment in the VRP request payload. - * - * @param limit The JSONObject representing the VRP request. - * @return A JSONObject containing the validation response. - */ - public static JSONObject validatePeriodAlignment(JSONObject limit) { - JSONObject validationResponse = new JSONObject(); - - if (limit.containsKey(ConsentExtensionConstants.PERIOD_ALIGNMENT)) { - Object periodAlignmentObj = limit.get(ConsentExtensionConstants.PERIOD_ALIGNMENT); - - if (periodAlignmentObj instanceof String && !((String) periodAlignmentObj).isEmpty()) { - String periodAlignment = (String) periodAlignmentObj; - - if (ConsentExtensionConstants.CONSENT.equals(periodAlignment) || - ConsentExtensionConstants.CALENDAR.equals(periodAlignment)) { - - validationResponse.put("isValid", true); - validationResponse.put("periodAlignment", periodAlignment); - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants.INVALID_PERIOD_ALIGNMENT); - } - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants. - PAYLOAD_FORMAT_ERROR_PERIODIC_LIMITS_ALIGNMENT); - } - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_PERIOD_ALIGNMENT); - } - return validationResponse; - } - - /** - * Validates the periodic type in the VRP request payload. - * - * @param limit The JSONObject representing the VRP request. - * @return A JSONObject containing the validation response. - */ - public static JSONObject validatePeriodType(JSONObject limit) { - JSONObject validationResponse = new JSONObject(); - - if (limit.containsKey(ConsentExtensionConstants.PERIOD_TYPE)) { - Object periodTypeObj = limit.get(ConsentExtensionConstants.PERIOD_TYPE); - - if (periodTypeObj instanceof String && !((String) periodTypeObj).isEmpty()) { - String periodType = (String) periodTypeObj; - - if (ConsentExtensionConstants.DAY.equals(periodType) || - ConsentExtensionConstants.WEEK.equals(periodType) || - ConsentExtensionConstants.FORTNIGHT.equals(periodType) || - ConsentExtensionConstants.MONTH.equals(periodType) || - ConsentExtensionConstants.HALF_YEAR.equals(periodType) || - ConsentExtensionConstants.YEAR.equals(periodType)) { - - validationResponse.put("isValid", true); - validationResponse.put("periodAlignment", periodType); - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants.INVALID_PERIOD_TYPE); - } - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants. - PAYLOAD_FORMAT_ERROR_PERIODIC_LIMITS_PERIOD_TYPE); - } - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_PERIOD_TYPE); - } - return validationResponse; - } - - /** - * Checks if the given Object is a JSONObject and the JSONObject is non-empty . - * - * @param value The Object to be validated. - * @return true if the object is a non-null and non-empty JSONObject. - */ - public static boolean isValidJSONObject(Object value) { - return value instanceof JSONObject && !((JSONObject) value).isEmpty(); - } - - /** - * Checks if the given object is a valid date-time string and it is non empty. - * - * @param value The object to be checked for a valid date-time format. - * @return True if the object is a non-empty string in ISO date-time format, false otherwise. - */ - private static final DateTimeFormatter dateTimeFormat = DateTimeFormatter.ISO_DATE_TIME; - - public static JSONObject isValidDateTimeObject(Object value) { - JSONObject validationResponse = new JSONObject(); - - if (value instanceof String && !((String) value).isEmpty()) { - try { - String dateTimeString = (String) value; - dateTimeFormat.parse(dateTimeString); - } catch (DateTimeParseException e) { - return ConsentManageUtil.getValidationResponse(ErrorConstants.INVALID_DATE_TIME_FORMAT); - } - } else { - return ConsentManageUtil.getValidationResponse(ErrorConstants.MISSING_DATE_TIME_FORMAT); - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/ConsentManageUtil.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/ConsentManageUtil.java deleted file mode 100644 index f4297901..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/ConsentManageUtil.java +++ /dev/null @@ -1,664 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import net.minidev.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.regex.Pattern; - -/** - * Consent manage util class for accelerator. - */ -public class ConsentManageUtil { - private static final Log log = LogFactory.getLog(ConsentManageUtil.class); - private static final OpenBankingConfigParser parser = OpenBankingConfigParser.getInstance(); - - /** - * Check whether valid Data object is provided. - * - * @param initiationRequestbody Data object in initiation payload - * @return whether the Data object is valid - */ - public static JSONObject validateInitiationDataBody(JSONObject initiationRequestbody) { - JSONObject validationResponse = new JSONObject(); - - if (!initiationRequestbody.containsKey(ConsentExtensionConstants.DATA) || !(initiationRequestbody. - get(ConsentExtensionConstants.DATA) - instanceof JSONObject) || ((JSONObject) initiationRequestbody.get(ConsentExtensionConstants.DATA)) - .isEmpty()) { - log.error(ErrorConstants.PAYLOAD_FORMAT_ERROR); - return ConsentManageUtil.getValidationResponse(ErrorConstants.RESOURCE_INVALID_FORMAT, - ErrorConstants.PAYLOAD_FORMAT_ERROR, ErrorConstants.PATH_REQUEST_BODY); - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - /** - * Method to construct the consent manage validation response. - * - * @param errorCode Error Code - * @param errorMessage Error Message - * @param errorPath Error Path - * @return JSONObject Validation response - */ - public static JSONObject getValidationResponse(String errorCode, String errorMessage, String errorPath) { - JSONObject validationResponse = new JSONObject(); - - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, errorMessage); - return validationResponse; - } - - /** - * Method to construct the consent manage validation response for vrp. - * - * @param errorMessage Error Message - * - * @return JSONObject Validation response - */ - public static JSONObject getValidationResponse(String errorMessage) { - JSONObject validationResponse = new JSONObject(); - - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, errorMessage); - return validationResponse; - } - - /** - * Method to validate debtor account. - * - * @param debtorAccount Debtor Account object - * @return JSONObject Validation response - */ - public static JSONObject validateDebtorAccount(JSONObject debtorAccount) { - - JSONObject validationResponse = new JSONObject(); - //Check Debtor Account Scheme name exists - if (!debtorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) || - StringUtils.isEmpty(debtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - log.error(ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME); - - return validationResponse; - } - - //Validate Debtor Account Scheme name Length - if (debtorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) && - !ConsentManageUtil.validateDebtorAccSchemeNameLength(debtorAccount - .getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_SCHEME_NAME_LENGTH); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, - ErrorConstants.INVALID_DEBTOR_ACC_SCHEME_NAME_LENGTH); - - return validationResponse; - } - - //Validate Debtor Account Scheme name - if (debtorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) && - (!(debtorAccount.get(ConsentExtensionConstants.SCHEME_NAME) instanceof String) || - !ConsentManageUtil.isDebtorAccSchemeNameValid(debtorAccount - .getAsString(ConsentExtensionConstants.SCHEME_NAME)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_SCHEME_NAME); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_DEBTOR_ACC_SCHEME_NAME); - - return validationResponse; - } - - //Check Debtor Account Identification existing - if (!debtorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION) || - StringUtils.isEmpty(debtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION))) { - log.error(ErrorConstants.MISSING_DEBTOR_ACC_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.MISSING_DEBTOR_ACC_IDENTIFICATION); - - return validationResponse; - } - - //Validate Debtor Account Identification - if (debtorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION) && - (!(debtorAccount.get(ConsentExtensionConstants.IDENTIFICATION) instanceof String) || - !ConsentManageUtil.isDebtorAccIdentificationValid(debtorAccount - .getAsString(ConsentExtensionConstants.IDENTIFICATION)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_DEBTOR_ACC_IDENTIFICATION); - - return validationResponse; - } - - //Validate Debtor Account Name - if (debtorAccount.containsKey(ConsentExtensionConstants.NAME) && - (!(debtorAccount.get(ConsentExtensionConstants.NAME) instanceof String) || - !ConsentManageUtil.isDebtorAccNameValid(debtorAccount - .getAsString(ConsentExtensionConstants.NAME)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_NAME); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_DEBTOR_ACC_NAME); - - return validationResponse; - } - - //Validate Debtor Account Secondary Identification - if (debtorAccount.containsKey(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) && - (!(debtorAccount.get(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) instanceof String) || - !ConsentManageUtil.isDebtorAccSecondaryIdentificationValid(debtorAccount - .getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION)))) { - log.error(ErrorConstants.INVALID_DEBTOR_ACC_SEC_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, - ErrorConstants.INVALID_DEBTOR_ACC_SEC_IDENTIFICATION); - - return validationResponse; - } - - //Validate Sort Code number scheme - String schemeName = debtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME); - String identification = debtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION); - if (!checkSortCodeSchemeNameAndIdentificationValidity(schemeName, identification)) { - log.error(ErrorConstants.INVALID_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_IDENTIFICATION); - - return validationResponse; - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - - return validationResponse; - } - - /** - * Validate creditor account. - * - * @param creditorAccount Creditor Account object - * @return JSONObject Validation response - */ - public static JSONObject validateCreditorAccount(JSONObject creditorAccount) { - - JSONObject validationResponse = new JSONObject(); - //Check Creditor Account Scheme name exists - if (!creditorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) || - StringUtils.isEmpty(creditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - log.error(ErrorConstants.MISSING_CREDITOR_ACC_SCHEME_NAME); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.MISSING_CREDITOR_ACC_SCHEME_NAME); - return validationResponse; - } - - //Validate Creditor Account Scheme name Length - if (creditorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) && - !ConsentManageUtil.validateDebtorAccSchemeNameLength(creditorAccount - .getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - log.error(ErrorConstants.INVALID_CREDITOR_ACC_SCHEME_NAME_LENGTH); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, - ErrorConstants.INVALID_CREDITOR_ACC_SCHEME_NAME_LENGTH); - return validationResponse; - } - - //Validate Creditor Account Scheme name - if (creditorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME) && - (!(creditorAccount.get(ConsentExtensionConstants.SCHEME_NAME) instanceof String) || - !ConsentManageUtil.isDebtorAccSchemeNameValid(creditorAccount - .getAsString(ConsentExtensionConstants.SCHEME_NAME)))) { - log.error(ErrorConstants.INVALID_CREDITOR_ACC_SCHEME_NAME); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_CREDITOR_ACC_SCHEME_NAME); - return validationResponse; - } - - //Check Creditor Account Identification existing - if (!creditorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION) || - StringUtils.isEmpty(creditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION))) { - log.error(ErrorConstants.MISSING_CREDITOR_ACC_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, - ErrorConstants.MISSING_CREDITOR_ACC_IDENTIFICATION); - return validationResponse; - } - - //Validate Creditor Account Identification - if (creditorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION) && - (!(creditorAccount.get(ConsentExtensionConstants.IDENTIFICATION) instanceof String) || - !ConsentManageUtil.isDebtorAccIdentificationValid(creditorAccount - .getAsString(ConsentExtensionConstants.IDENTIFICATION)))) { - log.error(ErrorConstants.INVALID_CREDITOR_ACC_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, - ErrorConstants.INVALID_CREDITOR_ACC_IDENTIFICATION); - return validationResponse; - } - - //Validate Creditor Account Name - if (creditorAccount.containsKey(ConsentExtensionConstants.NAME) && - (!(creditorAccount.get(ConsentExtensionConstants.NAME) instanceof String) || - !ConsentManageUtil.isDebtorAccNameValid(creditorAccount - .getAsString(ConsentExtensionConstants.NAME)))) { - log.error(ErrorConstants.INVALID_CREDITOR_ACC_NAME); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_CREDITOR_ACC_NAME); - return validationResponse; - } - - //Validate Creditor Account Secondary Identification - if (creditorAccount.containsKey(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) && - (!(creditorAccount.get(ConsentExtensionConstants.SECONDARY_IDENTIFICATION) instanceof String) || - !ConsentManageUtil.isDebtorAccSecondaryIdentificationValid(creditorAccount - .getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION)))) { - log.error(ErrorConstants.INVALID_CREDITOR_ACC_SEC_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, - ErrorConstants.INVALID_CREDITOR_ACC_SEC_IDENTIFICATION); - return validationResponse; - } - - //Validate Sort Code number scheme - String schemeName = creditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME); - String identification = creditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION); - if (!checkSortCodeSchemeNameAndIdentificationValidity(schemeName, identification)) { - log.error(ErrorConstants.INVALID_IDENTIFICATION); - validationResponse.put(ConsentExtensionConstants.IS_VALID, false); - validationResponse.put(ConsentExtensionConstants.HTTP_CODE, ResponseStatus.BAD_REQUEST); - validationResponse.put(ConsentExtensionConstants.ERRORS, ErrorConstants.INVALID_IDENTIFICATION); - return validationResponse; - } - - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } - - - /** - * Method to handle the Payment/cof Consent Delete requests. - * - * @param consentManageData Object containing request details - */ - public static void handleConsentManageDelete(ConsentManageData consentManageData) { - - String consentId = consentManageData.getRequestPath().split("/")[1]; - Boolean shouldRevokeTokens; - if (ConsentManageUtil.isConsentIdValid(consentId)) { - try { - ConsentResource consentResource = ConsentServiceUtil.getConsentService() - .getConsent(consentId, false); - - if (!consentResource.getClientID().equals(consentManageData.getClientId())) { - //Throwing this error in a generic manner since client will not be able to identify if consent - // exists if consent does not belong to them - throw new ConsentException(ResponseStatus.BAD_REQUEST, - ErrorConstants.NO_CONSENT_FOR_CLIENT_ERROR); - } - - if (ConsentExtensionConstants.REVOKED_STATUS.equals(consentResource.getCurrentStatus())) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, - "Consent already in revoked state"); - } - - //Revoke tokens related to the consent if the flag 'shouldRevokeTokens' is true. - shouldRevokeTokens = ConsentExtensionConstants.AUTHORIZED_STATUS - .equals(consentResource.getCurrentStatus()); - - boolean success = ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .revokeConsent(consentId, ConsentExtensionConstants.REVOKED_STATUS, null, - shouldRevokeTokens); - if (!success) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Token revocation unsuccessful"); - } - consentManageData.setResponseStatus(ResponseStatus.NO_CONTENT); - } catch (ConsentManagementException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } else { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Consent ID invalid"); - } - } - - /** - * Utility class to check whether the Debtor Account Scheme name length. - * - * @param debtorAccSchemeName Debtor Account Scheme Name - * @return boolean Whether the Debtor Account Scheme name length is valid - */ - public static boolean validateDebtorAccSchemeNameLength(String debtorAccSchemeName) { - if (log.isDebugEnabled()) { - log.debug("debtorAccSchemeName: " + debtorAccSchemeName); - } - - return (debtorAccSchemeName.length() <= 256); - } - - /** - * Utility class to check whether the Debtor Account Scheme name matches with Enum values. - * - * @param debtorAccSchemeName Debtor Account Scheme Name - * @return boolean Whether the Debtor Account Scheme name is valid - */ - public static boolean isDebtorAccSchemeNameValid(String debtorAccSchemeName) { - if (log.isDebugEnabled()) { - log.debug("debtorAccSchemeName: " + debtorAccSchemeName); - } - - EnumSet set = EnumSet.allOf(DebtorAccountSchemeNameEnum.class); - boolean result = set.contains(DebtorAccountSchemeNameEnum.fromValue(debtorAccSchemeName)); - if (log.isDebugEnabled()) { - log.debug("Result: " + result); - } - return result; - } - - /** - * Utility class to check whether the Debtor Account Identification is valid. - * - * @param debtorAccIdentification Debtor Account Identification - * @return boolean Whether the Debtor Account Identification is valid - */ - public static boolean isDebtorAccIdentificationValid(String debtorAccIdentification) { - if (log.isDebugEnabled()) { - log.debug("debtorAccIdentification: " + debtorAccIdentification); - } - - return (debtorAccIdentification.length() <= 256); - } - - /** - * Utility class to check whether the Debtor Account Name is valid. - * - * @param debtorAccName Debtor Account Name - * @return boolean Whether the Debtor Account Name is valid - */ - public static boolean isDebtorAccNameValid(String debtorAccName) { - if (log.isDebugEnabled()) { - log.debug("debtorAccName: " + debtorAccName); - } - - return (debtorAccName.length() <= 350); - } - - /** - * Utility class to check whether the Debtor AccountSecondary Identification is valid. - * - * @param debtorAccSecondaryIdentification Debtor Account Secondary Identification - * @return boolean Whether the Debtor Account Secondary Identification is valid - */ - public static boolean isDebtorAccSecondaryIdentificationValid(String debtorAccSecondaryIdentification) { - if (log.isDebugEnabled()) { - log.debug("debtorAccSecondaryIdentification: " + debtorAccSecondaryIdentification); - } - - return (debtorAccSecondaryIdentification.length() <= 34); - } - - /** - * Utility class to check whether the SortCode SchemeName and Identification is valid. - * - * @param schemeName Scheme name - * @param identification Identification - * @return - */ - private static boolean checkSortCodeSchemeNameAndIdentificationValidity(String schemeName, String identification) { - - boolean isValid = true; - if ((ConsentExtensionConstants.OB_SORT_CODE_ACCOUNT_NUMBER.equals(schemeName) - || ConsentExtensionConstants.SORT_CODE_ACCOUNT_NUMBER.equals(schemeName)) && - (StringUtils.isNotEmpty(identification) && - !(identification.length() == ConsentExtensionConstants.ACCOUNT_IDENTIFICATION_LENGTH && - identification.matches(ConsentExtensionConstants.SORT_CODE_PATTERN)))) { - isValid = false; - } - return isValid; - } - - /** - * Check whether the local instrument is supported. - * - * @param localInstrument Local Instrument value to validate - * @return Whether the local instrument is valid - */ - public static boolean validateLocalInstrument(String localInstrument) { - ArrayList defaultLocalInstrumentList = new ArrayList<>(Arrays.asList( - "OB.BACS", - "OB.BalanceTransfer", "OB.CHAPS", "OB.Euro1", "OB.FPS", "OB.Link", - "OB.MoneyTransfer", "OB.Paym", "OB.SEPACreditTransfer", - "OB.SEPAInstantCreditTransfer", "OB.SWIFT", "OB.Target2")); - - String customValues = (String) parser.getConfiguration().get( - ConsentExtensionConstants.CUSTOM_LOCAL_INSTRUMENT_VALUES); - if (customValues != null) { - - String[] customLocalInstrumentList = customValues.split("\\|"); - defaultLocalInstrumentList.addAll(Arrays.asList(customLocalInstrumentList)); - } - return defaultLocalInstrumentList.contains(localInstrument); - - } - - /** - * Check whether the amount is higher that the max instructed amount allowed by the bank. - * - * @param instructedAmount Instructed Amount to validate - * @return Whether the instructed amount is valid - */ - public static boolean validateMaxInstructedAmount(String instructedAmount) { - //This is a mandatory configuration in open-banking.xml. Hence can't be null. - String maxInstructedAmount = (String) parser.getConfiguration().get( - ConsentExtensionConstants.MAX_INSTRUCTED_AMOUNT); - return Double.parseDouble(instructedAmount) <= Double.parseDouble(maxInstructedAmount); - - } - - /** - * Method to construct Initiation response. - * - * @param response Response of the request - * @param createdConsent Consent response received from service layer - * @param consentManageData Request Details received - * @param type ConsentType - * @return JSONObject Initiation Response - */ - public static JSONObject getInitiationResponse(JSONObject response, DetailedConsentResource createdConsent, - ConsentManageData consentManageData, String type) { - JSONObject dataObject = (JSONObject) response.get(ConsentExtensionConstants.DATA); - dataObject.appendField(ConsentExtensionConstants.CONSENT_ID, createdConsent.getConsentID()); - dataObject.appendField("CreationDateTime", convertEpochDateTime(createdConsent.getCreatedTime())); - dataObject.appendField("StatusUpdateDateTime", convertEpochDateTime(createdConsent.getUpdatedTime())); - dataObject.appendField(ConsentExtensionConstants.STATUS, - ConsentExtensionUtils.getConsentStatus(createdConsent.getCurrentStatus())); - if (type.equals(ConsentExtensionConstants.PAYMENTS) && - ConsentExtensionUtils.isRequestAcceptedPastElapsedTime()) { - dataObject.appendField(ConsentExtensionConstants.CUT_OFF_DATE_TIME, ConsentExtensionUtils - .constructDateTime(0L, (String) parser.getConfiguration() - .get(OpenBankingConstants.DAILY_CUTOFF))); - } - - //add self link - JSONObject links = new JSONObject(); - links.put(ConsentExtensionConstants.SELF, - constructSelfLink(createdConsent.getConsentID(), consentManageData, type)); - response.appendField(ConsentExtensionConstants.LINKS, links); - - response.appendField(ConsentExtensionConstants.META, new JSONObject()); - - response.remove(ConsentExtensionConstants.DATA); - response.appendField(ConsentExtensionConstants.DATA, dataObject); - - return response; - } - - - /** - * Method to construct Retrieval Initiation response. - * - * @param receiptJSON Initiation of the request - * @param consent Consent response received from service layer - * @param consentManageData Request Details received - * @param type ConsentType - * @return JSONObject Initiation Response - */ - public static JSONObject getInitiationRetrievalResponse(JSONObject receiptJSON, ConsentResource consent, - ConsentManageData consentManageData, String type) { - - JSONObject dataObject = (JSONObject) receiptJSON.get(ConsentExtensionConstants.DATA); - dataObject.appendField(ConsentExtensionConstants.CONSENT_ID, consent.getConsentID()); - dataObject.appendField(ConsentExtensionConstants.STATUS, consent.getCurrentStatus()); - dataObject.appendField(ConsentExtensionConstants.STATUS_UPDATE_TIME, - ConsentExtensionUtils.convertToISO8601(consent.getUpdatedTime())); - dataObject.appendField(ConsentExtensionConstants.CREATION_TIME, - ConsentExtensionUtils.convertToISO8601(consent.getCreatedTime())); - - receiptJSON.remove(ConsentExtensionConstants.DATA); - receiptJSON.appendField(ConsentExtensionConstants.DATA, dataObject); - - JSONObject links = new JSONObject(); - links.put(ConsentExtensionConstants.SELF, - constructSelfLink(consent.getConsentID(), consentManageData, type)); - receiptJSON.appendField(ConsentExtensionConstants.LINKS, links); - - receiptJSON.appendField(ConsentExtensionConstants.META, new JSONObject()); - - return receiptJSON; - } - - private static String convertEpochDateTime(long epochTime) { - - int nanoOfSecond = 0; - ZoneOffset offset = ZoneOffset.UTC; - LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochTime, nanoOfSecond, offset); - return DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").format(ldt); - } - - /** - * Method to construct the self link. - * - * @param consentId Consent ID - * @param consentManageData Request Details recieved - * @param type ConsentType - * @return Constructed Self Link - */ - public static String constructSelfLink(String consentId, ConsentManageData consentManageData, String type) { - - String baseUrl = ""; - if (ConsentExtensionConstants.ACCOUNTS.equals(type)) { - baseUrl = (String) parser.getConfiguration().get( - ConsentExtensionConstants.ACCOUNTS_SELF_LINK); - } else if (ConsentExtensionConstants.PAYMENTS.equals(type)) { - baseUrl = (String) parser.getConfiguration().get( - ConsentExtensionConstants.PAYMENT_SELF_LINK); - } else if (ConsentExtensionConstants.FUNDSCONFIRMATIONS.equals(type)) { - baseUrl = (String) parser.getConfiguration().get( - ConsentExtensionConstants.COF_SELF_LINK); - } else if (ConsentExtensionConstants.VRP.equals(type)) { - baseUrl = (String) parser.getConfiguration().get( - ConsentExtensionConstants.VRP_SELF_LINK); - } - - String requestPath = consentManageData.getRequestPath(); - return baseUrl.replaceFirst("\\{version}", "3.1") + requestPath + "/" + consentId; - } - - /** - * Validate the consent ID. - * - * @param consentId Consent Id to validate - * @return Whether the consent ID is valid - */ - public static boolean isConsentIdValid(String consentId) { - return (consentId.length() == 36 && Pattern.matches(ConsentExtensionConstants.UUID_REGEX, consentId)); - } - - /** - * Validate Expiration Date Time. - * - * @param expDateVal Expiration Date Time - * @return Whether the expiration date time is valid - */ - public static boolean isConsentExpirationTimeValid(String expDateVal) { - if (expDateVal == null) { - return true; - } - try { - OffsetDateTime expDate = OffsetDateTime.parse(expDateVal); - OffsetDateTime currDate = OffsetDateTime.now(expDate.getOffset()); - - return expDate.compareTo(currDate) > 0; - } catch (DateTimeParseException e) { - return false; - } - } - /** - * Validate whether the date is a valid ISO 8601 format. - * @param dateValue Date value to validate - * @return Whether the date is a valid ISO 8601 format - */ - public static boolean isValid8601(String dateValue) { - try { - OffsetDateTime.parse(dateValue); - return true; - } catch (DateTimeParseException e) { - return false; - } - } - - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/DebtorAccountSchemeNameEnum.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/DebtorAccountSchemeNameEnum.java deleted file mode 100644 index daccab47..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/DebtorAccountSchemeNameEnum.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.util; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -/** - * Specifies the Schema Names of Debtor Account. - */ -public enum DebtorAccountSchemeNameEnum { - - BBAN("OB.BBAN"), - - IBAN("OB.IBAN"), - - PAN("OB.PAN"), - - PAYM("OB.Paym"), - - SORT_CODE_NUMBER("OB.SortCodeAccountNumber"); - - private String value; - - DebtorAccountSchemeNameEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static DebtorAccountSchemeNameEnum fromValue(String text) { - - List accountList = Arrays.asList(DebtorAccountSchemeNameEnum.values()); - Optional accountOpt = accountList - .stream() - .filter(i -> String.valueOf(i.value).equals(text)) - .findAny(); - - return accountOpt.isPresent() ? accountOpt.get() : null; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PaymentPayloadValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PaymentPayloadValidator.java deleted file mode 100644 index 03e4782a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PaymentPayloadValidator.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.util; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Validator class to validate payment initiation payload. - */ -public class PaymentPayloadValidator { - - private static final Log log = LogFactory.getLog(PaymentPayloadValidator.class); - - /** - * Method to validate payment initiation payload. - * - * @param requestPath Request Path of the request - * @param initiation Initiation Object of the request - * @return JSONObject Validation Response - */ - public static JSONObject validatePaymentInitiationPayload(String requestPath, JSONObject initiation) { - - JSONObject validationResponse = new JSONObject(); - - //Validate DebtorAccount - if (initiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) { - JSONObject debtorAccount = (JSONObject) initiation.get(ConsentExtensionConstants.DEBTOR_ACC); - JSONObject validationResult = ConsentManageUtil.validateDebtorAccount(debtorAccount); - if (!(boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)) { - return validationResult; - } - } - - //Validate CreditorAccount - if (initiation.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) { - JSONObject creditorAccount = (JSONObject) initiation.get(ConsentExtensionConstants.CREDITOR_ACC); - JSONObject validationResult = ConsentManageUtil.validateCreditorAccount(creditorAccount); - - if (!(boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)) { - return validationResult; - } - } else { - if (!requestPath.contains(ConsentExtensionConstants.PAYMENTS)) { - log.error(ErrorConstants.MSG_MISSING_CREDITOR_ACC); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_MISSING, - ErrorConstants.MSG_MISSING_CREDITOR_ACC, ErrorConstants.PATH_CREDIT_ACCOUNT); - } - } - - //Validate Local Instrument - if (initiation.containsKey(ConsentExtensionConstants.LOCAL_INSTRUMENT) && !ConsentManageUtil - .validateLocalInstrument(initiation.getAsString(ConsentExtensionConstants.LOCAL_INSTRUMENT))) { - log.error(ErrorConstants.INVALID_LOCAL_INSTRUMENT); - return ConsentManageUtil.getValidationResponse(ErrorConstants.UNSUPPORTED_LOCAL_INSTRUMENTS, - ErrorConstants.INVALID_LOCAL_INSTRUMENT, ErrorConstants.PATH_LOCAL_INSTRUMENT); - } - - - if (!requestPath.contains(ConsentExtensionConstants.PAYMENTS)) { - JSONObject instructedAmount = (JSONObject) initiation.get(ConsentExtensionConstants.INSTRUCTED_AMOUNT); - if (Double.parseDouble(instructedAmount.getAsString(ConsentExtensionConstants.AMOUNT)) < 1) { - log.error(ErrorConstants.INVALID_INSTRUCTED_AMOUNT); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_INSTRUCTED_AMOUNT, ErrorConstants.PATH_INSTRUCTED_AMOUNT); - } - - if (!ConsentManageUtil - .validateMaxInstructedAmount(instructedAmount.getAsString(ConsentExtensionConstants.AMOUNT))) { - log.error(ErrorConstants.MAX_INSTRUCTED_AMOUNT); - return ConsentManageUtil.getValidationResponse(ErrorConstants.FIELD_INVALID, - ErrorConstants.MAX_INSTRUCTED_AMOUNT, ErrorConstants.PATH_INSTRUCTED_AMOUNT); - } - - } - validationResponse.put(ConsentExtensionConstants.IS_VALID, true); - return validationResponse; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PeriodicTypesEnum.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PeriodicTypesEnum.java deleted file mode 100644 index 5ec0d221..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PeriodicTypesEnum.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.util; - -import java.time.LocalDate; - -/** - * This enum represents the different types of periods that can be used in the application. - * Each enum value is associated with a string representation and a method to calculate the divisor based - * on the period type. - * The divisor is used to convert other time units to this period type. - */ -public enum PeriodicTypesEnum { - - DAY("Day"), - - WEEK("Week"), - - FORTNIGHT("Fortnight"), - - MONTH("Month"), - - HALF_YEAR("Half-Year"), - - YEAR("Year"); - - private String value; - - PeriodicTypesEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - /** - * Returns the divisor based on the period type. - * - * @return the divisor based on the period type - */ - public int getDivisor() { - switch (this) { - case DAY: - return 1; - case WEEK: - return 7; - case FORTNIGHT: - return 14; - case MONTH: - return LocalDate.now().lengthOfMonth(); - case HALF_YEAR: - return LocalDate.now().isLeapYear() ? 181 : 180; - case YEAR: - return LocalDate.now().isLeapYear() ? 366 : 365; - default: - throw new IllegalArgumentException("Invalid PeriodType"); - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PeriodicalConsentJobActivator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PeriodicalConsentJobActivator.java deleted file mode 100644 index 2852b1ff..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/PeriodicalConsentJobActivator.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package com.wso2.openbanking.accelerator.consent.extensions.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.consent.extensions.util.jobs.ExpiredConsentStatusUpdateJob; -import com.wso2.openbanking.accelerator.consent.extensions.util.jobs.RetentionDatabaseSyncJob; -import com.wso2.openbanking.accelerator.consent.extensions.util.scheduler.PeriodicalConsentJobScheduler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.CronScheduleBuilder; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.Trigger; - -import static org.quartz.JobBuilder.newJob; -import static org.quartz.TriggerBuilder.newTrigger; - -/** - * Scheduled Task definition and trigger to perform expired consent status updateJob based on the cron string. - */ -public class PeriodicalConsentJobActivator { - - private static Log log = LogFactory.getLog(PeriodicalConsentJobActivator.class); - - /** - * activate the scheduler task. - */ - public void activate() { - - if (OpenBankingConfigParser.getInstance().isConsentExpirationPeriodicalJobEnabled()) { - JobDetail job = newJob(ExpiredConsentStatusUpdateJob.class) - .withIdentity("ConsentStatusUpdateJob", "group1") - .build(); - - Trigger trigger = newTrigger() - .withIdentity("periodicalTrigger", "group1") - .withSchedule(CronScheduleBuilder.cronSchedule( - OpenBankingConfigParser.getInstance().getConsentExpiryCronExpression())) - .build(); - - try { - Scheduler scheduler = PeriodicalConsentJobScheduler.getInstance().getScheduler(); - // this check is to remove already stored jobs in clustered mode. - if (scheduler.checkExists(job.getKey())) { - scheduler.deleteJob(job.getKey()); - } - - scheduler.scheduleJob(job, trigger); - if (log.isDebugEnabled()) { - log.debug("Periodical Consent Status Updater Started with cron : " - + OpenBankingConfigParser.getInstance().getConsentExpiryCronExpression()); - } - } catch (SchedulerException e) { - log.error("Error while creating and starting Periodical Consent Status Update Scheduled Task", e); - } - } - - if (OpenBankingConfigParser.getInstance().isRetentionDataDBSyncEnabled() && - OpenBankingConfigParser.getInstance().isConsentDataRetentionEnabled()) { - JobDetail job = newJob(RetentionDatabaseSyncJob.class) - .withIdentity("RetentionDatabaseSyncJob", "group1") - .build(); - - Trigger trigger = newTrigger() - .withIdentity("RetentionDatabaseSyncPeriodicalTrigger", "group1") - .withSchedule(CronScheduleBuilder.cronSchedule( - OpenBankingConfigParser.getInstance().getRetentionDataDBSyncCronExpression())) - .build(); - - try { - Scheduler scheduler = PeriodicalConsentJobScheduler.getInstance().getScheduler(); - // this check is to remove already stored jobs in clustered mode. - if (scheduler.checkExists(job.getKey())) { - scheduler.deleteJob(job.getKey()); - } - - scheduler.scheduleJob(job, trigger); - if (log.isDebugEnabled()) { - log.debug("Retention database sync job started with cron : " - + OpenBankingConfigParser.getInstance().getConsentExpiryCronExpression()); - } - } catch (SchedulerException e) { - log.error("Error while creating and starting retention database syncing scheduled Task", e); - } - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/jobs/ExpiredConsentStatusUpdateJob.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/jobs/ExpiredConsentStatusUpdateJob.java deleted file mode 100644 index fde76d8a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/jobs/ExpiredConsentStatusUpdateJob.java +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.util.jobs; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.DisallowConcurrentExecution; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.Map; - -/** - * Scheduled Task to read and update expired consents in the DB - * 1) Read the consents which has a expiry time attribute from the DB. - * 2) Check if expired, and collect expired consents - * 3) Update the expired statues in DB - * 4) Notify state change to relevant handler. - */ -@DisallowConcurrentExecution -public class ExpiredConsentStatusUpdateJob implements Job { - - private static Log log = LogFactory.getLog(ExpiredConsentStatusUpdateJob.class); - private static final String expiredConsentStatus = - OpenBankingConfigParser.getInstance().getStatusWordingForExpiredConsents(); - private static final String expirationEligibleConsentStatuses = - OpenBankingConfigParser.getInstance().getEligibleStatusesForConsentExpiry(); - - /** - * Method used to enforce periodic statues update of consents. - * - * @param jobExecutionContext Job Execution Context - * @throws JobExecutionException if an error occurs while executing the job - */ - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - try { - updateExpiredStatues(); - } catch (ConsentManagementException e) { - log.error("Error occurred while updating status for expired consents", e); - } - - } - - /** - * Method to update statues of consents. - * @throws ConsentManagementException if an error occurs while updating the consent status - */ - public static void updateExpiredStatues() throws ConsentManagementException { - - log.debug("Expired Consent Status Update Scheduled Task is executing."); - // get consents which has a expiry time attribute - ArrayList consentsEligibleForExpiration = - ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .getConsentsEligibleForExpiration(expirationEligibleConsentStatuses); - // filter out expired consents and change the status of expired consents - for (DetailedConsentResource consentResource : consentsEligibleForExpiration) { - if (isExpired(consentResource)) { - String updatedConsentId = updateConsentExpiredStatus(consentResource); - if (log.isDebugEnabled()) { - log.debug("Expired status updated for consent : " + updatedConsentId); - } - } - } - log.debug("Expired Consent Status Update Scheduled Task is finished."); - } - - /** - * Check if the consents is expired based on the consent attribute value. - * - * @param detailedConsentResource - * @return - */ - private static boolean isExpired(DetailedConsentResource detailedConsentResource) { - - Map consentAttributes = detailedConsentResource.getConsentAttributes(); - if (consentAttributes.containsKey(ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE)) { - // Read the UTC expiry timestamp in long - long expiryTimestamp = Long.parseLong( - consentAttributes.get(ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE)); - // Compare with current UTC timestamp in long - Instant instant = Instant.now(); - long currentTimeStampSeconds = instant.getEpochSecond(); - if (currentTimeStampSeconds >= expiryTimestamp) { - log.info("Consent " + detailedConsentResource.getConsentID() + " is identified as expired based on the " - + "given consent expiration time : " + expiryTimestamp); - return true; - } - } - return false; - } - - /** - * Update the expired consents in DB. - * - * @param detailedConsentResource - * @return - */ - private static String updateConsentExpiredStatus(DetailedConsentResource detailedConsentResource) { - - try { - ConsentExtensionsDataHolder.getInstance().getConsentCoreService() - .updateConsentStatus(detailedConsentResource.getConsentID(), expiredConsentStatus); - - //since the consent status is changed during the consent expiration, the previous status will be saved - //in the consent history to properly back-track the previous status held in the consent - storeConsentStateChangeInConsentHistory(detailedConsentResource); - - } catch (ConsentManagementException e) { - log.error("Error occurred while updating status for consentId : " + - detailedConsentResource.getConsentID(), e); - } - return detailedConsentResource.getConsentID(); - } - - private static void storeConsentStateChangeInConsentHistory(DetailedConsentResource detailedConsentResource) - throws ConsentManagementException { - - if (OpenBankingConfigParser.getInstance().isConsentAmendmentHistoryEnabled()) { - - ConsentCoreService consentCoreService = ConsentExtensionsDataHolder.getInstance().getConsentCoreService(); - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setTimestamp(System.currentTimeMillis() / 1000); - consentHistoryResource.setReason(ConsentCoreServiceConstants.AMENDMENT_REASON_CONSENT_EXPIRATION); - consentHistoryResource.setDetailedConsentResource(detailedConsentResource); - - consentCoreService.storeConsentAmendmentHistory(detailedConsentResource.getConsentID(), - consentHistoryResource, null); - } - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/jobs/RetentionDatabaseSyncJob.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/jobs/RetentionDatabaseSyncJob.java deleted file mode 100644 index 8ea9068e..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/jobs/RetentionDatabaseSyncJob.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package com.wso2.openbanking.accelerator.consent.extensions.util.jobs; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.DisallowConcurrentExecution; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -/** - * Scheduled Task to read and sync the temporary retention data in consent tables to retention database. - * 1) Read the consents in temporary retention tables in consennt DB. - * 2) Insert each consent data to retention database. - * 3) Delete the consent data from temporary retention tables. - */ -@DisallowConcurrentExecution -public class RetentionDatabaseSyncJob implements Job { - - private static Log log = LogFactory.getLog(RetentionDatabaseSyncJob.class); - - /** - * Method used to enforce sync the temporary retention data. - * - * @param jobExecutionContext Job Execution Context - * @throws JobExecutionException if an error occurs while executing the job - */ - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - - try { - syncRetentionDatabase(); - } catch (ConsentManagementException e) { - log.error("Error occurred while retention database syncing", e); - } - } - - /** - * Method to sync the temporary retention data. - * @throws ConsentManagementException if an error occurs while syncing the retention database - */ - public static void syncRetentionDatabase() throws ConsentManagementException { - - log.debug("Retention database syncing scheduled task is executing."); - ConsentExtensionsDataHolder.getInstance().getConsentCoreService().syncRetentionDatabaseWithPurgedConsent(); - log.debug("Retention database syncing scheduled task is finished."); - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/scheduler/PeriodicalConsentJobScheduler.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/scheduler/PeriodicalConsentJobScheduler.java deleted file mode 100644 index 3131c3d9..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/util/scheduler/PeriodicalConsentJobScheduler.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package com.wso2.openbanking.accelerator.consent.extensions.util.scheduler; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.impl.StdSchedulerFactory; -import org.wso2.carbon.utils.CarbonUtils; - -import java.io.File; -import java.nio.file.Paths; - -/** - * Periodic consent job scheduler class. - * This class initialize the scheduler and schedule configured jobs and triggers. - */ -public class PeriodicalConsentJobScheduler { - - private static volatile PeriodicalConsentJobScheduler instance; - private static final String QUARTZ_PROPERTY_FILE = "quartz.properties"; - - private static volatile Scheduler scheduler; - private static Log log = LogFactory.getLog(PeriodicalConsentJobScheduler.class); - - private PeriodicalConsentJobScheduler() { - - initScheduler(); - } - - /** - * Get an instance of the PeriodicalConsentJobScheduler. It implements a double checked locking initialization. - * - * @return PeriodicalConsentJobScheduler instance - */ - public static synchronized PeriodicalConsentJobScheduler getInstance() { - - if (instance == null) { - synchronized (PeriodicalConsentJobScheduler.class) { - if (instance == null) { - instance = new PeriodicalConsentJobScheduler(); - } - } - } - return instance; - } - - /** - * Initialize the scheduler. - */ - private void initScheduler() { - - if (instance != null) { - return; - } - synchronized (PeriodicalConsentJobScheduler.class) { - try { - String quartzConfigFile = Paths.get(CarbonUtils.getCarbonConfigDirPath()).toString() + "/" - + QUARTZ_PROPERTY_FILE; - boolean exists = new File(quartzConfigFile).exists(); - if (exists) { - StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory(); - stdSchedulerFactory.initialize(quartzConfigFile); - scheduler = stdSchedulerFactory.getScheduler(); - } else { - scheduler = StdSchedulerFactory.getDefaultScheduler(); - } - scheduler.start(); - } catch (SchedulerException e) { - log.error("Exception while initializing the scheduler", e); - } - } - } - - /** - * Returns the scheduler. - * - * @return Scheduler scheduler. - */ - public Scheduler getScheduler() { - - return scheduler; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/builder/ConsentValidateBuilder.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/builder/ConsentValidateBuilder.java deleted file mode 100644 index de6b065f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/builder/ConsentValidateBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.builder; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Builder class for consent validator. - */ -public class ConsentValidateBuilder { - - private static final Log log = LogFactory.getLog(ConsentValidateBuilder.class); - private ConsentValidator consentValidator = null; - private String requestSignatureAlias = null; - private static String validatorConfigPath = "Consent.Validation.Validator"; - private static String signatureAliasConfigPath = "Consent.Validation.RequestSignatureAlias"; - - - public void build() { - - OpenBankingConfigurationService configurationService = - ConsentExtensionsDataHolder.getInstance().getOpenBankingConfigurationService(); - String handlerConfig = (String) configurationService.getConfigurations().get(validatorConfigPath); - consentValidator = (ConsentValidator) OpenBankingUtils.getClassInstanceFromFQN(handlerConfig); - requestSignatureAlias = (String) configurationService.getConfigurations().get(signatureAliasConfigPath); - log.debug("Admin handler loaded successfully"); - } - - public ConsentValidator getConsentValidator() { - return consentValidator; - } - - public String getRequestSignatureAlias() { - return requestSignatureAlias; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/DefaultConsentValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/DefaultConsentValidator.java deleted file mode 100644 index 0692ec13..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/DefaultConsentValidator.java +++ /dev/null @@ -1,508 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.impl; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidateData; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidationResult; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidator; -import com.wso2.openbanking.accelerator.consent.extensions.validate.util.ConsentValidatorUtil; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; - -import java.time.OffsetDateTime; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; - -/** - * Consent validator default implementation. - */ -public class DefaultConsentValidator implements ConsentValidator { - - private static final Log log = LogFactory.getLog(DefaultConsentValidator.class); - private static final String ACCOUNTS_REGEX = "/accounts/[^/?]*"; - private static final String TRANSACTIONS_REGEX = "/accounts/[^/?]*/transactions"; - private static final String BALANCES_REGEX = "/accounts/[^/?]*/balances"; - private static final String PERMISSION_MISMATCH_ERROR = "Permission mismatch. Consent does not contain necessary " + - "permissions"; - private static final String INVALID_URI_ERROR = "Path requested is invalid"; - private static final String CONSENT_EXPIRED_ERROR = "Provided consent is expired"; - private static final String CONSENT_STATE_ERROR = "Provided consent not in authorised state"; - private static final String AUTHORISED_STATUS = "authorised"; - - @Override - public void validate(ConsentValidateData consentValidateData, ConsentValidationResult consentValidationResult) - throws ConsentException { - - String uri = consentValidateData.getRequestPath(); - JSONObject receiptJSON; - try { - receiptJSON = (JSONObject) (new JSONParser(JSONParser.MODE_PERMISSIVE)). - parse(consentValidateData.getComprehensiveConsent().getReceipt()); - - } catch (ParseException e) { - log.error(e.getMessage()); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Exception occurred while validating" + - " permissions"); - } - - //User Validation - String userIdFromToken = consentValidateData.getUserId(); - boolean userIdMatching = false; - ArrayList authResources = consentValidateData.getComprehensiveConsent() - .getAuthorizationResources(); - for (AuthorizationResource resource : authResources) { - if (userIdFromToken.contains(resource.getUserID())) { - userIdMatching = true; - break; - } - } - - if (!userIdMatching) { - log.error(ErrorConstants.INVALID_USER_ID); - consentValidationResult.setErrorMessage(ErrorConstants.INVALID_USER_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - String clientIdFromToken = consentValidateData.getClientId(); - String clientIdFromConsent = consentValidateData.getComprehensiveConsent().getClientID(); - if (clientIdFromToken == null || clientIdFromConsent == null || - !clientIdFromToken.equals(clientIdFromConsent)) { - log.error(ErrorConstants.MSG_INVALID_CLIENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CLIENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_FORBIDDEN); - return; - } - - String requestType = consentValidateData.getComprehensiveConsent().getConsentType(); - - switch (requestType) { - case ConsentExtensionConstants.ACCOUNTS: - validateAccountSubmission(consentValidateData, receiptJSON, consentValidationResult); - break; - case ConsentExtensionConstants.PAYMENTS: - validatePaymentSubmission(consentValidateData, receiptJSON, consentValidationResult); - break; - case ConsentExtensionConstants.FUNDSCONFIRMATIONS: - validateFundsConfirmationSubmission(consentValidateData, receiptJSON, consentValidationResult); - break; - case ConsentExtensionConstants.VRP: - validateVRPSubmission(consentValidateData, receiptJSON, consentValidationResult); - break; - default: - log.error(ErrorConstants.INVALID_CONSENT_TYPE); - consentValidationResult.setErrorMessage(ErrorConstants.INVALID_CONSENT_TYPE); - consentValidationResult.setErrorCode(ErrorConstants.UNEXPECTED_ERROR); - consentValidationResult.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - return; - } - } - - /** - * Validate Account Retrieval Request. - * - * @param consentValidateData Object with request data - * @param consentValidationResult Validation result object to return - */ - private void validateAccountSubmission(ConsentValidateData consentValidateData, JSONObject receiptJSON, - ConsentValidationResult consentValidationResult) { - - JSONArray permissions = (JSONArray) ((JSONObject) receiptJSON.get("Data")).get("Permissions"); - - // Perform URI Validation. - String uri = consentValidateData.getRequestPath(); - if (!(uri.matches(ACCOUNTS_REGEX) || uri.matches(TRANSACTIONS_REGEX) || uri.matches(BALANCES_REGEX))) { - consentValidationResult.setErrorMessage(INVALID_URI_ERROR); - consentValidationResult.setErrorCode("00013"); - consentValidationResult.setHttpCode(401); - return; - } - if ((uri.matches(ACCOUNTS_REGEX) && !permissions.contains("ReadAccountsDetail")) || - (uri.matches(TRANSACTIONS_REGEX) && !permissions.contains("ReadTransactionsDetail")) || - (uri.matches(BALANCES_REGEX)) && !permissions.contains("ReadBalances")) { - consentValidationResult.setErrorMessage(PERMISSION_MISMATCH_ERROR); - consentValidationResult.setErrorCode("00010"); - consentValidationResult.setHttpCode(401); - return; - } - - //Consent Status Validation - if (!ConsentExtensionConstants.AUTHORIZED_STATUS - .equalsIgnoreCase(consentValidateData.getComprehensiveConsent().getCurrentStatus())) { - consentValidationResult.setErrorMessage(ErrorConstants.ACCOUNT_CONSENT_STATE_INVALID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_INVALID_CONSENT_STATUS); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - if (isConsentExpired(((JSONObject) receiptJSON.get("Data")).getAsString("ExpirationDateTime"))) { - consentValidationResult.setErrorMessage(CONSENT_EXPIRED_ERROR); - consentValidationResult.setErrorCode("00011"); - consentValidationResult.setHttpCode(401); - return; - } - consentValidationResult.setValid(true); - } - - - /** - * Validate Payment Retrieval Request. - * - * @param consentValidateData Object with request data - * @param consentValidationResult Validation result object to return - */ - private void validatePaymentSubmission(ConsentValidateData consentValidateData, JSONObject initiationJson, - ConsentValidationResult consentValidationResult) { - - DetailedConsentResource detailedConsentResource = consentValidateData.getComprehensiveConsent(); - - try { - // Rejecting consent if cut off time is elapsed and the policy is REJECT - // Updating the consent status to "Reject" if the above condition is true - if (ConsentExtensionUtils.shouldSubmissionRequestBeRejected(ConsentExtensionUtils - .convertToISO8601(detailedConsentResource.getCreatedTime()))) { - boolean success = ConsentExtensionUtils.getConsentService().revokeConsent( - detailedConsentResource.getConsentID(), ConsentExtensionConstants.REJECTED_STATUS); - if (!success) { - log.error(ErrorConstants.TOKEN_REVOKE_ERROR); - consentValidationResult.setErrorMessage(ErrorConstants.TOKEN_REVOKE_ERROR); - consentValidationResult.setErrorCode(ErrorConstants.UNEXPECTED_ERROR); - consentValidationResult.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - return; - } - log.error(ErrorConstants.CUT_OFF_DATE_ELAPSED); - consentValidationResult.setErrorMessage(ErrorConstants.CUT_OFF_DATE_ELAPSED); - consentValidationResult.setErrorCode(ErrorConstants.RULES_CUTOFF); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - // Check if requested consent ID matches to initiation consent ID. - if (consentValidateData.getConsentId() == null || detailedConsentResource.getConsentID() == null || - !consentValidateData.getConsentId().equals(detailedConsentResource.getConsentID())) { - log.error(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - if (consentValidateData.getRequestPath().contains(ConsentExtensionConstants.PAYMENT_COF_PATH)) { - PaymentFundsConfirmationPayloadValidator paymentFundsConfirmationValidator = - new PaymentFundsConfirmationPayloadValidator(); - paymentFundsConfirmationValidator.validatePaymentFundsConfirmationRequest(consentValidateData, - consentValidationResult, detailedConsentResource); - return; - } else { - if (!ConsentExtensionConstants.AUTHORIZED_STATUS - .equalsIgnoreCase(consentValidateData.getComprehensiveConsent().getCurrentStatus())) { - log.error(ErrorConstants.PAYMENT_CONSENT_STATE_INVALID); - consentValidationResult.setErrorMessage(ErrorConstants.PAYMENT_CONSENT_STATE_INVALID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_INVALID_CONSENT_STATUS); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - JSONObject submissionJson = consentValidateData.getPayload(); - JSONObject submissionData = new JSONObject(); - JSONObject submissionInitiation = new JSONObject(); - - JSONObject requestInitiation = (JSONObject) ((JSONObject) initiationJson - .get(ConsentExtensionConstants.DATA)).get(ConsentExtensionConstants.INITIATION); - - if (submissionJson.containsKey(ConsentExtensionConstants.DATA) && - submissionJson.get(ConsentExtensionConstants.DATA) instanceof JSONObject) { - submissionData = (JSONObject) submissionJson.get(ConsentExtensionConstants.DATA); - } else { - log.error(ErrorConstants.DATA_NOT_FOUND); - consentValidationResult.setErrorMessage(ErrorConstants.DATA_NOT_FOUND); - consentValidationResult.setErrorCode(ErrorConstants.FIELD_MISSING); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - if (submissionData.containsKey(ConsentExtensionConstants.INITIATION) && - submissionData.get(ConsentExtensionConstants.INITIATION) instanceof JSONObject) { - submissionInitiation = (JSONObject) submissionData.get(ConsentExtensionConstants.INITIATION); - } else { - log.error(ErrorConstants.INITIATION_NOT_FOUND); - consentValidationResult.setErrorMessage(ErrorConstants.INITIATION_NOT_FOUND); - consentValidationResult.setErrorCode(ErrorConstants.FIELD_MISSING); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - // Check if requested consent ID in the body to initiation consent ID. - if (!submissionData.containsKey(ConsentExtensionConstants.CONSENT_ID_VALIDATION) || - submissionData.get(ConsentExtensionConstants.CONSENT_ID_VALIDATION) == null || - !submissionData.get(ConsentExtensionConstants.CONSENT_ID_VALIDATION) - .equals(detailedConsentResource.getConsentID())) { - log.error(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - PaymentSubmissionPayloadValidator validator = new PaymentSubmissionPayloadValidator(); - JSONObject initiationValidationResult = validator - .validateInitiation(submissionInitiation, requestInitiation); - - if (!(boolean) initiationValidationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD)) { - log.error(initiationValidationResult.getAsString(ConsentExtensionConstants.ERROR_MESSAGE)); - consentValidationResult.setErrorMessage(initiationValidationResult - .getAsString(ConsentExtensionConstants.ERROR_MESSAGE)); - consentValidationResult.setErrorCode(initiationValidationResult - .getAsString(ConsentExtensionConstants.ERROR_CODE)); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - } - - } catch (ConsentManagementException e) { - log.error(e.getMessage()); - consentValidationResult.setErrorMessage(e.getMessage()); - consentValidationResult.setErrorCode(ErrorConstants.UNEXPECTED_ERROR); - consentValidationResult.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - return; - } - consentValidationResult.setValid(true); - } - - private boolean isConsentExpired(String expDateVal) throws ConsentException { - - if (expDateVal != null && !expDateVal.isEmpty()) { - try { - OffsetDateTime expDate = OffsetDateTime.parse(expDateVal); - return OffsetDateTime.now().isAfter(expDate); - } catch (DateTimeParseException e) { - log.error("Error occurred while parsing the expiration date : " + expDateVal); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "Error occurred while parsing the expiration date"); - } - } else { - return false; - } - - } - - /** - * Validate Funds Confirmation Retrieval Request. - * - * @param consentValidateData Object with request data - * @param consentValidationResult Validation result object to return - */ - private static void validateFundsConfirmationSubmission(ConsentValidateData consentValidateData, - JSONObject receiptJSON, - ConsentValidationResult consentValidationResult) { - - // Perform URI Validation. - String uri = consentValidateData.getRequestPath(); - if (uri == null || !ConsentValidatorUtil.isCOFURIValid(uri)) { - consentValidationResult.setErrorMessage(ErrorConstants.INVALID_URI_ERROR); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_INVALID_FORMAT); - consentValidationResult.setHttpCode(401); - return; - } - - //Consent Status Validation - if (!ConsentExtensionConstants.AUTHORIZED_STATUS - .equalsIgnoreCase(consentValidateData.getComprehensiveConsent().getCurrentStatus())) { - consentValidationResult.setErrorMessage(ErrorConstants.COF_CONSENT_STATE_INVALID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_INVALID_CONSENT_STATUS); - consentValidationResult.setHttpCode(400); - return; - } - - //Validate whether the consent is expired - if (ConsentValidatorUtil - .isConsentExpired(((JSONObject) receiptJSON.get(ConsentExtensionConstants.DATA)) - .getAsString(ConsentExtensionConstants.EXPIRATION_DATE))) { - consentValidationResult.setErrorMessage(ErrorConstants.CONSENT_EXPIRED_ERROR); - consentValidationResult.setErrorCode(ErrorConstants.FIELD_INVALID); - consentValidationResult.setHttpCode(400); - return; - } - - // Check if requested consent ID in the token to initiation consent ID. - if (consentValidateData.getConsentId() == null || - consentValidateData.getComprehensiveConsent().getConsentID() == null || - !consentValidateData.getConsentId() - .equals(consentValidateData.getComprehensiveConsent().getConsentID())) { - log.error(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - JSONObject data = (JSONObject) consentValidateData.getPayload().get(ConsentExtensionConstants.DATA); - // Check if requested consent ID in the body to initiation consent ID. - if (!data.containsKey(ConsentExtensionConstants.CONSENT_ID_VALIDATION) || - data.get(ConsentExtensionConstants.CONSENT_ID_VALIDATION) == null || - !data.get(ConsentExtensionConstants.CONSENT_ID_VALIDATION) - .equals(consentValidateData.getComprehensiveConsent().getConsentID())) { - log.error(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - consentValidationResult.setValid(true); - - } - - /** - * Validate VRP Submission Request. - * - * @param consentValidateData Object with request data - * @param consentValidationResult Validation result object to return - */ - private void validateVRPSubmission(ConsentValidateData consentValidateData, JSONObject initiationJson, - ConsentValidationResult consentValidationResult) { - - DetailedConsentResource detailedConsentResource = consentValidateData.getComprehensiveConsent(); - - if (!ConsentExtensionConstants.AUTHORIZED_STATUS - .equals(consentValidateData.getComprehensiveConsent().getCurrentStatus())) { - log.error(ErrorConstants.VRP_CONSENT_STATUS_INVALID); - consentValidationResult.setErrorMessage(ErrorConstants.VRP_CONSENT_STATUS_INVALID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_INVALID_CONSENT_STATUS); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - // Check if requested consent ID matches to initiation consent ID. - if (consentValidateData.getConsentId() == null || detailedConsentResource.getConsentID() == null || - !consentValidateData.getConsentId().equals(detailedConsentResource.getConsentID())) { - log.error(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - JSONObject submissionJson = consentValidateData.getPayload(); - - JSONObject dataValidationResults = VRPSubmissionPayloadValidator.validateSubmissionData(submissionJson); - if (!Boolean.parseBoolean(dataValidationResults. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(dataValidationResults, - consentValidationResult); - return; - } - - JSONObject submissionData = (JSONObject) submissionJson.get(ConsentExtensionConstants.DATA); - - JSONObject initiationParameterValidationResults = VRPSubmissionPayloadValidator. - validateInitiationParameter(submissionData); - if (!Boolean.parseBoolean(initiationParameterValidationResults. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(initiationParameterValidationResults, - consentValidationResult); - return; - } - - JSONObject instructionParameterValidationResults = VRPSubmissionPayloadValidator. - validateInstructionParameter(submissionData); - if (!Boolean.parseBoolean(instructionParameterValidationResults. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(instructionParameterValidationResults, - consentValidationResult); - return; - } - - // Check if requested consent ID in the body to initiation consent ID. - if (!submissionData.containsKey(ConsentExtensionConstants.CONSENT_ID) || - !(submissionData.get(ConsentExtensionConstants.CONSENT_ID) instanceof String) || - !submissionData.get(ConsentExtensionConstants.CONSENT_ID) - .equals(detailedConsentResource.getConsentID())) { - log.error(ErrorConstants.INVALID_REQUEST_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.INVALID_REQUEST_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - JSONObject dataObject = (JSONObject) initiationJson.get(ConsentExtensionConstants.DATA); - JSONObject requestInitiation = (JSONObject) dataObject.get(ConsentExtensionConstants.INITIATION); - JSONObject submissionInitiation = (JSONObject) submissionData.get(ConsentExtensionConstants.INITIATION); - JSONObject submissionInstruction = (JSONObject) submissionData.get(ConsentExtensionConstants.INSTRUCTION); - - JSONObject initiationValidationResult = VRPSubmissionPayloadValidator - .validateInitiation(submissionInitiation, requestInitiation); - - if (!Boolean.parseBoolean(initiationValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(initiationValidationResult, - consentValidationResult); - return; - } - - // Here the requestInitiation is passed as a parameter inorder to compare the creditor account in - // the initiation payload present under the initiation parameter, with the submission payload present under the - // instruction parameter. - JSONObject instructionValidationResult = VRPSubmissionPayloadValidator. - validateInstruction(submissionInstruction, requestInitiation); - - if (!Boolean.parseBoolean(instructionValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(instructionValidationResult, - consentValidationResult); - return; - } - - JSONObject riskParameterValidationResults = VRPSubmissionPayloadValidator.validateRiskParameter(submissionJson); - if (!Boolean.parseBoolean(riskParameterValidationResults. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(riskParameterValidationResults, - consentValidationResult); - return; - } - - JSONObject initiationRisk = (JSONObject) initiationJson.get(ConsentExtensionConstants.RISK); - JSONObject submissionRisk = (JSONObject) submissionJson.get(ConsentExtensionConstants.RISK); - JSONObject riskValidationResult = VRPSubmissionPayloadValidator.validateRisk(submissionRisk, - initiationRisk); - - if (!Boolean.parseBoolean(riskValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - ConsentValidatorUtil.setErrorMessageForConsentValidationResult(riskValidationResult, - consentValidationResult); - return; - } - consentValidationResult.setValid(true); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/PaymentFundsConfirmationPayloadValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/PaymentFundsConfirmationPayloadValidator.java deleted file mode 100644 index 968a7181..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/PaymentFundsConfirmationPayloadValidator.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.impl; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidateData; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidationResult; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; - -/** - * Class for validating Payments funds confirmation requests. - */ -public class PaymentFundsConfirmationPayloadValidator { - - private static Log log = LogFactory.getLog(PaymentFundsConfirmationPayloadValidator.class); - - /** - * MEthod to validate Payment Funds Confirmation requests. - * - * @param consentValidateData Object with request data - * @param consentValidationResult Validation result object to return - * @param detailedConsentResource detailed consent resource retrieved from database - */ - public void validatePaymentFundsConfirmationRequest(ConsentValidateData consentValidateData, - ConsentValidationResult consentValidationResult, - DetailedConsentResource detailedConsentResource) { - - //Consent Status Validation - if (!ConsentExtensionConstants.AUTHORIZED_STATUS - .equalsIgnoreCase(consentValidateData.getComprehensiveConsent().getCurrentStatus())) { - consentValidationResult.setErrorMessage(ErrorConstants.PAYMENT_CONSENT_STATE_INVALID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_INVALID_CONSENT_STATUS); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - //Validate Consent Id From path - //ResourcePath comes in format /pisp/domestic-scheduled-consents/{consentId}/funds-confirmation - String[] requestPathArray = ((String) consentValidateData.getResourceParams().get("ResourcePath")) - .trim().split("/"); - - if (requestPathArray.length != 5 || StringUtils.isEmpty(requestPathArray[3])) { - log.error(ErrorConstants.CONSENT_ID_NOT_FOUND); - consentValidationResult.setErrorMessage(ErrorConstants.CONSENT_ID_NOT_FOUND); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - //Validate whether consentId from path matches - String consentIdFromPath = requestPathArray[3]; - if (consentIdFromPath == null || !consentIdFromPath.equals(detailedConsentResource.getConsentID())) { - log.error(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorMessage(ErrorConstants.MSG_INVALID_CONSENT_ID); - consentValidationResult.setErrorCode(ErrorConstants.RESOURCE_CONSENT_MISMATCH); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - return; - } - - consentValidationResult.setValid(true); - } -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/PaymentSubmissionPayloadValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/PaymentSubmissionPayloadValidator.java deleted file mode 100644 index 421a13b3..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/PaymentSubmissionPayloadValidator.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.impl; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.validate.util.ConsentValidatorUtil; -import com.wso2.openbanking.accelerator.consent.extensions.validate.util.PaymentSubmissionValidationUtil; -import net.minidev.json.JSONObject; - -/** - * Class for validating Payment submission requests. - */ -public class PaymentSubmissionPayloadValidator { - - /** - * Method to validate payment submission initiation payload. - * - * @param submission Submission Request - * @param initiation Initiation Request - * @return JSONObject Validation Response - */ - public JSONObject validateInitiation(JSONObject submission, JSONObject initiation) { - - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - validationResult.put(ConsentExtensionConstants.ERROR_CODE, ""); - validationResult.put(ConsentExtensionConstants.ERROR_MESSAGE, ""); - - if (submission != null && initiation != null) { - - //Validate Instruction Identification - JSONObject instructionIdentificationResult = PaymentSubmissionValidationUtil - .validateInstructionIdentification(submission, initiation); - if (!((boolean) instructionIdentificationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return instructionIdentificationResult; - } - - //Validate End to End Identification - JSONObject endToEndIdentificationResult = PaymentSubmissionValidationUtil - .validateEndToEndIdentification(submission, initiation); - if (!((boolean) endToEndIdentificationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return endToEndIdentificationResult; - } - - //Validate Instructed Amount - JSONObject instructedAmountResult = PaymentSubmissionValidationUtil - .validateInstructedAmount(submission, initiation); - if (!((boolean) instructedAmountResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return instructedAmountResult; - } - - - //Validate Creditor Account - if (submission.containsKey(ConsentExtensionConstants.CREDITOR_ACC) && - initiation.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) { - - JSONObject subCreditorAccount = (JSONObject) submission.get(ConsentExtensionConstants.CREDITOR_ACC); - JSONObject initCreditorAccount = (JSONObject) initiation.get(ConsentExtensionConstants.CREDITOR_ACC); - - JSONObject creditorAccValidationResult = ConsentValidatorUtil.validateCreditorAcc(subCreditorAccount, - initCreditorAccount); - if (!(boolean) creditorAccValidationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD)) { - return creditorAccValidationResult; - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.CREDITOR_ACC_NOT_FOUND); - } - - //Validate Debtor Account - if ((!submission.containsKey(ConsentExtensionConstants.DEBTOR_ACC) && - initiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) || - (submission.containsKey(ConsentExtensionConstants.DEBTOR_ACC) && - !initiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.DEBTOR_ACC_MISMATCH); - } else if (submission.containsKey(ConsentExtensionConstants.DEBTOR_ACC) && - initiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) { - - JSONObject subDebtorAccount = (JSONObject) submission.get(ConsentExtensionConstants.DEBTOR_ACC); - JSONObject initDebtorAccount = (JSONObject) initiation.get(ConsentExtensionConstants.DEBTOR_ACC); - - JSONObject debtorAccValidationResult = ConsentValidatorUtil.validateDebtorAcc(subDebtorAccount, - initDebtorAccount); - if (!(boolean) debtorAccValidationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD)) { - return debtorAccValidationResult; - } - } - - //Validate Local Instrument - if (!ConsentValidatorUtil.compareOptionalParameter( - submission.getAsString(ConsentExtensionConstants.LOCAL_INSTRUMENT), - initiation.getAsString(ConsentExtensionConstants.LOCAL_INSTRUMENT))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.LOCAL_INSTRUMENT_MISMATCH); - } - } - - return validationResult; - - } -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/VRPSubmissionPayloadValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/VRPSubmissionPayloadValidator.java deleted file mode 100644 index d6431f1d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/impl/VRPSubmissionPayloadValidator.java +++ /dev/null @@ -1,516 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.validate.impl; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.validate.util.ConsentValidatorUtil; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Class for validating VRP submission request. - */ -public class VRPSubmissionPayloadValidator { - private static final Log log = LogFactory.getLog(VRPSubmissionPayloadValidator.class); - - /** - * Validates the initiation parameters between the initiation of submission request and the initiation parameters - * of consent initiation request. - * - * @param initiationOfSubmission The initiation parameters from the submission request. - * @param initiationParameterOfConsentInitiation The initiation parameters from the consent initiation request. - * @return A JSONObject indicating the validation result. It contains a boolean value under the key - * ConsentExtensionConstants.IS_VALID_PAYLOAD, indicating whether the payload is valid. If the - * validation fails, it returns a JSONObject containing error details with keys defined in ErrorConstants. - */ - public static JSONObject validateInitiation(JSONObject initiationOfSubmission, - JSONObject initiationParameterOfConsentInitiation) { - - if (initiationOfSubmission != null && initiationParameterOfConsentInitiation != null) { - - - - //Validate Creditor Account - if ((!initiationOfSubmission.containsKey(ConsentExtensionConstants.CREDITOR_ACC) && - initiationParameterOfConsentInitiation.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) || - (initiationOfSubmission.containsKey(ConsentExtensionConstants.CREDITOR_ACC) && - !initiationParameterOfConsentInitiation. - containsKey(ConsentExtensionConstants.CREDITOR_ACC))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.CREDITOR_ACC_NOT_FOUND); - } else if (initiationOfSubmission.containsKey(ConsentExtensionConstants.CREDITOR_ACC) && - initiationParameterOfConsentInitiation.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) { - - Object submissionCreditorAccounts = initiationOfSubmission. - get(ConsentExtensionConstants.CREDITOR_ACC); - Object consentInitiationCreditorAccounts = initiationParameterOfConsentInitiation. - get(ConsentExtensionConstants.CREDITOR_ACC); - - if (submissionCreditorAccounts instanceof JSONObject && - consentInitiationCreditorAccounts instanceof JSONObject) { - JSONObject submissionCreditorAccount = (JSONObject) initiationOfSubmission. - get(ConsentExtensionConstants.CREDITOR_ACC); - JSONObject consentInitiationCreditorAccount = (JSONObject) - initiationParameterOfConsentInitiation.get(ConsentExtensionConstants.CREDITOR_ACC); - - JSONObject creditorAccValidationResult = ConsentValidatorUtil. - validateCreditorAcc(submissionCreditorAccount, consentInitiationCreditorAccount); - if (!Boolean.parseBoolean(creditorAccValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return creditorAccValidationResult; - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INITIATION_CREDITOR_ACC_NOT_JSON_ERROR); - } - } - - //Validate Debtor Account - // This code if condition checks whether the debtor account parameter is present in both the request - // payloads (Initiation and the submission payloads) since both the payloads as to be equal. - if ((!initiationOfSubmission.containsKey(ConsentExtensionConstants.DEBTOR_ACC) && - initiationParameterOfConsentInitiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) || - (initiationOfSubmission.containsKey(ConsentExtensionConstants.DEBTOR_ACC) && - !initiationParameterOfConsentInitiation. - containsKey(ConsentExtensionConstants.DEBTOR_ACC))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.DEBTOR_ACC_NOT_FOUND); - } else if (initiationOfSubmission.containsKey(ConsentExtensionConstants.DEBTOR_ACC) && - initiationParameterOfConsentInitiation.containsKey(ConsentExtensionConstants.DEBTOR_ACC)) { - - Object submissionDebtorAccounts = initiationOfSubmission - .get(ConsentExtensionConstants.DEBTOR_ACC); - Object consentInitiationDebtorAccounts = initiationParameterOfConsentInitiation - .get(ConsentExtensionConstants.DEBTOR_ACC); - - if (submissionDebtorAccounts instanceof JSONObject && - consentInitiationDebtorAccounts instanceof JSONObject) { - JSONObject submissionDebtorAccount = (JSONObject) initiationOfSubmission - .get(ConsentExtensionConstants.DEBTOR_ACC); - JSONObject consentInitiationDebtorAccount = (JSONObject) initiationParameterOfConsentInitiation - .get(ConsentExtensionConstants.DEBTOR_ACC); - - JSONObject debtorAccValidationResult = ConsentValidatorUtil. - validateDebtorAcc(submissionDebtorAccount, consentInitiationDebtorAccount); - if (!Boolean.parseBoolean(debtorAccValidationResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return debtorAccValidationResult; - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.DEBTOR_ACC_NOT_JSON_ERROR); - } - } - - if ((!initiationOfSubmission.containsKey(ConsentExtensionConstants.REMITTANCE_INFO) - && initiationParameterOfConsentInitiation.containsKey(ConsentExtensionConstants.REMITTANCE_INFO)) || - (initiationOfSubmission.containsKey(ConsentExtensionConstants.REMITTANCE_INFO) - && !initiationParameterOfConsentInitiation. - containsKey(ConsentExtensionConstants.REMITTANCE_INFO))) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.REMITTANCE_INFO_NOT_FOUND); - } else if (initiationOfSubmission.containsKey(ConsentExtensionConstants.REMITTANCE_INFO) - && initiationParameterOfConsentInitiation. - containsKey(ConsentExtensionConstants.REMITTANCE_INFO)) { - - Object remittanceInformationSubmission = initiationOfSubmission - .get(ConsentExtensionConstants.REMITTANCE_INFO); - Object remittanceInformationInitiation = initiationParameterOfConsentInitiation - .get(ConsentExtensionConstants.REMITTANCE_INFO); - - if (remittanceInformationSubmission instanceof JSONObject && - remittanceInformationInitiation instanceof JSONObject) { - JSONObject remittanceInformationSub = (JSONObject) initiationOfSubmission - .get(ConsentExtensionConstants.REMITTANCE_INFO); - JSONObject remittanceInformationInit = (JSONObject) initiationParameterOfConsentInitiation - .get(ConsentExtensionConstants.REMITTANCE_INFO); - - JSONObject validateRemittanceInfoResult = VRPSubmissionPayloadValidator.validateRemittanceInfo - (remittanceInformationSub, remittanceInformationInit); - if (!Boolean.parseBoolean(validateRemittanceInfoResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return validateRemittanceInfoResult; - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INITIATION_REMITTANCE_INFO_NOT_JSON_ERROR); - } - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INVALID_PARAMETER); - } - - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Validates the instruction between submission and initiation JSONObjects. - * - * @param submission The submission JSONObject from submission request. - * @param initiation The initiation JSONObject from initiation request, here we consider the initiation parameter - * since the creditor account from the initiation request need to be retrieved. - * @return A JSONObject indicating the validation result. It contains a boolean value under the key - * ConsentExtensionConstants.IS_VALID_PAYLOAD, indicating whether the payload is valid. If the - * validation fails, it returns a JSONObject containing error details with keys defined in ErrorConstants. - */ - public static JSONObject validateInstruction(JSONObject submission, - JSONObject initiation) { - - if (submission != null && initiation != null) { - - if (!submission.containsKey(ConsentExtensionConstants.INSTRUCTED_AMOUNT)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTED_AMOUNT_NOT_FOUND); - } else { - Object instructedAmountObject = submission.get(ConsentExtensionConstants.INSTRUCTED_AMOUNT); - - if (isValidJSONObject(instructedAmountObject)) { - JSONObject instructedAmount = (JSONObject) instructedAmountObject; - if (!instructedAmount.containsKey(ConsentExtensionConstants.AMOUNT)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTED_AMOUNT_AMOUNT_NOT_FOUND); - } else { - Object amountValue = instructedAmount.get(ConsentExtensionConstants.AMOUNT); - if (!isValidString(amountValue)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INSTRUCTED_AMOUNT_NOT_STRING); - } - - if (!instructedAmount.containsKey(ConsentExtensionConstants.CURRENCY)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTED_AMOUNT_CURRENCY_NOT_FOUND); - } else { - Object currencyValue = instructedAmount.get(ConsentExtensionConstants.CURRENCY); - if (!isValidString(currencyValue)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INSTRUCTED_AMOUNT_CURRENCY_NOT_STRING); - } - } - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INSTRUCTED_AMOUNT_NOT_JSON_ERROR); - } - } - - //Validate Creditor Account - JSONObject validateCreditorAccResult = VRPSubmissionPayloadValidator.validateCreditorAcc - (submission, initiation); - if (!Boolean.parseBoolean(validateCreditorAccResult. - get(ConsentExtensionConstants.IS_VALID_PAYLOAD).toString())) { - return validateCreditorAccResult; - } - - if (submission.containsKey(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION)) { - Object value = submission.get(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION); - - // Check if the instruction_identification is an instance of a string - if (!isValidString(value)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_SUBMISSION_TYPE); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTION_IDENTIFICATION_NOT_FOUND); - } - - if (submission.containsKey(ConsentExtensionConstants.END_TO_END_IDENTIFICATION)) { - Object endToEndIdentificationValue = submission. - get(ConsentExtensionConstants.END_TO_END_IDENTIFICATION); - if (!isValidString(endToEndIdentificationValue)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INVALID_END_TO_END_IDENTIFICATION_TYPE); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.END_TO_END_IDENTIFICATION_PARAMETER_NOT_FOUND); - } - - if ((!submission.containsKey(ConsentExtensionConstants.REMITTANCE_INFO) - && initiation.containsKey(ConsentExtensionConstants.REMITTANCE_INFO)) || - (submission.containsKey(ConsentExtensionConstants.REMITTANCE_INFO) - && !initiation.containsKey(ConsentExtensionConstants.REMITTANCE_INFO))) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.REMITTANCE_INFO_NOT_FOUND); - } else if (submission.containsKey(ConsentExtensionConstants.REMITTANCE_INFO) - && initiation.containsKey(ConsentExtensionConstants.REMITTANCE_INFO)) { - Object remittanceInformationSubmission = submission - .get(ConsentExtensionConstants.REMITTANCE_INFO); - Object remittanceInformationInitiation = initiation - .get(ConsentExtensionConstants.REMITTANCE_INFO); - - if (remittanceInformationSubmission instanceof JSONObject && - remittanceInformationInitiation instanceof JSONObject) { - JSONObject remittanceInformationSub = (JSONObject) submission - .get(ConsentExtensionConstants.REMITTANCE_INFO); - JSONObject remittanceInformationInit = (JSONObject) initiation - .get(ConsentExtensionConstants.REMITTANCE_INFO); - - JSONObject remittanceInfoValidationResult = VRPSubmissionPayloadValidator.validateRemittanceInfo - (remittanceInformationSub, remittanceInformationInit); - if ((!Boolean.parseBoolean(remittanceInfoValidationResult. - get(ConsentExtensionConstants.IS_VALID_PAYLOAD).toString()))) { - return remittanceInfoValidationResult; - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INSTRUCTION_REMITTANCE_INFO_NOT_JSON_ERROR); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INVALID_PARAMETER); - } - } - - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Validates the remittance information between two remittance information JSONObjects. - * - * @param remittanceInformationSub The remittance information from the submission request. - * @param remittanceInformationInit The remittance information from the initiation request. - * @return A JSONObject indicating the validation result. It contains a boolean value under the key - * ConsentExtensionConstants.IS_VALID_PAYLOAD, indicating whether the payload is valid. If the - * validation fails, it returns a JSONObject containing error details with keys defined in ErrorConstants. - */ - public static JSONObject validateRemittanceInfo(JSONObject remittanceInformationSub, - JSONObject remittanceInformationInit) { - - if (!ConsentValidatorUtil.compareOptionalParameter( - remittanceInformationSub.getAsString(ConsentExtensionConstants.REFERENCE), - remittanceInformationInit.getAsString(ConsentExtensionConstants.REFERENCE))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.REMITTANCE_INFO_MISMATCH); - } - - if (!ConsentValidatorUtil.compareOptionalParameter( - remittanceInformationSub.getAsString(ConsentExtensionConstants.UNSTRUCTURED), - remittanceInformationInit.getAsString(ConsentExtensionConstants.UNSTRUCTURED))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.REMITTANCE_UNSTRUCTURED_MISMATCH); - } - - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Validates the risk parameters between the risk of submission and the risk of initiation JSONObjects. - * - * @param riskOfSubmission The risk parameters from the submission. - * @param riskOfInitiation The risk parameters from the initiation. - * @return A JSONObject indicating the validation result. It contains a boolean value under the key - * ConsentExtensionConstants.IS_VALID_PAYLOAD, indicating whether the payload is valid. If the - * validation fails, it returns a JSONObject containing error details with keys defined in ErrorConstants. - */ - public static JSONObject validateRisk(JSONObject riskOfSubmission, - JSONObject riskOfInitiation) { - - if (!ConsentValidatorUtil.compareOptionalParameter( - riskOfSubmission.getAsString(ConsentExtensionConstants.CONTEXT_CODE), - riskOfInitiation.getAsString(ConsentExtensionConstants.CONTEXT_CODE))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.RISK_PARAMETER_MISMATCH); - } - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * This method validates whether the risk parameter is present in the request and validates the risk parameter is an - * instance of JSONObject. - * - * @param submissionJson - * @return validationResult - */ - public static JSONObject validateRiskParameter(JSONObject submissionJson) { - - //Validate RISK - if (submissionJson.containsKey(ConsentExtensionConstants.RISK)) { - - Object dataObject = submissionJson.get(ConsentExtensionConstants.RISK); - // Check if the risk is valid JSON Object - if (!isValidJSONObject(dataObject)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.RISK_NOT_JSON_ERROR); - } - } else { - log.error(ErrorConstants.RISK_NOT_FOUND); - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.RISK_NOT_FOUND); - } - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Checks if the given Object is a JSONObject and the JSONObject is non-empty , and it is an instance of a string. - * - * @param value The Object to be validated. - * @return true if the object is a non-null and non-empty JSONObject. - */ - public static boolean isValidString(Object value) { - return value instanceof String; - } - - /** - * Validates initiation parameter in the submission data. - * - * @param submissionData The JSONObject containing submission data. - * @return A JSONObject indicating the validation result. - */ - public static JSONObject validateInitiationParameter(JSONObject submissionData) { - - if (submissionData.containsKey(ConsentExtensionConstants.INITIATION)) { - - Object dataObject = submissionData.get(ConsentExtensionConstants.INITIATION); - - if (!isValidJSONObject(dataObject)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INITIATION_NOT_JSON); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INITIATION_NOT_FOUND); - } - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Validates instruction parameter in the submission data. - * - * @param submissionData The JSONObject containing submission data. - * @return A JSONObject indicating the validation result. - */ - public static JSONObject validateInstructionParameter(JSONObject submissionData) { - - if (submissionData.containsKey(ConsentExtensionConstants.INSTRUCTION)) { - - Object dataObject = submissionData.get(ConsentExtensionConstants.INSTRUCTION); - if (!isValidJSONObject(dataObject)) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INSTRUCTION_NOT_JSON); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTION_NOT_FOUND); - } - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Extracts submission data from a JSONObject. - * - * @param submissionJson The JSONObject containing submission data. - * @return A JSONObject indicating the validation result. - */ - public static JSONObject validateSubmissionData(JSONObject submissionJson) { - - if (!submissionJson.containsKey(ConsentExtensionConstants.DATA) && - !(submissionJson.get(ConsentExtensionConstants.DATA) instanceof JSONObject)) { - log.error(ErrorConstants.DATA_NOT_FOUND); - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.DATA_NOT_FOUND); - } - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } - - /** - * Checks if the given object is a valid JSONObject. - * - * @param value The object to be checked. - * @return true if the object is a JSONObject, otherwise false. - */ - public static boolean isValidJSONObject(Object value) { - return value instanceof JSONObject; - } - - /** - * Validates the creditor account parameter between the creditor account of submission under instruction parameter - * and the creditor account of initiation JSONObjects. - * - * @param submission The creditor account parameters from the submission. - * @param initiation The creditor account parameters from the initiation. - * @return A JSONObject indicating the validation result. It contains a boolean value under the key - * ConsentExtensionConstants.IS_VALID_PAYLOAD, indicating whether the payload is valid. If the - * validation fails, it returns a JSONObject containing error details with keys defined in ErrorConstants. - */ - public static JSONObject validateCreditorAcc(JSONObject submission, - JSONObject initiation) { - JSONObject validationResult = new JSONObject(); - - if (submission.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) { - // If the CreditorAccount was not specified in the consent initiation,the CreditorAccount must be specified - // in the instruction present in the submission payload. - if (!initiation.containsKey(ConsentExtensionConstants.CREDITOR_ACC)) { - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - } else { - Object submissionCreditorAccounts = submission.get(ConsentExtensionConstants.CREDITOR_ACC); - Object consentInitiationCreditorAccounts = initiation.get(ConsentExtensionConstants.CREDITOR_ACC); - - if (submissionCreditorAccounts instanceof JSONObject && - consentInitiationCreditorAccounts instanceof JSONObject) { - JSONObject submissionCreditorAccount = (JSONObject) submission. - get(ConsentExtensionConstants.CREDITOR_ACC); - JSONObject consentInitiationCreditorAccount = (JSONObject) initiation. - get(ConsentExtensionConstants.CREDITOR_ACC); - - JSONObject creditorAccValidationResult = ConsentValidatorUtil. - validateCreditorAcc(submissionCreditorAccount, consentInitiationCreditorAccount); - if (!Boolean.parseBoolean(validationResult. - getAsString(ConsentExtensionConstants.IS_VALID_PAYLOAD))) { - return creditorAccValidationResult; - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_INVALID, - ErrorConstants.INSTRUCTION_CREDITOR_ACC_NOT_JSON_ERROR); - } - } - } else { - // Creditor account present under the instruction in the submission request - // is considered to be a mandatory parameter - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.CREDITOR_ACC_NOT_FOUND); - } - - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - return validationResult; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidateData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidateData.java deleted file mode 100644 index 14525e22..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidateData.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.model; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import net.minidev.json.JSONObject; - -import java.util.Map; -import java.util.TreeMap; - -/** - * Data wrapper for consent validate data. - */ -public class ConsentValidateData { - - private JSONObject headers; - private JSONObject payload; - private String requestPath; - private String consentId; - private String userId; - private String clientId; - private Map resourceParams; - private DetailedConsentResource comprehensiveConsent; - private TreeMap headersMap; - - public ConsentValidateData(JSONObject headers, JSONObject payload, String requestPath, String consentId, - String userId, String clientId, Map resourceParams) { - this.headers = headers; - this.payload = payload; - this.requestPath = requestPath; - this.consentId = consentId; - this.userId = userId; - this.clientId = clientId; - this.resourceParams = resourceParams; - } - - public ConsentValidateData(JSONObject headers, JSONObject payload, String requestPath, String consentId, - String userId, String clientId, Map resourceParams, - TreeMap headersMap) { - this.headers = headers; - this.payload = payload; - this.requestPath = requestPath; - this.consentId = consentId; - this.userId = userId; - this.clientId = clientId; - this.resourceParams = resourceParams; - this.headersMap = headersMap; - } - - public String getRequestPath() { - return requestPath; - } - - public JSONObject getPayload() { - return payload; - } - - public JSONObject getHeaders() { - return headers; - } - - public DetailedConsentResource getComprehensiveConsent() { - return comprehensiveConsent; - } - - public void setComprehensiveConsent(DetailedConsentResource comprehensiveConsent) { - this.comprehensiveConsent = comprehensiveConsent; - } - - public String getConsentId() { - return consentId; - } - - public void setConsentId(String consentId) { - this.consentId = consentId; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public Map getResourceParams() { - return resourceParams; - } - - public void setResourceParams(Map resourceParams) { - this.resourceParams = resourceParams; - } - - public TreeMap getHeadersMap() { - return headersMap; - } - - private void setHeadersMap(TreeMap headersMap) { - this.headersMap = headersMap; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidationResult.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidationResult.java deleted file mode 100644 index f59bb436..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidationResult.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.model; - -import net.minidev.json.JSONObject; - -/** - * Data wrapper for the result of consent validation. - */ -public class ConsentValidationResult { - - private boolean isValid = false; - private JSONObject modifiedPayload = null; - private JSONObject consentInformation = new JSONObject(); - /** - * errorCode, errorMessage and httpCode have to be set in error/invalid scenarios. - */ - private String errorCode = null; - private String errorMessage = null; - private int httpCode = 0; - - public boolean isValid() { - return isValid; - } - - public void setValid(boolean valid) { - isValid = valid; - } - - public JSONObject getModifiedPayload() { - return modifiedPayload; - } - - public void setModifiedPayload(JSONObject modifiedPayload) { - this.modifiedPayload = modifiedPayload; - } - - public JSONObject getConsentInformation() { - return consentInformation; - } - - public void setConsentInformation(JSONObject consentInformation) { - this.consentInformation = consentInformation; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public int getHttpCode() { - return httpCode; - } - - public void setHttpCode(int httpCode) { - this.httpCode = httpCode; - } - - public JSONObject generatePayload() throws Exception { - JSONObject payload = new JSONObject(); - payload.appendField("isValid", isValid); - if (modifiedPayload != null) { - payload.appendField("modifiedPayload", modifiedPayload); - } - if (errorCode != null && errorMessage != null && httpCode != 0) { - payload.appendField("errorCode", errorCode); - payload.appendField("errorMessage", errorMessage); - payload.appendField("httpCode", httpCode); - } - return payload; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidator.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidator.java deleted file mode 100644 index 9f7767d8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/model/ConsentValidator.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.model; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; - -/** - * Consent validator interface. - */ -public interface ConsentValidator { - - /** - * Validate function to implement required validations. - * - * @param consentValidateData Object with data of the request and consent needed for validations - * @param consentValidationResult Object to set data with regard to the validation result - * @throws ConsentException Error object with data required for the error response - */ - public void validate(ConsentValidateData consentValidateData, ConsentValidationResult consentValidationResult) - throws ConsentException; - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/util/ConsentValidatorUtil.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/util/ConsentValidatorUtil.java deleted file mode 100644 index a80d3ba6..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/util/ConsentValidatorUtil.java +++ /dev/null @@ -1,302 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.util; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidationResult; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; - -import java.time.OffsetDateTime; -import java.time.format.DateTimeParseException; -import java.util.Arrays; -import java.util.List; - -/** - * Consent validate util class for accelerator. - */ -public class ConsentValidatorUtil { - - private static final Log log = LogFactory.getLog(ConsentValidatorUtil.class); - - /** - * Utility method to validate mandatory parameters. - * - * @param str1 First String to validate - * @param str2 Second String to validate - * @return Whether mandatory parameters are same - */ - public static boolean compareMandatoryParameter(String str1, String str2) { - - return (str1 == null) || (str2 == null) ? false : str1.equals(str2); - - } - - /** - * Method to construct the validation result. - * - * @param errorCode Error Code - * @param errorMessage Error Message - * @return Validation Result - */ - public static JSONObject getValidationResult(String errorCode, String errorMessage) { - - JSONObject validationResult = new JSONObject(); - log.error(errorMessage); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, false); - validationResult.put(ConsentExtensionConstants.ERROR_CODE, errorCode); - validationResult.put(ConsentExtensionConstants.ERROR_MESSAGE, errorMessage); - - return validationResult; - } - - - /** - * Populates the provided consent validation result object with error information. - * - * @param errorResult the JSONObject containing error details, specifically error message and error code - * @param consentValidationResult the ConsentValidationResult object to be updated with error details - * - */ - public static void setErrorMessageForConsentValidationResult(JSONObject errorResult - , ConsentValidationResult consentValidationResult) { - - String errorMessage = errorResult.getAsString(ConsentExtensionConstants.ERROR_MESSAGE); - String errorCode = errorResult.getAsString(ConsentExtensionConstants.ERROR_CODE); - - consentValidationResult.setErrorMessage(errorMessage); - consentValidationResult.setErrorCode(errorCode); - consentValidationResult.setHttpCode(HttpStatus.SC_BAD_REQUEST); - } - - /** - * Method to construct the success validation result. - * - * @return Validation Result - */ - public static JSONObject getSuccessValidationResult() { - - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - - return validationResult; - } - - /** - * Validate whether fields in creditor account from initiation and submission are same. - * - * @param subCreditorAccount Creditor Account from submission request - * @param initCreditorAccount Creditor Account from initiation request - * @return Validation Result - */ - public static JSONObject validateCreditorAcc(JSONObject subCreditorAccount, JSONObject initCreditorAccount) { - - if (subCreditorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME)) { - if (StringUtils.isEmpty(subCreditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME)) || - !ConsentValidatorUtil.compareMandatoryParameter( - subCreditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME), - initCreditorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.CREDITOR_ACC_SCHEME_NAME_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.CREDITOR_ACC_SCHEME_NAME_NOT_FOUND); - } - - if (subCreditorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION)) { - if (StringUtils.isEmpty(subCreditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION)) || - !ConsentValidatorUtil.compareMandatoryParameter( - subCreditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION), - initCreditorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.CREDITOR_ACC_IDENTIFICATION_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.CREDITOR_ACC_IDENTIFICATION_NOT_FOUND); - } - - if (!ConsentValidatorUtil - .compareOptionalParameter(subCreditorAccount.getAsString(ConsentExtensionConstants.NAME), - initCreditorAccount.getAsString(ConsentExtensionConstants.NAME))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.CREDITOR_ACC_NAME_MISMATCH); - } - - if (!ConsentValidatorUtil.compareOptionalParameter(subCreditorAccount - .getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION), - initCreditorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION))) { - - return ConsentValidatorUtil - .getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.CREDITOR_ACC_SEC_IDENTIFICATION_MISMATCH); - } - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - - return validationResult; - } - /** - * Utility method to validate optional parameters. - * - * @param str1 First String to validate - * @param str2 Second String to validate - * @return Whether optional parameters are same - */ - public static boolean compareOptionalParameter(String str1, String str2) { - - boolean isStr1Empty = StringUtils.isBlank(str1); - boolean isStr2Empty = StringUtils.isBlank(str2); - - if (!(isStr1Empty || isStr2Empty)) { - return str1.equals(str2); - } else { - return (isStr1Empty && isStr2Empty); - } - } - - /** - * Validate whether fields in debtor account from initiation and submission are same. - * - * @param subDebtorAccount Debtor Account from submission request - * @param initDebtorAccount Debtor Account from initiation request - * @return Validation Result - */ - public static JSONObject validateDebtorAcc(JSONObject subDebtorAccount, JSONObject initDebtorAccount) { - - if (subDebtorAccount.containsKey(ConsentExtensionConstants.SCHEME_NAME)) { - if (StringUtils.isEmpty(subDebtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME)) || - !ConsentValidatorUtil.compareMandatoryParameter( - subDebtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME), - initDebtorAccount.getAsString(ConsentExtensionConstants.SCHEME_NAME))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.DEBTOR_ACC_SCHEME_NAME_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.DEBTOR_ACC_SCHEME_NAME_NOT_FOUND); - } - - if (subDebtorAccount.containsKey(ConsentExtensionConstants.IDENTIFICATION)) { - if (StringUtils.isEmpty(subDebtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION)) || - !ConsentValidatorUtil.compareMandatoryParameter( - subDebtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION), - initDebtorAccount.getAsString(ConsentExtensionConstants.IDENTIFICATION))) { - - return ConsentValidatorUtil - .getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.DEBTOR_ACC_IDENTIFICATION_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.DEBTOR_ACC_IDENTIFICATION_NOT_FOUND); - } - - if (!ConsentValidatorUtil.compareOptionalParameter( - subDebtorAccount.getAsString(ConsentExtensionConstants.NAME), - initDebtorAccount.getAsString(ConsentExtensionConstants.NAME))) { - - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.DEBTOR_ACC_NAME_MISMATCH); - } - - if (!ConsentValidatorUtil.compareOptionalParameter(subDebtorAccount - .getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION), - initDebtorAccount.getAsString(ConsentExtensionConstants.SECONDARY_IDENTIFICATION))) { - - return ConsentValidatorUtil - .getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.DEBTOR_ACC_SEC_IDENTIFICATION_MISMATCH); - } - - JSONObject validationResult = new JSONObject(); - validationResult.put(ConsentExtensionConstants.IS_VALID_PAYLOAD, true); - - return validationResult; - } - /** - * Method provides API resource paths applicable for Confirmtaion of Funds API. - * - * @return map of API Resources. - */ - public static List getCOFAPIPathRegexArray() { - - List requestUrls = Arrays.asList(ConsentExtensionConstants.COF_CONSENT_INITIATION_PATH, - ConsentExtensionConstants.COF_CONSENT_CONSENT_ID_PATH, - ConsentExtensionConstants.COF_SUBMISSION_PATH); - - return requestUrls; - - } - - - /** - * Util method to validate the Confirmation of Funds request URI. - * - * @param uri Request URI - * @return Whether URI is valid - */ - public static boolean isCOFURIValid(String uri) { - - List accountPaths = getCOFAPIPathRegexArray(); - - for (String entry : accountPaths) { - if (uri.equals(entry)) { - return true; - } - } - - return false; - } - - /** - * Validate whether consent is expired. - * - * @param expDateVal Expiration Date Time - * @return Whether consent is expired - * @throws ConsentException if an error occurs while parsing expiration date - */ - public static boolean isConsentExpired(String expDateVal) throws ConsentException { - - if (expDateVal != null && !expDateVal.isEmpty()) { - try { - OffsetDateTime expDate = OffsetDateTime.parse(expDateVal); - return OffsetDateTime.now().isAfter(expDate); - } catch (DateTimeParseException e) { - log.error(ErrorConstants.EXP_DATE_PARSE_ERROR + " : " + expDateVal); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - ErrorConstants.EXP_DATE_PARSE_ERROR); - } - } else { - return false; - } - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/util/PaymentSubmissionValidationUtil.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/util/PaymentSubmissionValidationUtil.java deleted file mode 100644 index dbfa8cb6..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/java/com/wso2/openbanking/accelerator/consent/extensions/validate/util/PaymentSubmissionValidationUtil.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.validate.util; - -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import net.minidev.json.JSONObject; -import org.apache.commons.lang3.StringUtils; - -/** - * Util class for Payment Submission Validation. - */ -public class PaymentSubmissionValidationUtil { - - public static JSONObject validateInstructionIdentification (JSONObject submission, JSONObject initiation) { - if (submission.containsKey(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION)) { - if (StringUtils.isEmpty(submission.getAsString(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION)) - || !ConsentValidatorUtil.compareMandatoryParameter( - submission.getAsString(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION), - initiation.getAsString(ConsentExtensionConstants.INSTRUCTION_IDENTIFICATION))) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.INSTRUCTION_IDENTIFICATION_MISMATCH); - } - } - return ConsentValidatorUtil.getSuccessValidationResult(); - } - - public static JSONObject validateEndToEndIdentification (JSONObject submission, JSONObject initiation) { - - if (submission.containsKey(ConsentExtensionConstants.END_TO_END_IDENTIFICATION)) { - if (StringUtils.isEmpty(submission.getAsString(ConsentExtensionConstants.END_TO_END_IDENTIFICATION)) - || !ConsentValidatorUtil.compareMandatoryParameter( - submission.getAsString(ConsentExtensionConstants.END_TO_END_IDENTIFICATION), - initiation.getAsString(ConsentExtensionConstants.END_TO_END_IDENTIFICATION))) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.END_TO_END_IDENTIFICATION_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.END_TO_END_IDENTIFICATION_NOT_FOUND); - } - - return ConsentValidatorUtil.getSuccessValidationResult(); - } - - public static JSONObject validateInstructedAmount (JSONObject submission, JSONObject initiation) { - - if (submission.containsKey(ConsentExtensionConstants.INSTRUCTED_AMOUNT)) { - - JSONObject subInstrAmount = (JSONObject) submission.get(ConsentExtensionConstants.INSTRUCTED_AMOUNT); - JSONObject initInstrAmount = (JSONObject) initiation.get(ConsentExtensionConstants.INSTRUCTED_AMOUNT); - - if (subInstrAmount.containsKey(ConsentExtensionConstants.AMOUNT)) { - if (StringUtils.isEmpty(subInstrAmount.getAsString(ConsentExtensionConstants.AMOUNT)) || - !ConsentValidatorUtil.compareMandatoryParameter( - subInstrAmount.getAsString(ConsentExtensionConstants.AMOUNT), - initInstrAmount.getAsString(ConsentExtensionConstants.AMOUNT))) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.INSTRUCTED_AMOUNT_AMOUNT_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTED_AMOUNT_AMOUNT_NOT_FOUND); - } - - if (subInstrAmount.containsKey(ConsentExtensionConstants.CURRENCY)) { - if (StringUtils.isEmpty(subInstrAmount.getAsString(ConsentExtensionConstants.CURRENCY)) || - !ConsentValidatorUtil.compareMandatoryParameter( - subInstrAmount.getAsString(ConsentExtensionConstants.CURRENCY), - initInstrAmount.getAsString(ConsentExtensionConstants.CURRENCY))) { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.RESOURCE_CONSENT_MISMATCH, - ErrorConstants.INSTRUCTED_AMOUNT_CURRENCY_MISMATCH); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTED_AMOUNT_CURRENCY_NOT_FOUND); - } - } else { - return ConsentValidatorUtil.getValidationResult(ErrorConstants.FIELD_MISSING, - ErrorConstants.INSTRUCTED_AMOUNT_NOT_FOUND); - } - - return ConsentValidatorUtil.getSuccessValidationResult(); - } - -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index 5160ee77..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/persistence/flow/ConsentPersistStepTests.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/persistence/flow/ConsentPersistStepTests.java deleted file mode 100644 index db75703c..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/persistence/flow/ConsentPersistStepTests.java +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.vrp.persistence.flow; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.impl.DefaultConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistData; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentAuthorizeTestConstants; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestUtils; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockObjectFactory; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test class for Consent Persistence. - */ -@PrepareForTest({OpenBankingConfigParser.class, ConsentServiceUtil.class}) -@PowerMockIgnore({"com.wso2.openbanking.accelerator.consent.extensions.common.*", "net.minidev.*", - "jdk.internal.reflect.*"}) -public class ConsentPersistStepTests { - - @Mock - OpenBankingConfigParser openBankingConfigParserMock; - @Mock - private static DefaultConsentPersistStep consentPersistStep; - @Mock - private static ConsentPersistData consentPersistDataMock; - @Mock - private static ConsentData consentDataMock; - @Mock - private static ConsentResource consentResourceMock; - @Mock - ConsentCoreServiceImpl consentCoreServiceMock; - private static Map configMap; - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - - @BeforeClass - public void initTest() throws ReflectiveOperationException { - - MockitoAnnotations.initMocks(this); - - consentPersistStep = new DefaultConsentPersistStep(); - consentPersistDataMock = Mockito.mock(ConsentPersistData.class); - consentDataMock = Mockito.mock(ConsentData.class); - consentResourceMock = Mockito.mock(ConsentResource.class); - consentCoreServiceMock = Mockito.mock(ConsentCoreServiceImpl.class); - - configMap = new HashMap<>(); - configMap.put("ErrorURL", "https://localhost:8243/error"); - - //to execute util class initialization - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - ConsentExtensionTestUtils.injectEnvironmentVariable("CARBON_HOME", "."); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new PowerMockObjectFactory(); - } - - @BeforeMethod - public void initMethod() { - - openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - } - - @Test(priority = 1, expectedExceptions = ConsentException.class) - public void testConsentPersistWithoutConsentId() { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - consentPersistStep.execute(consentPersistDataMock); - } - - @Test(priority = 3, expectedExceptions = ConsentException.class) - public void testConsentPersistWithoutAuthResource() { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - Mockito.doReturn("1234").when(consentDataMock).getConsentId(); - Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); - - consentPersistStep.execute(consentPersistDataMock); - } - - @Test(priority = 6, expectedExceptions = ConsentException.class) - public void testAccountConsentPersistWithoutAccountIDs() throws Exception { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CONSENT_ID).when(consentDataMock).getConsentId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.USER_ID).when(consentDataMock).getUserId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CLIENT_ID).when(consentDataMock).getClientId(); - Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.getAuthResource()).when(consentDataMock).getAuthResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(true).when(consentPersistDataMock).getApproval(); - - JSONObject payload = (JSONObject) parser - .parse(ConsentAuthorizeTestConstants.ACCOUNT_PERSIST_PAYLOAD_WITHOUT_ACCOUNT_ID); - Mockito.doReturn(payload).when(consentPersistDataMock).getPayload(); - - consentPersistStep.execute(consentPersistDataMock); - } - - @Test(priority = 7, expectedExceptions = ConsentException.class) - public void testAccountConsentPersistWithNonStringAccountIDs() throws Exception { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CONSENT_ID).when(consentDataMock).getConsentId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.USER_ID).when(consentDataMock).getUserId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CLIENT_ID).when(consentDataMock).getClientId(); - Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.getAuthResource()).when(consentDataMock).getAuthResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(true).when(consentPersistDataMock).getApproval(); - - JSONObject payload = (JSONObject) parser - .parse(ConsentAuthorizeTestConstants.PAYLOAD_WITH_NON_STRING_ACCOUNTID); - Mockito.doReturn(payload).when(consentPersistDataMock).getPayload(); - - consentPersistStep.execute(consentPersistDataMock); - } - - @Test(priority = 9, expectedExceptions = ConsentException.class) - public void testCOFConsentPersistWithoutCOFAccount() throws Exception { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CONSENT_ID).when(consentDataMock).getConsentId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.USER_ID).when(consentDataMock).getUserId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CLIENT_ID).when(consentDataMock).getClientId(); - Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.getAuthResource()).when(consentDataMock).getAuthResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.FUNDS_CONFIRMATIONS).when(consentResourceMock) - .getConsentType(); - Mockito.doReturn(true).when(consentPersistDataMock).getApproval(); - - JSONObject payload = (JSONObject) parser - .parse(ConsentAuthorizeTestConstants.COF_PERSIST_PAYLOAD_WITHOUT_COF_ACC); - Mockito.doReturn(payload).when(consentPersistDataMock).getPayload(); - - consentPersistStep.execute(consentPersistDataMock); - } - - @Test(priority = 10, expectedExceptions = ConsentException.class) - public void testCOFConsentPersistWithNonStringCOFAccount() throws Exception { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CONSENT_ID).when(consentDataMock).getConsentId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.USER_ID).when(consentDataMock).getUserId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CLIENT_ID).when(consentDataMock).getClientId(); - Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.getAuthResource()).when(consentDataMock).getAuthResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.FUNDS_CONFIRMATIONS).when(consentResourceMock) - .getConsentType(); - Mockito.doReturn(true).when(consentPersistDataMock).getApproval(); - - JSONObject payload = (JSONObject) parser - .parse(ConsentAuthorizeTestConstants.COF_PERSIST_PAYLOAD_WITH_NON_STRING_COF_ACC); - Mockito.doReturn(payload).when(consentPersistDataMock).getPayload(); - - consentPersistStep.execute(consentPersistDataMock); - } - - @Test(priority = 11, expectedExceptions = ConsentException.class) - public void testCOFPersistThrowingExceptionWhenConsentBinding() throws Exception { - - Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CONSENT_ID).when(consentDataMock).getConsentId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.USER_ID).when(consentDataMock).getUserId(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CLIENT_ID).when(consentDataMock).getClientId(); - Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.getAuthResource()).when(consentDataMock).getAuthResource(); - Mockito.doReturn(ConsentAuthorizeTestConstants.FUNDS_CONFIRMATIONS).when(consentResourceMock) - .getConsentType(); - Mockito.doReturn(false).when(consentPersistDataMock).getApproval(); - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - JSONObject payload = (JSONObject) parser - .parse(ConsentAuthorizeTestConstants.COF_PERSIST_PAYLOAD); - Mockito.doReturn(payload).when(consentPersistDataMock).getPayload(); - - consentPersistStep.execute(consentPersistDataMock); -} - -// @Test -// public void testAccountConsentPersistSuccessScenarioWithApprovalTrue() -// throws ParseException, ConsentManagementException { -// -// Mockito.doReturn(consentDataMock).when(consentPersistDataMock).getConsentData(); -// Mockito.doReturn(ConsentAuthorizeTestConstants.CONSENT_ID).when(consentDataMock).getConsentId(); -// Mockito.doReturn(ConsentAuthorizeTestConstants.USER_ID).when(consentDataMock).getUserId(); -// Mockito.doReturn(ConsentAuthorizeTestConstants.CLIENT_ID).when(consentDataMock).getClientId(); -// Mockito.doReturn(consentResourceMock).when(consentDataMock).getConsentResource(); -// Mockito.doReturn(ConsentAuthorizeTestConstants.getAuthResource()).when(consentDataMock).getAuthResource(); -// Mockito.doReturn(ConsentAuthorizeTestConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); -// Mockito.doReturn(true).when(consentPersistDataMock).getApproval(); -// -// Mockito.doReturn(true).when(consentCoreServiceMock).bindUserAccountsToConsent( -// Mockito.anyObject(), Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), -// Mockito.anyString(), Mockito.anyString()); -// -// PowerMockito.mockStatic(ConsentServiceUtil.class); -// PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); -// -// JSONObject payload = (JSONObject) parser.parse(ConsentAuthorizeTestConstants.ACCOUNT_PERSIST_PAYLOAD); -// Mockito.doReturn(payload).when(consentPersistDataMock).getPayload(); -// -// consentPersistStep.execute(consentPersistDataMock); -// } -} - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/ConsentExtensionDataProvider.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/ConsentExtensionDataProvider.java deleted file mode 100644 index 098a8706..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/ConsentExtensionDataProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.authorize.vrp.retrieval.flow; - -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentAuthorizeTestConstants; -import org.testng.annotations.DataProvider; - -/** - * Data Provider for Consent Executor Tests. - */ -public class ConsentExtensionDataProvider { - - @DataProvider(name = "PaymentConsentDataDataProvider") - Object[][] getPaymentConsentDataDataProvider() { - - return new Object[][]{ - {ConsentAuthorizeTestConstants.PAYMENT_INITIATION}, - {ConsentAuthorizeTestConstants.INTERNATIONAL_PAYMENT_INITIATION} - }; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/VRPConsentRetrievalStepTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/VRPConsentRetrievalStepTest.java deleted file mode 100644 index f8b11e02..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/VRPConsentRetrievalStepTest.java +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.authorize.vrp.retrieval.flow; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.impl.DefaultConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentAuthorizeTestConstants; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestUtils; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.ParseException; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** - * Test class for Consent Retrieval Step. - */ -@PrepareForTest({OpenBankingConfigParser.class, OpenBankingConfigParser.class, ConsentServiceUtil.class}) -@PowerMockIgnore({"com.wso2.openbanking.accelerator.consent.extensions.common.*", "net.minidev.*", - "jdk.internal.reflect.*"}) -public class VRPConsentRetrievalStepTest extends PowerMockTestCase { - - private static DefaultConsentRetrievalStep defaultConsentRetrievalStep; - @Mock - private static ConsentData consentDataMock; - @Mock - private static ConsentResource consentResourceMock; - @Mock - private static AuthorizationResource authorizationResourceMock; - @Mock - ConsentFile consentFileMock; - @Mock - ConsentCoreServiceImpl consentCoreServiceMock; - @Mock - OpenBankingConfigParser openBankingConfigParserMock; - - private static Map configMap; - ArrayList authResources; - - @BeforeClass - public void initClass() { - - MockitoAnnotations.initMocks(this); - - defaultConsentRetrievalStep = new DefaultConsentRetrievalStep(); - consentDataMock = Mockito.mock(ConsentData.class); - consentResourceMock = Mockito.mock(ConsentResource.class); - authorizationResourceMock = Mockito.mock(AuthorizationResource.class); - consentFileMock = Mockito.mock(ConsentFile.class); - consentCoreServiceMock = Mockito.mock(ConsentCoreServiceImpl.class); - - configMap = new HashMap<>(); - openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - authResources = new ArrayList(); - } - - @BeforeMethod - public void initMethod() throws ReflectiveOperationException { - - //to execute util class initialization - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - ConsentExtensionTestUtils.injectEnvironmentVariable("CARBON_HOME", "."); - - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.doReturn("jdbc/WSO2OB_DB").when(openBankingConfigParserMock).getDataSourceName(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - Mockito.doReturn(configMap).when(openBankingConfigParserMock).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void testGetConsentDataSetForNonRegulatory() { - - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(false).when(consentDataMock).isRegulatory(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertTrue(jsonObject.isEmpty()); - } - - @Test - public void testConsentRetrievalWithEmptyConsentData() { - - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - String errorMsg = (String) jsonObject.get(ConsentExtensionConstants.IS_ERROR); - Assert.assertFalse(errorMsg.contains(ErrorConstants.REQUEST_OBJ_EXTRACT_ERROR)); - } - - @Test - public void testConsentRetrievalWithNonJWTRequestObject() { - - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - Mockito.doReturn("request=qwertyuijhbvbn").when(consentDataMock).getSpQueryParams(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - String errorMsg = (String) jsonObject.get(ConsentExtensionConstants.IS_ERROR); - Assert.assertTrue(errorMsg.contains(ErrorConstants.REQUEST_OBJ_NOT_SIGNED)); - } - - @Test - public void testConsentRetrievalWithInvalidRequestObject() { - - String request = "request=" + ConsentAuthorizeTestConstants.INVALID_REQUEST_OBJECT; - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - Mockito.doReturn(request).when(consentDataMock).getSpQueryParams(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - String errorMsg = (String) jsonObject.get(ConsentExtensionConstants.IS_ERROR); - Assert.assertTrue(errorMsg.contains(ErrorConstants.NOT_JSON_PAYLOAD)); - } - - @Test - public void testConsentRetrievalWithValidRequestObject() throws ConsentManagementException { - - String request = "request=" + ConsentAuthorizeTestConstants.VALID_REQUEST_OBJECT; - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - Mockito.doReturn(request).when(consentDataMock).getSpQueryParams(); - - Mockito.doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(consentResourceMock).getCurrentStatus(); - Mockito.doReturn(ConsentExtensionConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VALID_INITIATION_OBJECT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(consentResourceMock).when(consentCoreServiceMock) - .getConsent(Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(authorizationResourceMock) - .getAuthorizationStatus(); - authResources.add(authorizationResourceMock); - Mockito.doReturn(authResources).when(consentCoreServiceMock) - .searchAuthorizations(Mockito.anyString()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - } - - @Test - public void testGetConsentDataSetForAccounts() { - - Mockito.doReturn(ConsentExtensionConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VALID_INITIATION_OBJECT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray accountConsentData = defaultConsentRetrievalStep.getConsentDataSet(consentResourceMock); - Assert.assertNotNull(accountConsentData); - } - - - - @Test(dataProvider = "PaymentConsentDataDataProvider", dataProviderClass = ConsentExtensionDataProvider.class) - public void testGetConsentDataSetForPayments(String paymentReceipt) throws ConsentManagementException, - ParseException { - - Mockito.doReturn(configMap).when(openBankingConfigParserMock).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - Mockito.doReturn(ConsentExtensionConstants.PAYMENTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(paymentReceipt).when(consentResourceMock).getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CREATED_TIME).when(consentResourceMock) - .getCreatedTime(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray paymentConsentData = defaultConsentRetrievalStep.getConsentDataSet(consentResourceMock); - Assert.assertNotNull(paymentConsentData); - } - - @Test - public void testGetConsentDataSetForFilePayments() { - - Mockito.doReturn(configMap).when(openBankingConfigParserMock).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - Mockito.doReturn(ConsentExtensionConstants.PAYMENTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CREATED_TIME).when(consentResourceMock) - .getCreatedTime(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray paymentConsentData = defaultConsentRetrievalStep.getConsentDataSet(consentResourceMock); - Assert.assertNotNull(paymentConsentData); - } - - - @Test - public void testGetConsentDataSetForCOF() { - - Mockito.doReturn(ConsentExtensionConstants.FUNDSCONFIRMATIONS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.COF_RECEIPT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray cofConsentData = defaultConsentRetrievalStep.getConsentDataSet(consentResourceMock); - Assert.assertNotNull(cofConsentData); - } - - @Test - public void testGetConsentDataSetForVRP() { - - Mockito.doReturn(ConsentExtensionConstants.VRP).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VRP_INITIATION).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray cofConsentData = defaultConsentRetrievalStep.getConsentDataSet(consentResourceMock); - Assert.assertNotNull(cofConsentData); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/VRPConsentRetrievalUtilTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/VRPConsentRetrievalUtilTest.java deleted file mode 100644 index 9ad35bf6..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authorize/vrp/retrieval/flow/VRPConsentRetrievalUtilTest.java +++ /dev/null @@ -1,333 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authorize.vrp.retrieval.flow; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.impl.DefaultConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.utils.ConsentRetrievalUtil; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentAuthorizeTestConstants; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestUtils; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - - -import static com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentAuthorizeTestConstants.VRP_WITHOUT_DATA; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.testng.Assert.assertTrue; - -/** - * Test class for consentRetrievalUtil. - */ -@PowerMockIgnore({"com.wso2.openbanking.accelerator.consent.extensions.common.*", "net.minidev.*", - "jdk.internal.reflect.*"}) -@PrepareForTest({OpenBankingConfigParser.class, OpenBankingConfigParser.class, ConsentServiceUtil.class}) -public class VRPConsentRetrievalUtilTest extends PowerMockTestCase { - - @InjectMocks - private final DefaultConsentRetrievalStep defaultConsentRetrievalStep = new DefaultConsentRetrievalStep(); - private final ConsentRetrievalUtil consentRetrievalUtil = new ConsentRetrievalUtil(); - @Mock - private static ConsentData consentDataMock; - @Mock - private static ConsentResource consentResourceMock; - @Mock - private static AuthorizationResource authorizationResourceMock; - @Mock - ConsentCoreServiceImpl consentCoreServiceMock; - @Mock - OpenBankingConfigParser openBankingConfigParser; - @Mock - OpenBankingConfigParser openBankingConfigParse; - private static Map configMap; - ArrayList authResources; - - - @BeforeClass - public void initClass() { - MockitoAnnotations.initMocks(this); - consentDataMock = mock(ConsentData.class); - consentResourceMock = mock(ConsentResource.class); - authorizationResourceMock = mock(AuthorizationResource.class); - consentCoreServiceMock = mock(ConsentCoreServiceImpl.class); - configMap = new HashMap<>(); - authResources = new ArrayList(); - } - - @BeforeClass - public void setUp() throws ReflectiveOperationException { - - MockitoAnnotations.initMocks(this); - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - ConsentExtensionTestUtils.injectEnvironmentVariable("CARBON_HOME", "."); - - consentResourceMock = mock(ConsentResource.class); - - } - - @BeforeMethod - public void initMethod() { - openBankingConfigParser = mock(OpenBankingConfigParser.class); - doReturn(configMap).when(openBankingConfigParser).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParser); - - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void testGetConsentDataSetForNonRegulatory() { - - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(false).when(consentDataMock).isRegulatory(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - assertTrue(jsonObject.isEmpty()); - } - - @Test - public void testConsentRetrievalWithEmptyConsentData() { - - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - String errorMsg = (String) jsonObject.get(ConsentExtensionConstants.IS_ERROR); - Assert.assertFalse(errorMsg.contains(ErrorConstants.REQUEST_OBJ_EXTRACT_ERROR)); - } - - @Test - public void testConsentRetrievalWithNonJWTRequestObject() { - - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - Mockito.doReturn("request=qwertyuijhbvbn").when(consentDataMock).getSpQueryParams(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - String errorMsg = (String) jsonObject.get(ConsentExtensionConstants.IS_ERROR); - Assert.assertTrue(errorMsg.contains(ErrorConstants.REQUEST_OBJ_NOT_SIGNED)); - } - - @Test - public void testConsentRetrievalWithInvalidRequestObject() { - - String request = "request=" + ConsentAuthorizeTestConstants.INVALID_REQUEST_OBJECT; - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - Mockito.doReturn(request).when(consentDataMock).getSpQueryParams(); - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - String errorMsg = (String) jsonObject.get(ConsentExtensionConstants.IS_ERROR); - assertTrue(errorMsg.contains(ErrorConstants.NOT_JSON_PAYLOAD)); - } - - @Test - public void testConsentRetrievalWithValidRequestObject() throws ConsentManagementException { - - String request = "request=" + ConsentAuthorizeTestConstants.VALID_REQUEST_OBJECT; - JSONObject jsonObject = new JSONObject(); - Mockito.doReturn(true).when(consentDataMock).isRegulatory(); - Mockito.doReturn(request).when(consentDataMock).getSpQueryParams(); - - Mockito.doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(consentResourceMock).getCurrentStatus(); - Mockito.doReturn(ConsentExtensionConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VALID_INITIATION_OBJECT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(consentResourceMock).when(consentCoreServiceMock) - .getConsent(Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(authorizationResourceMock) - .getAuthorizationStatus(); - authResources.add(authorizationResourceMock); - Mockito.doReturn(authResources).when(consentCoreServiceMock) - .searchAuthorizations(Mockito.anyString()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - defaultConsentRetrievalStep.execute(consentDataMock, jsonObject); - Assert.assertNotNull(jsonObject.get(ConsentExtensionConstants.IS_ERROR)); - } - - @Test - public void testGetConsentDataSetForAccounts() { - Mockito.doReturn(ConsentExtensionConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VALID_INITIATION_OBJECT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray accountConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(accountConsentData); - } - - @Test(dataProvider = "PaymentConsentDataDataProvider", dataProviderClass = ConsentExtensionDataProvider.class) - public void testGetConsentDataSetForPayments(String paymentReceipt) { - - Mockito.doReturn(configMap).when(openBankingConfigParse).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParse); - - Mockito.doReturn(ConsentExtensionConstants.PAYMENTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(paymentReceipt).when(consentResourceMock).getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.CREATED_TIME).when(consentResourceMock) - .getCreatedTime(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray paymentConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(paymentConsentData); - } - - @Test - public void testGetConsentDataSetForCOF() { - - Mockito.doReturn(ConsentExtensionConstants.FUNDSCONFIRMATIONS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.COF_RECEIPT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray cofConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(cofConsentData); - } - - @Test - public void testGetConsentDataSetForVRPData() { - - Mockito.doReturn(ConsentExtensionConstants.VRP).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VRP_INITIATION).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - JSONArray vrpConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(vrpConsentData); - } - - @Test(expectedExceptions = ConsentException.class) - public void testConsentDataWithInvalidJson() { - String invalidJsonString = "Invalid JSON String"; - Mockito.when(consentResourceMock.getReceipt()).thenReturn(invalidJsonString); - - JSONArray consentDataJSON = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(consentDataJSON); - } - - @Test(expectedExceptions = ConsentException.class) - public void testGetConsentDataSetForVRPDataParameter() { - - Mockito.doReturn(ConsentExtensionConstants.VRP).when(consentResourceMock).getConsentType(); - Mockito.doReturn(VRP_WITHOUT_DATA).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - JSONArray vrpConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(vrpConsentData); - } - - @Test(expectedExceptions = ConsentException.class) - public void testGetConsentDataSetForVRPDataWithoutControlParameters() { - - Mockito.doReturn(ConsentExtensionConstants.VRP).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.VRP_WITHOUT_CONTROLPARAMETERS).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray vrpConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(vrpConsentData); - } - - @Test(expectedExceptions = ConsentException.class) - public void testGetConsentDataSetForAccount() { - - Mockito.doReturn(ConsentExtensionConstants.ACCOUNTS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.INVALID_INITIATION_OBJECT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray accountConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(accountConsentData); - } - - @Test(expectedExceptions = ConsentException.class) - public void testGetConsentDataSetForCOFs() { - - Mockito.doReturn(ConsentExtensionConstants.FUNDSCONFIRMATIONS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.INVALID_COF_RECEIPT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray cofConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(cofConsentData); - } - - @Test(expectedExceptions = ConsentException.class) - public void testGetConsentDataSetForCOFNull() { - - Mockito.doReturn(ConsentExtensionConstants.FUNDSCONFIRMATIONS).when(consentResourceMock).getConsentType(); - Mockito.doReturn(ConsentAuthorizeTestConstants.NULL_COF_RECEIPT).when(consentResourceMock) - .getReceipt(); - Mockito.doReturn(ConsentAuthorizeTestConstants.AWAITING_AUTH_STATUS).when(consentResourceMock) - .getCurrentStatus(); - - JSONArray cofConsentData = ConsentRetrievalUtil.getConsentData(consentResourceMock); - Assert.assertNotNull(cofConsentData); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/AuthServletTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/AuthServletTest.java deleted file mode 100644 index 3fe0b66a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/AuthServletTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.utils.AuthServletTestConstants; -import org.json.JSONObject; -import org.junit.Assert; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -/** - * Test class for OB Auth Servlet. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -public class AuthServletTest { - - OBDefaultAuthServletImpl obAuthServlet; - @Mock - HttpServletRequest httpServletRequestMock; - @Mock - ResourceBundle resourceBundle; - - @BeforeClass - public void initClass() { - - MockitoAnnotations.initMocks(this); - - obAuthServlet = new OBDefaultAuthServletImpl(); - httpServletRequestMock = Mockito.mock(HttpServletRequest.class); - resourceBundle = Mockito.mock(ResourceBundle.class); - } - - @Test - public void testUpdateRequestAttributeForAccounts() { - - JSONObject accountObj = new JSONObject(AuthServletTestConstants.ACCOUNT_DATA); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - accountObj, resourceBundle); - - Assert.assertFalse(requestAttributes.isEmpty()); - Assert.assertTrue(requestAttributes.containsKey(ConsentExtensionConstants.DATA_REQUESTED)); - } - - @Test - public void testUpdateRequestAttributeForCOF() { - - JSONObject cofObj = new JSONObject(AuthServletTestConstants.COF_DATA); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - cofObj, resourceBundle); - - Assert.assertFalse(requestAttributes.isEmpty()); - Assert.assertTrue(requestAttributes.containsKey(ConsentExtensionConstants.DATA_REQUESTED)); - } - - @Test - public void testUpdateRequestAttributeForPayments() { - - JSONObject paymentObj = new JSONObject(AuthServletTestConstants.PAYMENT_DATA); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.doReturn(session).when(httpServletRequestMock).getSession(); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - paymentObj, resourceBundle); - - Assert.assertFalse(requestAttributes.isEmpty()); - Assert.assertTrue(requestAttributes.containsKey(ConsentExtensionConstants.DATA_REQUESTED)); - } - - @Test - public void testUpdateRequestAttributeForPaymentsWithoutDebtorAccInPayload() { - - JSONObject paymentObj = new JSONObject(AuthServletTestConstants.PAYMENT_DATA_WITHOUT_DEBTOR_ACC); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.doReturn(session).when(httpServletRequestMock).getSession(); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - paymentObj, resourceBundle); - - Assert.assertTrue(requestAttributes.isEmpty()); - Assert.assertFalse(requestAttributes.containsKey(ConsentExtensionConstants.DATA_REQUESTED)); - } - - @Test - public void testUpdateRequestAttributeForVRP() { - - JSONObject paymentObj = new JSONObject(AuthServletTestConstants.VRP_DATA); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.doReturn(session).when(httpServletRequestMock).getSession(); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - paymentObj, resourceBundle); - - Assert.assertFalse(requestAttributes.isEmpty()); - Assert.assertTrue(requestAttributes.containsKey(ConsentExtensionConstants.DATA_REQUESTED)); - } - - @Test - public void testUpdateRequestAttributeForVRPWithoutDebtorAcc() { - - JSONObject paymentObj = new JSONObject(AuthServletTestConstants.VRP_DATA_WITHOUT_DEBTOR_ACC); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.doReturn(session).when(httpServletRequestMock).getSession(); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - paymentObj, resourceBundle); - - Assert.assertFalse(requestAttributes.isEmpty()); - Assert.assertTrue(requestAttributes.containsKey(ConsentExtensionConstants.DATA_REQUESTED)); - } - - @Test - public void testUpdateRequestAttributeForNonExistingType() { - - JSONObject object = new JSONObject(AuthServletTestConstants.JSON_WITH_TYPE); - - Map requestAttributes = obAuthServlet.updateRequestAttribute(httpServletRequestMock, - object, resourceBundle); - - Assert.assertTrue(requestAttributes.isEmpty()); - } - - @Test - public void testUpdateConsentData() { - - String param = "Test_parameter"; - Mockito.doReturn(param).when(httpServletRequestMock).getParameter(Mockito.anyString()); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.doReturn(session).when(httpServletRequestMock).getSession(); - - Map consentData = obAuthServlet.updateConsentData(httpServletRequestMock); - Assert.assertFalse(consentData.isEmpty()); - Assert.assertTrue(consentData.containsKey(ConsentExtensionConstants.ACCOUNT_IDS)); - Assert.assertFalse(consentData.containsKey(ConsentExtensionConstants.PAYMENT_ACCOUNT)); - Assert.assertFalse(consentData.containsKey(ConsentExtensionConstants.COF_ACCOUNT)); - } - - @Test - public void testUpdateConsentMetaData() { - - Map consentMetadata = obAuthServlet.updateConsentMetaData(httpServletRequestMock); - - Assert.assertTrue(consentMetadata.isEmpty()); - } - - @Test - public void testUpdateSessionAttribute() { - - Map sessionAttributes = obAuthServlet.updateSessionAttribute(httpServletRequestMock, - new JSONObject(), resourceBundle); - - Assert.assertTrue(sessionAttributes.isEmpty()); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ConsentMgrAuthServletImplTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ConsentMgrAuthServletImplTest.java deleted file mode 100644 index 9427bea5..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/authservlet/impl/ConsentMgrAuthServletImplTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl; - -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Constants; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.model.OBAuthServletInterface; -import org.json.JSONArray; -import org.json.JSONObject; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -/** - * Test for consent management auth servlet implementation. - */ -public class ConsentMgrAuthServletImplTest { - OBAuthServletInterface uut = new ConsentMgrAuthServletImpl(); - - @Test - public void testUpdateRequestAttribute() { - JSONArray scopeArray = new JSONArray(); - scopeArray.put("scope1"); - scopeArray.put("scope2"); - scopeArray.put("scope3"); - - JSONObject dataset = new JSONObject(); - dataset.put("openid_scopes", scopeArray); - - // mock - HttpServletRequest servletRequestMock = Mockito.mock(HttpServletRequest.class); - HttpSession httpSessionMock = Mockito.mock(HttpSession.class); - ResourceBundle resourceBundleMock = Mockito.mock(ResourceBundle.class); - - // when - Mockito.when(httpSessionMock.getAttribute("displayScopes")).thenReturn(true); - Mockito.when(servletRequestMock.getSession()).thenReturn(httpSessionMock); - - // assert - Map returnMap = uut - .updateRequestAttribute(servletRequestMock, dataset, resourceBundleMock); - Assert.assertNotNull(returnMap); - List oidScopes = (List) returnMap.get(Constants.OIDC_SCOPES); - Assert.assertTrue(oidScopes.contains("scope1")); - Assert.assertTrue(oidScopes.contains("scope2")); - Assert.assertTrue(oidScopes.contains("scope3")); - } - - @Test(description = "when displayScopes is false, OIDCScopes should be null") - public void testUpdateRequestAttributeWithFalseDisplayScope() { - // mock - HttpServletRequest servletRequestMock = Mockito.mock(HttpServletRequest.class); - HttpSession httpSessionMock = Mockito.mock(HttpSession.class); - ResourceBundle resourceBundleMock = Mockito.mock(ResourceBundle.class); - - // when - Mockito.when(httpSessionMock.getAttribute("displayScopes")).thenReturn(false); - Mockito.when(servletRequestMock.getSession()).thenReturn(httpSessionMock); - - // assert - Map returnMap = uut - .updateRequestAttribute(servletRequestMock, null, resourceBundleMock); - Assert.assertNotNull(returnMap); - Assert.assertNull(returnMap.get(Constants.OIDC_SCOPES)); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticatorTests.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticatorTests.java deleted file mode 100644 index 9a84e09e..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/ciba/authenticator/CIBAPushAuthenticatorTests.java +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.ciba.authenticator; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentCache; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.identity.cache.IdentityCache; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import net.minidev.json.JSONObject; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationContextCache; -import org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig; -import org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationRequest; -import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -/** - * Test class for CIBAPushAuthenticator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({SessionDataCache.class, AuthenticationContextCache.class, ConsentExtensionUtils.class, - ConsentCache.class, ConsentData.class, IdentityCommonUtil.class, FrameworkUtils.class, - AuthenticationContext.class, SequenceConfig.class, ServiceProvider.class, ApplicationConfig.class, - AuthenticationRequest.class, SessionDataCacheEntry.class, IdentityCache.class, OAuth2Parameters.class, - HttpServletRequest.class, ConsentCoreServiceImpl.class, ConsentExtensionsDataHolder.class, - OpenBankingConfigurationService.class, OpenBankingConfigParser.class}) -public class CIBAPushAuthenticatorTests extends PowerMockTestCase { - - private final String dummyString = "dummyString"; - - @Mock - OpenBankingConfigurationService openBankingConfigurationService; - - @Mock - ConsentExtensionsDataHolder consentExtensionsDataHolder; - - @DataProvider(name = "splitQueryParams") - public Object[][] getSplitQueryParams() { - - String validQueryParms = "key1=val1&key2=val2"; - Map validQueryParamMap = new HashMap<>(); - validQueryParamMap.put("key1", "val1"); - validQueryParamMap.put("key2", "val2"); - - String invalidQueryParams = "key1:val1&key2:val2"; - Map invalidQueryParamMap = new HashMap<>(); - invalidQueryParamMap.put("key1:val1", null); - invalidQueryParamMap.put("key2:val2", null); - - return new Object[][]{ - {validQueryParms, validQueryParamMap}, - {invalidQueryParams, invalidQueryParamMap} - }; - } - - @Test(dataProvider = "splitQueryParams") - public void splitQueryValidQueryTest(String dummyQueryParms, Map queryParamMap) throws Exception { - CIBAPushAuthenticator cibaPushAuthenticator = new CIBAPushAuthenticator(); - Map splitQueryParamMap = cibaPushAuthenticator.splitQuery(dummyQueryParms); - - assertEquals(queryParamMap, splitQueryParamMap); - } - - @Test - public void handlePreConsentTest() { - AuthenticationContext mockAuthnCtxt = spy(AuthenticationContext.class); - - Map params = new HashMap() { - { - put(CIBAPushAuthenticatorConstants.LOGIN_HINT, dummyString); - put(CIBAPushAuthenticatorConstants.REQUEST_OBJECT, dummyString); - put(CIBAPushAuthenticatorConstants.SCOPE, dummyString); - } - }; - - Map queryParamMap = new HashMap<>(); - String[] queryParamArray = new String[1]; - queryParamArray[0] = dummyString; - queryParamMap.put(CIBAPushAuthenticatorConstants.NONCE, queryParamArray); - - SequenceConfig mockSequenceConfig = mock(SequenceConfig.class); - ApplicationConfig mockApplicationConfig = mock(ApplicationConfig.class); - ServiceProvider mockServiceProvider = mock(ServiceProvider.class); - AuthenticationRequest mockAuthenticationRequest = mock(AuthenticationRequest.class); - - when(mockAuthnCtxt.getSequenceConfig()).thenReturn(mockSequenceConfig); - when(mockSequenceConfig.getApplicationConfig()).thenReturn(mockApplicationConfig); - when(mockApplicationConfig.getServiceProvider()).thenReturn(mockServiceProvider); - when(mockServiceProvider.getApplicationName()).thenReturn(dummyString); - when(mockAuthnCtxt.getAuthenticationRequest()).thenReturn(mockAuthenticationRequest); - when(mockAuthenticationRequest.getRequestQueryParams()).thenReturn(queryParamMap); - - int initialSize = mockAuthnCtxt.getEndpointParams().size(); - CIBAPushAuthenticator cibaPushAuthenticator = new CIBAPushAuthenticator(); - cibaPushAuthenticator.handlePreConsent(mockAuthnCtxt, params); - int finalSize = mockAuthnCtxt.getEndpointParams().size(); - - assertTrue(finalSize > initialSize); - } - - @Test - public void setMetadataTest() throws Exception { - CIBAPushAuthenticator mockAuthenticator = spy(new CIBAPushAuthenticatorMock()); - - mockStatic(SessionDataCache.class); - mockStatic(AuthenticationContextCache.class); - mockStatic(FrameworkUtils.class); - - SessionDataCache sessionDataCache = mock(SessionDataCache.class); - SessionDataCacheEntry sessionDataCacheEntry = mock(SessionDataCacheEntry.class); - AuthenticationContextCache authenticationContextCache = mock(AuthenticationContextCache.class); - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - when(httpServletRequest.getParameter(CIBAPushAuthenticatorConstants.BINDING_MESSAGE)).thenReturn(dummyString); - - when(mockAuthenticator.splitQuery(Mockito.anyString())).thenReturn(new HashMap<>()); - when(FrameworkUtils.getQueryStringWithFrameworkContextId - (Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(dummyString); - when(SessionDataCache.getInstance()).thenReturn(sessionDataCache); - when(sessionDataCache.getValueFromCache(Mockito.anyObject())).thenReturn(sessionDataCacheEntry); - when(AuthenticationContextCache.getInstance()).thenReturn(authenticationContextCache); - - doNothing().when(mockAuthenticator).handlePreConsent(Mockito.anyObject(), Mockito.anyObject()); - doNothing().when(authenticationContextCache).addToCache(Mockito.anyObject(), Mockito.anyObject()); - JSONObject jsonObject = new JSONObject(); - jsonObject.put(dummyString, dummyString); - doReturn(jsonObject).when(mockAuthenticator).retrieveConsent(Mockito.anyObject(), - Mockito.anyObject(), Mockito.anyString()); - - assertNotNull(mockAuthenticator.getAdditionalInfo(httpServletRequest, httpServletResponse, - dummyString)); - } - - @Test - public void retrieveConsentTest() throws OpenBankingException { - - CIBAPushAuthenticator mockAuthenticator = spy(new CIBAPushAuthenticatorMock()); - Map configs = new HashMap<>(); - configs.put("Consent.PreserveConsentLink", "true"); - mockStatic(ConsentExtensionUtils.class); - mockStatic(ConsentCoreServiceImpl.class); - mockStatic(ConsentExtensionsDataHolder.class); - - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.doReturn(configs).when(openBankingConfigParserMock).getConfiguration(); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - mockStatic(ConsentCache.class); - mockStatic(ConsentData.class); - mockStatic(IdentityCommonUtil.class); - - ConsentData consentData = mock(ConsentData.class); - IdentityCache identityCache = mock(IdentityCache.class); - SessionDataCacheEntry cacheEntry = mock(SessionDataCacheEntry.class); - OAuth2Parameters oAuth2Parameters = mock(OAuth2Parameters.class); - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - IdentityCommonUtil identityCommonUtil = mock(IdentityCommonUtil.class); - - when(ConsentCache.getInstance()).thenReturn(identityCache); - when(ConsentCache.getCacheEntryFromSessionDataKey(Mockito.anyString())).thenReturn(cacheEntry); - when(cacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Parameters); - when(oAuth2Parameters.getRedirectURI()).thenReturn(dummyString); - when(oAuth2Parameters.getClientId()).thenReturn(dummyString); - when(oAuth2Parameters.getState()).thenReturn(dummyString); - when(identityCommonUtil.getRegulatoryFromSPMetaData(dummyString)).thenReturn(true); - when(consentData.getType()).thenReturn(dummyString); - when(consentData.getApplication()).thenReturn(dummyString); - - Map sensitiveDataMap = new HashMap<>(); - Map headers = new HashMap<>(); - sensitiveDataMap.put(CIBAPushAuthenticatorConstants.IS_ERROR, "false"); - sensitiveDataMap.put(CIBAPushAuthenticatorConstants.LOGGED_IN_USER, dummyString); - sensitiveDataMap.put(CIBAPushAuthenticatorConstants.SP_QUERY_PARAMS, dummyString); - sensitiveDataMap.put(CIBAPushAuthenticatorConstants.SCOPE, dummyString); - - when(ConsentExtensionUtils.getSensitiveDataWithConsentKey(Mockito.anyString())).thenReturn(sensitiveDataMap); - when(ConsentExtensionUtils.getHeaders(httpServletRequest)).thenReturn(headers); - when(mockAuthenticator.createConsentData(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyObject())).thenReturn(consentData); - - doNothing().when(consentData).setSensitiveDataMap(Mockito.anyObject()); - doNothing().when(consentData).setRedirectURI(Mockito.anyObject()); - doNothing().when(consentData).setRegulatory(Mockito.anyObject()); - doNothing().when(mockAuthenticator).executeRetrieval(Mockito.anyObject(), Mockito.anyObject()); - - assertNotNull(mockAuthenticator.retrieveConsent(Mockito.anyObject(), Mockito.anyObject(), Mockito.anyString())); - - } - -} - -class CIBAPushAuthenticatorMock extends CIBAPushAuthenticator { - - @Override - protected AuthenticationContext getAutenticationContext(String sessionDataKey) { - - return mock(AuthenticationContext.class); - } - - @Override - protected ConsentData createConsentData(String sessionDataKey, String loggedInUser, String spQueryParams, - String scopeString, String app, HttpServletRequest request) { - return mock(ConsentData.class); - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidatorTests.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidatorTests.java deleted file mode 100644 index f6afd117..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/common/idempotency/IdempotencyValidatorTests.java +++ /dev/null @@ -1,303 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.common.idempotency; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -/** - * Test class for IdempotencyValidator. - */ -@PrepareForTest({OpenBankingConfigParser.class, ConsentExtensionsDataHolder.class}) -@PowerMockIgnore("jdk.internal.reflect.*") -public class IdempotencyValidatorTests extends PowerMockTestCase { - - @Mock - private ConsentManageData consentManageData; - private ConsentCoreServiceImpl consentCoreServiceImpl; - private ArrayList consentIdList; - private Map attributeList; - private String consentId; - private Map configs; - private Map headers; - private static final String CLIENT_ID = "testClientId"; - - private static final String PAYLOAD = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"Yes\",\n" + - " \"Initiation\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"165.88\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"UK.OBIE.SortCodeAccountNumber\",\n" + - " \"Identification\": \"08080021325698\",\n" + - " \"Name\": \"ACME Inc\",\n" + - " \"SecondaryIdentification\": \"0002\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"FRESCO-101\",\n" + - " \"Unstructured\": \"Internal ops code 5120101\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " }\n" + - " }\n" + - "}"; - - private static final String DIFFERENT_PAYLOAD = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"No\",\n" + - " \"Initiation\": {\n" + - " \"InstructionIdentification\": \"ACME413\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"165.88\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"UK.OBIE.SortCodeAccountNumber\",\n" + - " \"Identification\": \"08080021325698\",\n" + - " \"Name\": \"ACME Inc\",\n" + - " \"SecondaryIdentification\": \"0002\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"FRESCO-101\",\n" + - " \"Unstructured\": \"Internal ops code 5120101\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " }\n" + - " }\n" + - "}"; - - - @BeforeClass - public void beforeTest() { - configs = new HashMap<>(); - - headers = new HashMap<>(); - headers.put(IdempotencyConstants.X_IDEMPOTENCY_KEY, "123456"); - headers.put(IdempotencyConstants.CONTENT_TYPE_TAG, "application/json"); - - consentManageData = Mockito.mock(ConsentManageData.class); - consentCoreServiceImpl = Mockito.mock(ConsentCoreServiceImpl.class); - - consentId = UUID.randomUUID().toString(); - consentIdList = new ArrayList<>(); - consentIdList.add(consentId); - - attributeList = new HashMap<>(); - attributeList.put(consentId, "123456"); - } - - @BeforeMethod - public void beforeMethod() { - OpenBankingConfigParser openBankingConfigParserMock = PowerMockito.mock(OpenBankingConfigParser.class); - Mockito.doReturn(configs).when(openBankingConfigParserMock).getConfiguration(); - Mockito.doReturn(true).when(openBankingConfigParserMock).isIdempotencyValidationEnabled(); - Mockito.doReturn("1").when(openBankingConfigParserMock).getIdempotencyAllowedTime(); - ConsentExtensionsDataHolder consentExtensionsDataHolderMock = PowerMockito - .mock(ConsentExtensionsDataHolder.class); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - PowerMockito.mockStatic(ConsentExtensionsDataHolder.class); - PowerMockito.when(ConsentExtensionsDataHolder.getInstance()).thenReturn(consentExtensionsDataHolderMock); - PowerMockito.when(consentExtensionsDataHolderMock.getConsentCoreService()).thenReturn(consentCoreServiceImpl); - } - - @Test - public void testValidateIdempotency() throws ConsentManagementException, IdempotencyValidationException { - OffsetDateTime offsetDateTime = OffsetDateTime.now(); - - Mockito.doReturn(consentIdList).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(getConsent(offsetDateTime.toEpochSecond())).when(consentCoreServiceImpl) - .getDetailedConsent(Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - IdempotencyValidationResult result = new IdempotencyValidator().validateIdempotency(consentManageData); - - Assert.assertTrue(result.isIdempotent()); - Assert.assertTrue(result.isValid()); - Assert.assertNotNull(result.getConsent()); - Assert.assertEquals(consentId, result.getConsentId()); - } - - @Test(expectedExceptions = IdempotencyValidationException.class) - public void testValidateIdempotencyForRequestsWithoutPayload() throws ConsentManagementException, - IdempotencyValidationException { - OffsetDateTime offsetDateTime = OffsetDateTime.now(); - - Mockito.doReturn(attributeList).when(consentCoreServiceImpl).getConsentAttributesByName(Mockito.anyString()); - Mockito.doReturn(getConsent(offsetDateTime.toEpochSecond())).when(consentCoreServiceImpl) - .getDetailedConsent(Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn("{}").when(consentManageData).getPayload(); - Mockito.doReturn("{}").when(consentManageData).getPayload(); - Mockito.doReturn("/payments/".concat(consentId)).when(consentManageData).getRequestPath(); - new IdempotencyValidator().validateIdempotency(consentManageData); - } - - @Test - public void testValidateIdempotencyWithoutIdempotencyKeyValue() throws IdempotencyValidationException { - - Mockito.doReturn(new HashMap<>()).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - IdempotencyValidationResult result = new IdempotencyValidator().validateIdempotency(consentManageData); - - Assert.assertFalse(result.isIdempotent()); - } - - @Test - public void testValidateIdempotencyWithoutRequest() throws IdempotencyValidationException { - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn("").when(consentManageData).getPayload(); - IdempotencyValidationResult result = new IdempotencyValidator().validateIdempotency(consentManageData); - - Assert.assertFalse(result.isIdempotent()); - } - - @Test - public void testValidateIdempotencyRetrievingAttributesWithException() - throws ConsentManagementException, IdempotencyValidationException { - - Mockito.doThrow(ConsentManagementException.class).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - IdempotencyValidationResult result = new IdempotencyValidator().validateIdempotency(consentManageData); - - Assert.assertFalse(result.isIdempotent()); - } - - @Test - public void testValidateIdempotencyWithoutAttribute() - throws ConsentManagementException, IdempotencyValidationException { - - Mockito.doReturn(new ArrayList<>()).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - IdempotencyValidationResult result = new IdempotencyValidator().validateIdempotency(consentManageData); - - Assert.assertFalse(result.isIdempotent()); - } - - @Test(expectedExceptions = IdempotencyValidationException.class) - public void testValidateIdempotencyWithNullConsentRequest() - throws ConsentManagementException, IdempotencyValidationException { - - Mockito.doReturn(consentIdList).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - Mockito.doReturn(null).when(consentCoreServiceImpl).getDetailedConsent(Mockito.anyString()); - new IdempotencyValidator().validateIdempotency(consentManageData); - } - - @Test(expectedExceptions = IdempotencyValidationException.class) - public void testValidateIdempotencyWithNonMatchingClientId() - throws ConsentManagementException, IdempotencyValidationException { - - Mockito.doReturn(consentIdList).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn("sampleClientID").when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - Mockito.doReturn(null).when(consentCoreServiceImpl).getDetailedConsent(Mockito.anyString()); - new IdempotencyValidator().validateIdempotency(consentManageData); - } - - @Test(expectedExceptions = IdempotencyValidationException.class) - public void testValidateIdempotencyAfterAllowedTime() - throws ConsentManagementException, IdempotencyValidationException { - - OffsetDateTime offsetDateTime = OffsetDateTime.now().minusHours(2); - - Mockito.doReturn(consentIdList).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(getConsent(offsetDateTime.toEpochSecond())).when(consentCoreServiceImpl) - .getDetailedConsent(Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(PAYLOAD).when(consentManageData).getPayload(); - new IdempotencyValidator().validateIdempotency(consentManageData); - } - - @Test(expectedExceptions = IdempotencyValidationException.class) - public void testValidateIdempotencyWithNonMatchingPayload() - throws ConsentManagementException, IdempotencyValidationException { - - OffsetDateTime offsetDateTime = OffsetDateTime.now(); - - Mockito.doReturn(consentIdList).when(consentCoreServiceImpl) - .getConsentIdByConsentAttributeNameAndValue(Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(getConsent(offsetDateTime.toEpochSecond())).when(consentCoreServiceImpl) - .getDetailedConsent(Mockito.anyString()); - Mockito.doReturn(headers).when(consentManageData).getHeaders(); - Mockito.doReturn(CLIENT_ID).when(consentManageData).getClientId(); - Mockito.doReturn(DIFFERENT_PAYLOAD).when(consentManageData).getPayload(); - new IdempotencyValidator().validateIdempotency(consentManageData); - - } - - private DetailedConsentResource getConsent(long createdTime) { - DetailedConsentResource consent = new DetailedConsentResource(); - consent.setConsentID(consentId); - consent.setReceipt(PAYLOAD); - consent.setClientID(CLIENT_ID); - consent.setCreatedTime(createdTime); - return consent; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/ConsentAmendmentHistoryEventExecutorTests.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/ConsentAmendmentHistoryEventExecutorTests.java deleted file mode 100644 index 0eb78099..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/event/executors/ConsentAmendmentHistoryEventExecutorTests.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.event.executors; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -/** - * Test class for ConsentAmendmentHistoryEventExecutor. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class, ConsentExtensionsDataHolder.class}) -public class ConsentAmendmentHistoryEventExecutorTests extends PowerMockTestCase { - - private static ByteArrayOutputStream outContent; - private static Logger logger = null; - private static PrintStream printStream; - private ConsentCoreServiceImpl consentCoreServiceImpl; - private String sampleConsentID; - - @BeforeClass - public void initTest() { - - consentCoreServiceImpl = Mockito.mock(ConsentCoreServiceImpl.class); - } - - @BeforeClass - public void beforeTests() { - - sampleConsentID = UUID.randomUUID().toString(); - outContent = new ByteArrayOutputStream(); - printStream = new PrintStream(outContent); - System.setOut(printStream); - logger = LogManager.getLogger(ConsentAmendmentHistoryEventExecutorTests.class); - } - - @Test - public void testProcessEventSuccess() throws Exception { - - ConsentAmendmentHistoryEventExecutor consentAmendmentHistoryEventExecutorSpy = - Mockito.spy(new ConsentAmendmentHistoryEventExecutor()); - - outContent.reset(); - - OpenBankingConfigParser openBankingConfigParserMock = mock(OpenBankingConfigParser.class); - ConsentExtensionsDataHolder consentExtensionsDataHolderMock = mock(ConsentExtensionsDataHolder.class); - mockStatic(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - when(openBankingConfigParserMock.isConsentAmendmentHistoryEnabled()).thenReturn(true); - - mockStatic(ConsentExtensionsDataHolder.class); - when(ConsentExtensionsDataHolder.getInstance()).thenReturn(consentExtensionsDataHolderMock); - when(consentExtensionsDataHolderMock.getConsentCoreService()).thenReturn(consentCoreServiceImpl); - - Map eventData = new HashMap<>(); - eventData.put("Reason", "Amended by the user"); - eventData.put("ConsentId", sampleConsentID); - eventData.put("ClientId", "dummyClientId"); - - Map consentDataMap = new HashMap<>(); - consentDataMap.put("ConsentResource", new DetailedConsentResource()); - consentDataMap.put("ConsentAmendmentHistory", new DetailedConsentResource()); - consentDataMap.put("ConsentAmendmentTime", System.currentTimeMillis()); - eventData.put("ConsentDataMap", consentDataMap); - - OBEvent obEvent = new OBEvent("amended", eventData); - Mockito.doReturn(true).when(consentCoreServiceImpl) - .storeConsentAmendmentHistory(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject()); - consentAmendmentHistoryEventExecutorSpy.processEvent(obEvent); - - Assert.assertTrue(outContent.toString().contains("Consent Amendment History of consentID:")); - } - - @Test - public void testProcessEventFailure() throws ConsentManagementException { - - ConsentAmendmentHistoryEventExecutor consentAmendmentHistoryEventExecutorSpy = - Mockito.spy(new ConsentAmendmentHistoryEventExecutor()); - - outContent.reset(); - - OpenBankingConfigParser openBankingConfigParserMock = mock(OpenBankingConfigParser.class); - ConsentExtensionsDataHolder consentExtensionsDataHolderMock = mock(ConsentExtensionsDataHolder.class); - mockStatic(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - when(openBankingConfigParserMock.isConsentAmendmentHistoryEnabled()).thenReturn(true); - - mockStatic(ConsentExtensionsDataHolder.class); - when(ConsentExtensionsDataHolder.getInstance()).thenReturn(consentExtensionsDataHolderMock); - when(consentExtensionsDataHolderMock.getConsentCoreService()).thenReturn(consentCoreServiceImpl); - - Map eventData = new HashMap<>(); - eventData.put("Reason", "Amended by the user"); - eventData.put("ConsentId", sampleConsentID); - eventData.put("ClientId", "dummyClientId"); - - Map consentDataMap = new HashMap<>(); - consentDataMap.put("ConsentResource", new DetailedConsentResource()); - consentDataMap.put("ConsentAmendmentHistory", new DetailedConsentResource()); - consentDataMap.put("ConsentAmendmentTime", System.currentTimeMillis()); - eventData.put("ConsentDataMap", consentDataMap); - - OBEvent obEvent = new OBEvent("amended", eventData); - Mockito.doThrow(ConsentManagementException.class).when(consentCoreServiceImpl) - .storeConsentAmendmentHistory(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject()); - consentAmendmentHistoryEventExecutorSpy.processEvent(obEvent); - - Assert.assertTrue(outContent.toString().contains("An error occurred while persisting consent amendment " + - "history data.")); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPConsentHandlerTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPConsentHandlerTest.java deleted file mode 100644 index 48e8ab94..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPConsentHandlerTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.vrp; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.internal.ConsentExtensionsDataHolder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.impl.VRPConsentRequestHandler; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestUtils; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test class for VRPConsentRequestHandler. - */ -@PowerMockIgnore({"jdk.internal.reflect.*", -"com.wso2.openbanking.accelerator.consent.extensions.common.*"}) -@PrepareForTest({OpenBankingConfigParser.class, ConsentServiceUtil.class, - ConsentExtensionsDataHolder.class}) -public class VRPConsentHandlerTest extends PowerMockTestCase { - - @InjectMocks - private final VRPConsentRequestHandler handler = new VRPConsentRequestHandler(); - - @Mock - private ConsentManageData consentManageData; - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - @Mock - ConsentCoreServiceImpl consentCoreServiceImpl; - - private static Map configMap; - - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @BeforeClass - public void setUp() throws ReflectiveOperationException { - MockitoAnnotations.initMocks(this); - - configMap = new HashMap<>(); - - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - ConsentExtensionTestUtils.injectEnvironmentVariable("CARBON_HOME", "."); - - consentManageData = mock(ConsentManageData.class); - } - - @BeforeMethod - public void initMethod() { - - openBankingConfigParser = mock(OpenBankingConfigParser.class); - doReturn(configMap).when(openBankingConfigParser).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParser); - - } - - @Test(expectedExceptions = ConsentException.class) - public void testHandleConsentManageGetWithValidConsentIdAndMatchingClientId() throws ConsentManagementException { - UUID consentIdUUID = UUID.randomUUID(); - doReturn("vrp-consent/".concat(consentIdUUID.toString())).when(consentManageData).getRequestPath(); - ConsentResource consent = mock(ConsentResource.class); - doReturn("5678").when(consent).getClientID(); - - consentCoreServiceImpl = mock(ConsentCoreServiceImpl.class); - doReturn(consent).when(consentCoreServiceImpl).getConsent(anyString(), anyBoolean()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceImpl); - - String expectedClientId = "matchingClientId"; - doReturn(expectedClientId).when(consentManageData).getClientId(); - - handler.handleConsentManageGet(consentManageData); - } - - - @Test(expectedExceptions = ConsentException.class) - public void testHandleConsentManageDeleteWithValidConsent() throws ConsentManagementException { - - UUID consentIdUUID = UUID.randomUUID(); - doReturn("vrp-consent/".concat(consentIdUUID.toString())).when(consentManageData).getRequestPath(); - ConsentResource consent = mock(ConsentResource.class); - doReturn("5678").when(consent).getClientID(); - - consentCoreServiceImpl = mock(ConsentCoreServiceImpl.class); - doReturn(consent).when(consentCoreServiceImpl).getConsent(anyString(), anyBoolean()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceImpl); - - String expectedClientId = "6788"; - doReturn(expectedClientId).when(consentManageData).getClientId(); - - handler.handleConsentManageDelete(consentManageData); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPConsentRequestValidatorTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPConsentRequestValidatorTest.java deleted file mode 100644 index 12ec982a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPConsentRequestValidatorTest.java +++ /dev/null @@ -1,2009 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.manage.vrp; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.manage.validator.VRPConsentRequestValidator; -import com.wso2.openbanking.accelerator.consent.extensions.util.ConsentManageUtil; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestUtils; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.JSONValue; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.mock; -import static org.testng.Assert.assertTrue; -import static org.testng.AssertJUnit.assertFalse; - -/** - * Test class for VRPConsentRequestValidator. - */ -@PowerMockIgnore({"jdk.internal.reflect.*"}) -@PrepareForTest({OpenBankingConfigParser.class}) -public class VRPConsentRequestValidatorTest extends PowerMockTestCase { - - @Mock - private ConsentManageData consentManageData; - - @Mock - OpenBankingConfigParser openBankingConfigParser; - - private static Map configMap; - - @BeforeClass - public void setUp() throws ReflectiveOperationException { - MockitoAnnotations.initMocks(this); - - configMap = new HashMap<>(); - //to execute util class initialization - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - ConsentExtensionTestUtils.injectEnvironmentVariable("CARBON_HOME", "."); - - consentManageData = mock(ConsentManageData.class); - } - - @BeforeMethod - public void initMethod() { - - openBankingConfigParser = mock(OpenBankingConfigParser.class); - Mockito.doReturn(configMap).when(openBankingConfigParser).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParser); - } - - @Test - public void testVrpPayload() { - - VRPConsentRequestValidator handler = new VRPConsentRequestValidator(); - JSONObject response = handler.validateVRPPayload("payload"); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, response.get(ConsentExtensionConstants.ERRORS)); - - } - - @Test - public void testVrpEmptyPayload() { - - JSONObject response = VRPConsentRequestValidator.validateVRPPayload(""); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, response.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiation() { - - String initiationPayloads = VRPTestConstants.vrpInitiationPayloadWithoutData; - JSONObject response = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, response.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpControlParameters() { - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CONTROL_PARAMETERS; - JSONObject response = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testVrpEmptyData() { - String initiationPayloads = VRPTestConstants.vrpInitiationPayloadWithStringData; - JSONObject response = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, response.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpDataIsJsonObject() { - String initiationPayloads = VRPTestConstants.vrpInitiationPayloadWithOutJsonObject; - JSONObject response = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, response.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutControlParameterKey() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CONTROL_PARAMETERS; - JSONObject result = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result2 = VRPConsentRequestValidator.validateMaximumIndividualAmount((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result3 = VRPConsentRequestValidator. - validateMaximumIndividualAmountCurrency((JSONObject) JSONValue.parse(initiationPayloads)); - - Assert.assertTrue(true); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyWithCurrencyKeys() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Currency", "USD"); - - JSONArray jsonArray = new JSONArray(); - jsonArray.add(jsonObject); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(jsonArray, "Currency", String.class); - Assert.assertTrue((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testValidateAmountCurrencyWithInvalidKey() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("InvalidKey", "USD"); - - JSONArray jsonArray = new JSONArray(); - jsonArray.add(jsonObject); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(jsonArray, "Currency", String.class); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutPeriodicLimitCurrency() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_PERIODIC_LIMIT_CURRENCY; - JSONObject results = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result = VRPConsentRequestValidator.validateCurrencyPeriodicLimit((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) results.get(ConsentExtensionConstants.IS_VALID)); - assertTrue(true); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result.get(ConsentExtensionConstants.ERRORS)); - - } - - @Test - public void testVrpInitiationPayloadWithoutPeriodicLimitAmount() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_PERIODIC_LIMIT_AMOUNT; - JSONObject results = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) results.get(ConsentExtensionConstants.IS_VALID)); - assertTrue(true); - - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithInvalidValue() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Currency", 123); - - JSONArray jsonArray = new JSONArray(); - jsonArray.add(jsonObject); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(jsonArray, "Currency", String.class); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithInvalidKey() { - - JSONArray testData = new JSONArray(); - JSONObject limit = new JSONObject(); - limit.put("anotherKey", "USD"); - testData.add(limit); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData, "currency", String.class); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testValidationFailureForCurrency() { - - JSONObject limit = new JSONObject(); - limit.put(ConsentExtensionConstants.CURRENCY, 123); - - JSONArray periodicLimits = new JSONArray(); - periodicLimits.add(limit); - - JSONObject result = VRPConsentRequestValidator.validateAmountCurrencyPeriodicLimits(periodicLimits, - ConsentExtensionConstants.CURRENCY, String.class); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("The value of 'Currency' is not of type String", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithCurrencyKey() { - - // Test case 2: Invalid currency key (empty value) - JSONArray testData2 = new JSONArray(); - JSONObject limit2 = new JSONObject(); - limit2.put("currency", ""); - testData2.add(limit2); - - JSONObject result2 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData2, "0", String.class); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - JSONArray testData3 = new JSONArray(); - - JSONObject result3 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData3, "0", String.class); - Assert.assertTrue((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - - JSONObject result4 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(null, "currency", String.class); - Assert.assertFalse((boolean) result4.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result4.get(ConsentExtensionConstants.ERRORS)); - - - } - - @Test - public void testVrpInitiationPayloadWithoutRisk() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_RISK; - JSONObject result = VRPConsentRequestValidator.validateConsentRisk((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testIsValidObjectDebAcc() { - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - - // Test case 3: Non-JSONObject value - String nonJsonObject = "not a JSONObject"; - Assert.assertFalse(VRPConsentRequestValidator.isValidJSONObject(nonJsonObject), - ConsentExtensionConstants.IS_VALID); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - - // Test case 4: Null value - Object nullValue = null; - Assert.assertFalse(VRPConsentRequestValidator.isValidJSONObject(nullValue), - ConsentExtensionConstants.IS_VALID); - - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testIsValidObjectDebtorAcc() { - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - - // Test case 3: Non-JSONObject value - String nonJsonObject = "not a JSONObject"; - Assert.assertFalse(VRPConsentRequestValidator.isValidJSONObject(nonJsonObject), - ConsentExtensionConstants.IS_VALID); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - // Test case 4: Null value - Object nullValue = null; - Assert.assertFalse(VRPConsentRequestValidator.isValidJSONObject(nullValue), - ConsentExtensionConstants.IS_VALID); - } - - @Test - public void testVrpInitiationPayloadWithoutDebtorAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutCreditAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_CREDITOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateConsentInitiation((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutCreditorAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_CREDITOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutSchemeName() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT_SCHEME_NAME; - JSONObject result = ConsentManageUtil.validateDebtorAccount((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateDebtorAccount_InvalidSchemeName() { - JSONObject debtorAccount = new JSONObject(); - debtorAccount.put(ConsentExtensionConstants.SCHEME_NAME, ""); - debtorAccount.put(ConsentExtensionConstants.IDENTIFICATION, "ValidIdentification"); - debtorAccount.put(ConsentExtensionConstants.NAME, "ValidName"); - - JSONObject result = ConsentManageUtil.validateDebtorAccount(debtorAccount); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(result.get(ConsentExtensionConstants.ERRORS), - ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME); - } - - @Test - public void testVrpInitiationPayloadWithoutIdentification() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT_IDENTIFICATION; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testVrpInitiationPayloadCreditorAccWithoutSchemeName() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_CREDITOR_ACCOUNT_SCHEME_NAME; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload((JSONValue. - parse(initiationPayloads))); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - - } - - @Test - public void testVrpInitiationPayloadCreditorAccWithoutIdentification() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_CREDITOR_ACCOUNT_IDENTIFICATION; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - - } - - @Test - public void testValidatePeriodicLimits() { - - JSONObject invalidLimit = new JSONObject(); - invalidLimit.put("someKey", "someValue"); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodicLimits(invalidLimit); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_LIMITS, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithValidKey() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Currency", "USD"); - - JSONArray jsonArray = new JSONArray(); - jsonArray.add(jsonObject); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(jsonArray, "Currency", String.class); - Assert.assertTrue(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithInvalidKeys() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("InvalidKey", "USD"); - - JSONArray jsonArray = new JSONArray(); - jsonArray.add(jsonObject); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(jsonArray, "Currency", String.class); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithEmptyArray() { - - JSONArray jsonArray = new JSONArray(); - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(jsonArray, "Currency", String.class); - - Assert.assertTrue(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(null, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimitsWithNullArray() { - - JSONObject result = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(null, "Currency", String.class); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("parameter passed in is null", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testVrpPeriodicTypeJsonArray() { - - Object invalidObject = "Not a JSONArray"; - boolean isValidInvalidObject = VRPConsentRequestValidator.isValidJSONArray(invalidObject); - - // Test case 2: Missing period type key - JSONObject missingKeyObject = new JSONObject(); - JSONObject result2 = VRPConsentRequestValidator.validatePeriodType(missingKeyObject); - Assert.assertFalse(Boolean.parseBoolean(result2.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_TYPE, result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 3: Null period type - JSONObject nullPeriodTypeObject = new JSONObject(); - nullPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_TYPE, null); - JSONObject result3 = VRPConsentRequestValidator.validatePeriodType(nullPeriodTypeObject); - Assert.assertFalse(Boolean.parseBoolean(result3.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_TYPE, result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 4: Empty period type - JSONObject emptyPeriodTypeObject = new JSONObject(); - emptyPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_TYPE, ""); - JSONObject result4 = VRPConsentRequestValidator.validatePeriodType(emptyPeriodTypeObject); - Assert.assertFalse(Boolean.parseBoolean(result4.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_TYPE, result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 5: Invalid period type - JSONObject invalidPeriodTypeObject = new JSONObject(); - invalidPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_TYPE, "InvalidType"); - JSONObject result5 = VRPConsentRequestValidator.validatePeriodType(invalidPeriodTypeObject); - Assert.assertFalse(Boolean.parseBoolean(result5.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_TYPE, result2.get(ConsentExtensionConstants.ERRORS)); - - Assert.assertFalse(isValidInvalidObject, ConsentExtensionConstants.IS_VALID); - } - - @Test - public void testDataContainsKey_InitiationNotPresent() { - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_INITIATION; - JSONObject result = VRPConsentRequestValidator.validateConsentInitiation((JSONObject) JSONValue. - parse(initiationPayloads)); - - boolean containsKey = result.containsKey(ConsentExtensionConstants.INITIATION); - Assert.assertFalse(containsKey, ConsentExtensionConstants.IS_VALID); - Assert.assertEquals("Missing mandatory parameter Initiation in the payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testDataContainsKey_ControlParametersNotPresent() { - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CONTROL_PARAMETERS; - JSONObject result = VRPConsentRequestValidator.validateConsentControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean containsKey = result.containsKey(ConsentExtensionConstants.CONTROL_PARAMETERS); - Assert.assertFalse(containsKey, ConsentExtensionConstants.IS_VALID); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_CONTROL_PARAMETER, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadMaximumIndividualAmountNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_EMPTY_MAX_INDIVIDUAL_AMOUNT; - String date = VRPTestConstants.METADATA_VRP_WITHOUT_VALID_FROM_DATE; - String date2 = VRPTestConstants.METADATA_VRP_WITHOUT_VALID_TO_DATE; - - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmount((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject results = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result2 = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(date)); - JSONObject result3 = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(date)); - - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - - - boolean isValidNonJSONObjects = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObjects, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) results.get(ConsentExtensionConstants.IS_VALID)); - - boolean obj2 = VRPConsentRequestValidator.isValidJSONObject(date); - Assert.assertFalse(obj2, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - - boolean obj3 = VRPConsentRequestValidator.isValidJSONObject(date2); - Assert.assertFalse(obj3, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testVrpInitiationPayloadDebAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_DEBTOR_ACC; - JSONObject result = VRPConsentRequestValidator.validateConsentInitiation((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadDebAccs() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_DEB_ACC; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Parameter 'debtor account' passed in is null, empty, or not a JSONObject", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationMax() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_EMPTY_MAX_INDIVIDUAL_AMOUNT; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR, result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadValidateDebAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_DEB_ACC; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadCreditorAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CREDITOR_ACC; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadCreditorAccs() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CREDITOR_ACC; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - - Assert.assertFalse(isValidNonJSONObject); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Parameter 'creditor account' passed in is null, empty, or not a JSONObject", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadDebtorAccs() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_DEB_ACC; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - - Assert.assertFalse(isValidNonJSONObject); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - - Assert.assertEquals("Parameter 'debtor account' passed in is null, empty, or not a JSONObject", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testIsValidObject_NegativeScenarios() { - - String nonJSONObject = "Not a JSONObject"; - JSONObject validInitiationObject = new JSONObject(); - - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(nonJSONObject); - boolean isValidNonJSONObject1 = VRPConsentRequestValidator.isValidJSONObject(validInitiationObject); - Assert.assertFalse(isValidNonJSONObject1, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testVrpInitiationPayloadInitiationNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_EMPTY_INITIATION; - JSONObject result = VRPConsentRequestValidator.validateConsentInitiation((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Parameter 'initiation' passed in is null, empty, or not a JSONObject", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadMaximumIndividualNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_INVALID_MAX_INDIVIDUAL_AMOUNT; - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmount((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadCurrencyNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_INVALID_MAX_INDIVIDUAL_AMOUNT; - JSONObject result = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadControlParametersNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_EMPTY_CONTROL_PARAMETERS; - JSONObject result = VRPConsentRequestValidator.validateConsentControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Parameter 'control parameters' passed in is null, empty, or not a JSONObject", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutDate() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_INVALID_VALID_FROM_DATETIME; - JSONObject result = VRPConsentRequestValidator.validateParameterDateTime((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_VALID_TO_DATE_TIME, - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testVrpInitiationPayloadWithoutValidToDate() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_VALID_TO_DATE; - JSONObject result = VRPConsentRequestValidator.validateParameterDateTime((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_VALID_TO_DATE_TIME, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadMaximumIndividualAmountIsJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_EMPTY_MAX_INDIVIDUAL_AMOUNT; - JSONObject result = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testIsValidDateTimeObjectNegativeScenarios() { - // Test case 1: Empty string - String emptyString = ""; - JSONObject resultEmptyString = VRPConsentRequestValidator.isValidDateTimeObject(emptyString); - Assert.assertFalse((boolean) resultEmptyString.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_DATE_TIME_FORMAT, - resultEmptyString.get(ConsentExtensionConstants.ERRORS)); - - // Test case 2: Null value - Object nullValue = null; - boolean resultNullValue = false; - Assert.assertFalse(resultNullValue, "Expected false for a null value"); - - // Test case 3: Non-string value - Object nonStringValue = 123; // Assuming an integer, but could be any non-string type - JSONObject resultNonStringValue = VRPConsentRequestValidator.isValidDateTimeObject(nonStringValue); - Assert.assertFalse((boolean) resultNonStringValue.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_DATE_TIME_FORMAT, - resultNonStringValue.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimits() { - - // Test case 2: Key is null - JSONArray testData2 = new JSONArray(); - JSONObject result2 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData2, null, String.class); - Assert.assertTrue((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 3: ParentObj is null - JSONObject result3 = VRPConsentRequestValidator.validateAmountCurrencyPeriodicLimits(null, "0", String.class); - Assert.assertTrue((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 4: Key is not present in parentObj - JSONArray testData4 = new JSONArray(); - JSONObject result4 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData4, "nonExistentKey", String.class); - Assert.assertTrue((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 5: Value is an empty String - JSONArray testData5 = new JSONArray(); - testData5.add(""); - JSONObject result5 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData5, "0", String.class); - Assert.assertTrue((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result2.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testValidateKeyAndNonEmptyStringValue() { - - // Test case 2: Key is null - JSONArray testData2 = new JSONArray(); - JSONObject result2 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData2, null, String.class); - Assert.assertTrue((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 3: ParentObj is null - JSONObject result3 = VRPConsentRequestValidator.validateAmountCurrencyPeriodicLimits(null, "0", String.class); - Assert.assertFalse((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result3.get(ConsentExtensionConstants.ERRORS)); - - // Test case 4: Key is not present in parentObj - JSONArray testData4 = new JSONArray(); - JSONObject result4 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData4, "nonExistentKey", String.class); - Assert.assertTrue((boolean) result4.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result4.get(ConsentExtensionConstants.ERRORS)); - - // Test case 5: Value is an empty String - JSONArray testData5 = new JSONArray(); - testData5.add(""); - JSONObject result5 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData5, "0", String.class); - Assert.assertTrue((boolean) result5.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result5.get(ConsentExtensionConstants.ERRORS)); - - - // Test case 7: Value is not a String - JSONArray testData7 = new JSONArray(); - testData7.add(123); // Assuming the value should be a String, but it's an integer in this case - JSONObject result7 = VRPConsentRequestValidator. - validateAmountCurrencyPeriodicLimits(testData7, "0", String.class); - Assert.assertTrue((boolean) result7.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(null, - result7.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidPeriodicLimitsFormat() { - - JSONObject controlParameters = new JSONObject(); - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, "invalid-format"); - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodicLimits(controlParameters); - - Assert.assertFalse((boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.INVALID_PARAMETER_PERIODIC_LIMITS, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidMaxAmountFormat() { - - JSONObject controlParameters = new JSONObject(); - controlParameters.put(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT, "invalid-format"); - JSONObject validationResult = VRPConsentRequestValidator.validateMaximumIndividualAmount(controlParameters); - - Assert.assertFalse((boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Parameter 'maximum individual amount' passed in is null, empty, or not a JSONObject", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidMaxAmountFormatPeriodicLimit() { - - JSONObject controlParameters = new JSONObject(); - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, "invalid-format"); - JSONObject validationResults = VRPConsentRequestValidator. - validateControlParameters(controlParameters); - JSONObject validationResult = VRPConsentRequestValidator. - validateMaximumIndividualAmountCurrency(controlParameters); - - Assert.assertFalse((boolean) validationResults.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidMaxAmountFormats() { - - JSONObject controlParameters = new JSONObject(); - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, "invalid-format"); - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodicLimits(controlParameters); - - Assert.assertFalse((boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.INVALID_PARAMETER_PERIODIC_LIMITS, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidJSONObject() { - - String invalidJSONObject = "not a JSON object"; - boolean isValid = VRPConsentRequestValidator.isValidJSONObject(invalidJSONObject); - - Assert.assertFalse(isValid); - } - - @Test - public void testEmptyJSONObject() { - JSONObject emptyJSONObject = new JSONObject(); - - boolean isValid = VRPConsentRequestValidator.isValidJSONObject(emptyJSONObject); - Assert.assertFalse(isValid); - } - - @Test - public void testInvalidPeriodicAlignment() { - // Arrange - JSONObject invalidLimit = new JSONObject(); - invalidLimit.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "InvalidAlignment"); - - JSONObject isValid = VRPConsentRequestValidator.validatePeriodicLimits(invalidLimit); - - Assert.assertFalse((boolean) isValid.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_LIMITS, - isValid.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidDateTimeRange() { - - JSONObject controlParameters = new JSONObject(); - controlParameters.put(ConsentExtensionConstants.VALID_FROM_DATE_TIME, "2023-01-01T00:00:00Z"); - controlParameters.put(ConsentExtensionConstants.VALID_TO_DATE_TIME, "2022-01-01T00:00:00Z"); - - boolean hasValidFromDate = controlParameters.containsKey(ConsentExtensionConstants.VALID_FROM_DATE_TIME); - boolean hasValidToDate = controlParameters.containsKey(ConsentExtensionConstants.VALID_TO_DATE_TIME); - - - assertTrue(hasValidFromDate && hasValidToDate); - } - - @Test - public void testVrpInitiationPayloadWithoutControlParameterss() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CURRENCY; - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmount((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Missing mandatory parameter Maximum Individual Amount", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutPeriodicType() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_PERIODIC_TYPE; - JSONObject result = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result2 = VRPConsentRequestValidator.validatePeriodicLimits((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result3 = VRPConsentRequestValidator.validatePeriodType((JSONObject) JSONValue. - parse(initiationPayloads)); - - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testValidationFailureForNullCurrencyKey() { - - JSONArray periodicLimits = new JSONArray(); - periodicLimits.add(new JSONObject()); - - JSONObject result = VRPConsentRequestValidator.validateAmountCurrencyPeriodicLimits(periodicLimits, - ConsentExtensionConstants.CURRENCY, String.class); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutPeriodicTypeCurrency() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_PERIODIC_TYPE_CURRENCY; - JSONObject result = VRPConsentRequestValidator.validateControlParameters((JSONObject) JSONValue. - parse(initiationPayloads)); - JSONObject result2 = VRPConsentRequestValidator.validatePeriodicLimits((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testValidationFailureForMissingKey() { - - JSONArray periodicLimits = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("otherKey", "someValue"); - periodicLimits.add(jsonObject); - - - JSONObject result = VRPConsentRequestValidator.validateAmountCurrencyPeriodicLimits(periodicLimits, - ConsentExtensionConstants.CURRENCY, String.class); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testValidateControlParameters() { - - JSONObject controlParameters = new JSONObject(); - - JSONObject result = VRPConsentRequestValidator.validateControlParameters(controlParameters); - - assertTrue(result.containsKey(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testValidateAmountCurrencyPeriodicLimits_Invalid() { - - JSONObject controlParameters = new JSONObject(); - JSONArray periodicLimits = new JSONArray(); - - JSONObject invalidPeriodicLimit = new JSONObject(); - periodicLimits.add(invalidPeriodicLimit); - - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimits); - - JSONObject result = VRPConsentRequestValidator.validateCurrencyPeriodicLimit(controlParameters); - - assertTrue(result.containsKey(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimit_WithErrors() { - - JSONObject controlParameters = new JSONObject(); - JSONArray periodicLimits = new JSONArray(); - - JSONObject invalidPeriodicLimit = new JSONObject(); - periodicLimits.add(invalidPeriodicLimit); - - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimits); - - JSONObject periodicLimitType = VRPConsentRequestValidator. - validateCurrencyPeriodicLimit(controlParameters); - - Assert.assertFalse((boolean) periodicLimitType.get(ConsentExtensionConstants.IS_VALID)); - - assertTrue(periodicLimitType.containsKey(ConsentExtensionConstants.ERRORS)); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - periodicLimitType.get(ConsentExtensionConstants.ERRORS)); - - } - - @Test - public void testValidateConsentRisk_ValidRequest() { - - JSONObject validRequest = new JSONObject(); - JSONObject data = new JSONObject(); - data.put("someKey", "someValue"); - - validRequest.put(ConsentExtensionConstants.DATA, data); - validRequest.put(ConsentExtensionConstants.RISK, new JSONObject()); - - JSONObject validationResponse = VRPConsentRequestValidator.validateConsentRisk(validRequest); - - assertTrue((boolean) validationResponse.get(ConsentExtensionConstants.IS_VALID)); - } - - @Test - public void testValidateConsentControlParameters_InvalidControlParameters() { - - JSONObject invalidControlParametersObject = new JSONObject(); - invalidControlParametersObject.put("invalidParam", "value"); - - JSONObject invalidDataObject = new JSONObject(); - invalidDataObject.put(ConsentExtensionConstants.CONTROL_PARAMETERS, invalidControlParametersObject); - - - JSONObject invalidRequestObject = new JSONObject(); - invalidRequestObject.put(ConsentExtensionConstants.DATA, invalidDataObject); - - JSONObject validationResult = VRPConsentRequestValidator.validateConsentControlParameters(invalidRequestObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_MAXIMUM_INDIVIDUAL_AMOUNT, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicLimits_Valid() { - - JSONObject controlParametersObject = new JSONObject(); - JSONArray periodicLimitsArray = new JSONArray(); - - JSONObject periodicLimit1 = new JSONObject(); - periodicLimit1.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "ALIGNMENT1"); - periodicLimit1.put(ConsentExtensionConstants.PERIOD_TYPE, "TYPE1"); - - JSONObject periodicLimit2 = new JSONObject(); - periodicLimit2.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "ALIGNMENT2"); - periodicLimit2.put(ConsentExtensionConstants.PERIOD_TYPE, "TYPE2"); - - periodicLimitsArray.add(periodicLimit1); - periodicLimitsArray.add(periodicLimit2); - - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimitsArray); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodicLimits(controlParametersObject); - JSONObject validationResults = VRPConsentRequestValidator.validatePeriodAlignment(controlParametersObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertFalse(Boolean.parseBoolean(validationResults.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_ALIGNMENT, - validationResults.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicLimits_InvalidFormat() { - JSONObject controlParametersObject = new JSONObject(); - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, "InvalidFormat"); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodicLimits(controlParametersObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.INVALID_PARAMETER_PERIODIC_LIMITS, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicLimits_MissingPeriodLimits() { - - JSONObject controlParametersObject = new JSONObject(); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodicLimits(controlParametersObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_LIMITS, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimit_Valid() { - - JSONObject controlParametersObject = new JSONObject(); - JSONArray periodicLimitsArray = new JSONArray(); - - JSONObject periodicLimit1 = new JSONObject(); - periodicLimit1.put(ConsentExtensionConstants.CURRENCY, "USD"); - - JSONObject periodicLimit2 = new JSONObject(); - periodicLimit2.put(ConsentExtensionConstants.CURRENCY, "EUR"); - - periodicLimitsArray.add(periodicLimit1); - periodicLimitsArray.add(periodicLimit2); - - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimitsArray); - - JSONObject validationResult = VRPConsentRequestValidator. - validateAmountPeriodicLimit(controlParametersObject); - - assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Amount' is not present in payload", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimit_MissingCurrency() { - JSONObject controlParametersObject = new JSONObject(); - JSONArray periodicLimitsArray = new JSONArray(); - - JSONObject periodicLimit1 = new JSONObject(); - periodicLimitsArray.add(periodicLimit1); - - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimitsArray); - - JSONObject validationResult = VRPConsentRequestValidator. - validateAmountPeriodicLimit(controlParametersObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Amount' is not present in payload", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicType_Valid() { - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_TYPE, ConsentExtensionConstants.MONTH); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodType(periodicLimitObject); - - Assert.assertTrue(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - } - - @Test - public void testValidatePeriodicType_InvalidType() { - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_TYPE, "InvalidType"); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodType(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.INVALID_PERIOD_TYPE, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicType_MissingType() { - - JSONObject periodicLimitObject = new JSONObject(); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodType(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_TYPE, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicType_EmptyType() { - - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_TYPE, ""); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodType(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Value of period type is empty or the value passed in is not a string", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicType_NullType() { - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_TYPE, null); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodType(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Value of period type is empty or the value passed in is not a string", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testYourMethod_ValidPeriodicType() { - - JSONObject controlParameters = new JSONObject(); - JSONArray periodicLimits = new JSONArray(); - - JSONObject periodicLimit = new JSONObject(); - periodicLimit.put(ConsentExtensionConstants.PERIOD_TYPE, ConsentExtensionConstants.MONTH); - periodicLimits.add(periodicLimit); - - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimits); - - JSONObject result = VRPConsentRequestValidator.validateAmountPeriodicLimit(controlParameters); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Amount' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - - } - - @Test - public void testYourMethod_InvalidPeriodicType() { - - JSONObject controlParameters = new JSONObject(); - JSONArray periodicLimits = new JSONArray(); - - JSONObject periodicLimit = new JSONObject(); - periodicLimit.put(ConsentExtensionConstants.PERIOD_TYPE, "InvalidType"); - periodicLimits.add(periodicLimit); - - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimits); - - JSONObject result = VRPConsentRequestValidator.validateCurrencyPeriodicLimit(controlParameters); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testYourMethod_MissingPeriodicType() { - - JSONObject controlParameters = new JSONObject(); - - JSONObject result = VRPConsentRequestValidator.validatePeriodicLimits(controlParameters); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_LIMITS, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutDebtorAccs() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateConsentInitiation((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRisk_InvalidRequest() { - JSONObject requestBody = new JSONObject(); - JSONObject data = new JSONObject(); - data.put("key1", "value1"); - requestBody.put("data", data); - - JSONObject validationResult = VRPConsentRequestValidator.validateVRPPayload(requestBody); - JSONObject validationResults = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertFalse(Boolean.parseBoolean(validationResults.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - validationResults.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutDeAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadDAccWithoutSchemeName() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT_SCHEME_NAME; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload((JSONValue. - parse(initiationPayloads))); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_DEBTOR_ACC_SCHEME_NAME, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadDAccWithoutIdentification() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT_IDENTIFICATION; - JSONObject result = VRPConsentRequestValidator.validateVRPPayload(JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_DEBTOR_ACC_IDENTIFICATION, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadDAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_DEBTOR_ACC; - JSONObject result = VRPConsentRequestValidator.validateVRPInitiationPayload((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutDAcc() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_DEBTOR_ACCOUNT; - JSONObject result = VRPConsentRequestValidator.validateConsentInitiation((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_DEBTOR_ACC, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateMaximumIndividualAmountCurrency_InvalidAmountCurrency() { - JSONObject controlParameters = new JSONObject(); - JSONObject maximumIndividualAmount = new JSONObject(); - maximumIndividualAmount.put("InvalidKey", "USD"); - controlParameters.put(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT, maximumIndividualAmount); - - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency(controlParameters); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateMaximumIndividualAmountCurrency_MissingCurrency() { - - JSONObject controlParameters = new JSONObject(); - JSONObject maximumIndividualAmount = new JSONObject(); - - controlParameters.put(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT, maximumIndividualAmount); - - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency(controlParameters); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodAlignmentInvalidValue() { - - JSONObject limit = new JSONObject(); - limit.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "InvalidValue"); - - JSONObject result = VRPConsentRequestValidator.validatePeriodAlignment(limit); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(result.get(ConsentExtensionConstants.ERRORS), - ErrorConstants.INVALID_PERIOD_ALIGNMENT); - } - - @Test - public void testValidatePeriodAlignmentMissingKey() { - - JSONObject limit = new JSONObject(); - - JSONObject result = VRPConsentRequestValidator.validatePeriodAlignment(limit); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(result.get(ConsentExtensionConstants.ERRORS), - ErrorConstants.MISSING_PERIOD_ALIGNMENT); - } - - - @Test - public void testValidatePeriodicAlignment_EmptyType() { - - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, ""); - - JSONObject result = VRPConsentRequestValidator.validatePeriodType(periodicLimitObject); - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_TYPE, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicAlignment() { - // Test case 1: Valid periodic type - JSONObject validLimitObject = new JSONObject(); - validLimitObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, ConsentExtensionConstants.DAY); - JSONObject result1 = VRPConsentRequestValidator.validatePeriodAlignment(validLimitObject); - Assert.assertFalse((boolean) result1.get(ConsentExtensionConstants.IS_VALID)); - - // Test case 2: Missing period type key - JSONObject missingKeyObject = new JSONObject(); - JSONObject result2 = VRPConsentRequestValidator.validatePeriodAlignment(missingKeyObject); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - - // Test case 3: Null period type - JSONObject nullPeriodTypeObject = new JSONObject(); - nullPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, null); - JSONObject result3 = VRPConsentRequestValidator.validatePeriodAlignment(nullPeriodTypeObject); - Assert.assertFalse((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - - // Test case 4: Empty period type - JSONObject emptyPeriodTypeObject = new JSONObject(); - emptyPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, ""); - JSONObject result4 = VRPConsentRequestValidator.validatePeriodAlignment(emptyPeriodTypeObject); - Assert.assertFalse((boolean) result4.get(ConsentExtensionConstants.IS_VALID)); - - // Test case 5: Invalid period type - JSONObject invalidPeriodTypeObject = new JSONObject(); - invalidPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "InvalidType"); - JSONObject result5 = VRPConsentRequestValidator.validatePeriodAlignment(invalidPeriodTypeObject); - Assert.assertFalse((boolean) result5.get(ConsentExtensionConstants.IS_VALID)); - - Assert.assertEquals("Invalid value for period alignment in PeriodicLimits", - result5.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicAlignment_Valid() { - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, ConsentExtensionConstants.CONSENT); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodAlignment(periodicLimitObject); - - Assert.assertTrue(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - - } - - @Test - public void testValidatePeriodicAlignment_InvalidType() { - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "InvalidType"); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodAlignment(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Invalid value for period alignment in PeriodicLimits", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicAlignment_MissingType() { - - JSONObject periodicLimitObject = new JSONObject(); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodAlignment(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.MISSING_PERIOD_ALIGNMENT, - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicAlignments_EmptyType() { - - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, ""); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodAlignment(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Value of periodic alignment is empty or the value passed in is not a string", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicAlignment_NullType() { - JSONObject periodicLimitObject = new JSONObject(); - periodicLimitObject.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, null); - - JSONObject validationResult = VRPConsentRequestValidator.validatePeriodAlignment(periodicLimitObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Value of periodic alignment is empty or the value passed in is not a string", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimits_Valid() { - - JSONObject controlParametersObject = new JSONObject(); - JSONArray periodicLimitsArray = new JSONArray(); - - JSONObject periodicLimit1 = new JSONObject(); - periodicLimit1.put(ConsentExtensionConstants.CURRENCY, "USD"); - - JSONObject periodicLimit2 = new JSONObject(); - periodicLimit2.put(ConsentExtensionConstants.CURRENCY, "EUR"); - - periodicLimitsArray.add(periodicLimit1); - periodicLimitsArray.add(periodicLimit2); - - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimitsArray); - - JSONObject validationResult = VRPConsentRequestValidator. - validateCurrencyPeriodicLimit(controlParametersObject); - - - } - - - @Test - public void testValidateAmountCurrencyPeriodicLimitS_MissingCurrency() { - JSONObject controlParametersObject = new JSONObject(); - JSONArray periodicLimitsArray = new JSONArray(); - - JSONObject periodicLimit1 = new JSONObject(); - periodicLimitsArray.add(periodicLimit1); - - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimitsArray); - - JSONObject validationResult = VRPConsentRequestValidator. - validateCurrencyPeriodicLimit(controlParametersObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - validationResult.get(ConsentExtensionConstants.ERRORS)); - - } - - @Test - public void testYourMethod_ValidPeriodicTypes() { - - JSONObject controlParameters = new JSONObject(); - JSONArray periodicLimits = new JSONArray(); - - JSONObject periodicLimit = new JSONObject(); - periodicLimit.put(ConsentExtensionConstants.PERIOD_TYPE, ConsentExtensionConstants.MONTH); - periodicLimits.add(periodicLimit); - - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimits); - - JSONObject result = VRPConsentRequestValidator.validateCurrencyPeriodicLimit(controlParameters); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - } - - @Test - public void testValidateAmountCurrencyPeriodicLimits_MissingCurrency() { - JSONObject controlParametersObject = new JSONObject(); - JSONArray periodicLimitsArray = new JSONArray(); - - JSONObject periodicLimit1 = new JSONObject(); - periodicLimitsArray.add(periodicLimit1); - - controlParametersObject.put(ConsentExtensionConstants.PERIODIC_LIMITS, periodicLimitsArray); - - JSONObject validationResult = VRPConsentRequestValidator. - validateCurrencyPeriodicLimit(controlParametersObject); - - Assert.assertFalse(Boolean.parseBoolean(validationResult.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("Mandatory parameter 'Currency' is not present in payload", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadMaximumIndividualAmountCurrencyNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_EMPTY_MAX_INDIVIDUAL_AMOUNT; - - JSONObject results = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - - boolean isValidNonJSONObjects = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObjects, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) results.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - results.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadMaximumIndividualCurrencyNotJsonObject() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITH_INVALID_MAX_INDIVIDUAL_AMOUNT; - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency((JSONObject) JSONValue. - parse(initiationPayloads)); - boolean isValidNonJSONObject = VRPConsentRequestValidator.isValidJSONObject(initiationPayloads); - Assert.assertFalse(isValidNonJSONObject, (ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testInvalidMaxAmountCurrencyFormatPeriodicLimit() { - - JSONObject controlParameters = new JSONObject(); - controlParameters.put(ConsentExtensionConstants.PERIODIC_LIMITS, "invalid-format"); - JSONObject validationResults = VRPConsentRequestValidator. - validateControlParameters(controlParameters); - JSONObject validationResult = VRPConsentRequestValidator. - validateMaximumIndividualAmountCurrency(controlParameters); - - Assert.assertFalse((boolean) validationResults.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertFalse((boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testInvalidCurrencyKey_MissingKeys() { - - JSONObject maximumIndividualAmount = new JSONObject(); - - JSONObject validationResults = VRPConsentRequestValidator. - validateJsonObjectKey(maximumIndividualAmount, ConsentExtensionConstants.CURRENCY, String.class); - - Assert.assertFalse((Boolean) validationResults.get(ConsentExtensionConstants.IS_VALID)); - - JSONObject parentObj = new JSONObject(); - JSONObject validationResult = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency(parentObj); - - Assert.assertFalse((Boolean) validationResult.get(ConsentExtensionConstants.IS_VALID)); - JSONObject isValid = VRPConsentRequestValidator.validateJsonObjectKey(parentObj, "Currency", String.class); - - Assert.assertFalse((Boolean) isValid.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - validationResult.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutControlParameterCurrency() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CURRENCY; - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testVrpInitiationPayloadWithoutControlParameter() { - - String initiationPayloads = VRPTestConstants.METADATA_VRP_WITHOUT_CURRENCY; - JSONObject result = VRPConsentRequestValidator.validateMaximumIndividualAmountCurrency((JSONObject) JSONValue. - parse(initiationPayloads)); - - Assert.assertFalse((boolean) result.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result.get(ConsentExtensionConstants.ERRORS)); - } - - - @Test - public void testWithEmptyDate() { - - String initiationPayloads = VRPTestConstants.vrpInitiationPayloadWithoutDate; - JSONObject response = VRPConsentRequestValidator.validateParameterDateTime((JSONObject) JSONValue. - parse(initiationPayloads)); - Assert.assertFalse((boolean) response.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals(ErrorConstants.MISSING_VALID_TO_DATE_TIME, response.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRisk() { - - JSONObject requestBody = new JSONObject(); - JSONObject data = new JSONObject(); - JSONObject risk = new JSONObject(); - - data.put(ConsentExtensionConstants.RISK, risk); - requestBody.put(ConsentExtensionConstants.DATA, data); - - JSONObject result = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRiskInvalidFormat() { - JSONObject requestBody = new JSONObject(); - requestBody.put("invalidKey", "invalidValue"); - - JSONObject result = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRiskMissingRiskKey() { - - JSONObject requestBody = new JSONObject(); - JSONObject data = new JSONObject(); - requestBody.put(ConsentExtensionConstants.DATA, data); - - JSONObject result = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRiskWithDataEmpty() { - - JSONObject requestBody = new JSONObject(); - requestBody.put(ConsentExtensionConstants.DATA, new JSONObject()); - - JSONObject result = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRiskWithDataNotPresent() { - - JSONObject requestBody = new JSONObject(); - - JSONObject result = VRPConsentRequestValidator.validateConsentRisk(requestBody); - - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateConsentRiskWithDataNotEmpty() { - JSONObject requestBody = new JSONObject(); - JSONObject data = new JSONObject(); - data.put("someKey", "someValue"); - requestBody.put(ConsentExtensionConstants.DATA, data); - - JSONObject result = VRPConsentRequestValidator.validateConsentRisk(requestBody); - Assert.assertFalse(Boolean.parseBoolean(result.getAsString(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals(ErrorConstants.PAYLOAD_FORMAT_ERROR_RISK, - result.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateCurrencyWithoutAmountKeyAndEmptyString() { - - // Test case 1: parentObj is null - JSONObject result1 = VRPConsentRequestValidator. - validateJsonObjectKey(null, "Currency", String.class); - Assert.assertFalse((boolean) result1.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result1.get(ConsentExtensionConstants.ERRORS)); - - // Test case 2: Key is not present in parentObj - JSONObject result2 = VRPConsentRequestValidator. - validateJsonObjectKey(new JSONObject(), "nonExistentKey", String.class); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'nonExistentKey' is not present in payload", - result2.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyWithCurrencyKey() { - - // Test case 3: Invalid currency key (missing key) - JSONObject testData3 = new JSONObject(); - - JSONObject result3 = VRPConsentRequestValidator. - validateJsonObjectKey(testData3, "currency", String.class); - Assert.assertFalse((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'currency' is not present in payload", - result3.get(ConsentExtensionConstants.ERRORS)); - - // Test case 4: Invalid currency key (null parentObj) - JSONObject result4 = VRPConsentRequestValidator. - validateJsonObjectKey(null, "currency", String.class); - Assert.assertFalse((boolean) result4.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'currency' is not present in payload", - result3.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidatePeriodicType() { - // Test case 1: Valid periodic type - JSONObject validLimitObject = new JSONObject(); - validLimitObject.put(ConsentExtensionConstants.PERIOD_TYPE, ConsentExtensionConstants.DAY); - JSONObject result1 = VRPConsentRequestValidator.validatePeriodType(validLimitObject); - Assert.assertTrue((boolean) result1.get(ConsentExtensionConstants.IS_VALID)); - - - // Test case 2: Missing period type key - JSONObject missingKeyObject = new JSONObject(); - JSONObject result2 = VRPConsentRequestValidator.validatePeriodType(missingKeyObject); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Missing required parameter Period type", - result2.get(ConsentExtensionConstants.ERRORS)); - - // Test case 3: Null period type - JSONObject nullPeriodTypeObject = new JSONObject(); - nullPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_TYPE, null); - JSONObject result3 = VRPConsentRequestValidator.validatePeriodType(nullPeriodTypeObject); - Assert.assertFalse((boolean) result3.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Missing required parameter Period type", - result2.get(ConsentExtensionConstants.ERRORS)); - - - // Test case 4: Empty period type - JSONObject emptyPeriodTypeObject = new JSONObject(); - emptyPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_TYPE, ""); - JSONObject result4 = VRPConsentRequestValidator.validatePeriodType(emptyPeriodTypeObject); - Assert.assertFalse((boolean) result4.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Missing required parameter Period type", - result2.get(ConsentExtensionConstants.ERRORS)); - - - // Test case 5: Invalid period type - JSONObject invalidPeriodTypeObject = new JSONObject(); - invalidPeriodTypeObject.put(ConsentExtensionConstants.PERIOD_TYPE, "InvalidType"); - JSONObject result5 = VRPConsentRequestValidator.validatePeriodType(invalidPeriodTypeObject); - Assert.assertFalse((boolean) result5.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Missing required parameter Period type", - result2.get(ConsentExtensionConstants.ERRORS)); - } - - @Test - public void testValidateAmountCurrencyWithoutCurrentKeyAndEmptyString() { - // Test case 1: parentObj is null - JSONObject result1 = VRPConsentRequestValidator. - validateJsonObjectKey(null, "Currency", String.class); - Assert.assertFalse(((boolean) result1.get(ConsentExtensionConstants.IS_VALID))); - Assert.assertEquals("parameter passed in is null", - result1.get(ConsentExtensionConstants.ERRORS)); - - // Test case 2: Key is not present in parentObj - JSONObject result2 = VRPConsentRequestValidator. - validateJsonObjectKey(new JSONObject(), "nonExistentKey", String.class); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'nonExistentKey' is not present in payload", - result2.get(ConsentExtensionConstants.ERRORS)); - - } - - @Test - public void testValidateAmountCurrencyWithoutAmountKeyAndEmptyString() { - - // Test case 1: parentObj is null - JSONObject result1 = VRPConsentRequestValidator. - validateJsonObjectKey(null, "Amount", String.class); - Assert.assertFalse((boolean) result1.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("parameter passed in is null", - result1.get(ConsentExtensionConstants.ERRORS)); - - // Test case 2: Key is not present in parentObj - JSONObject result2 = VRPConsentRequestValidator. - validateJsonObjectKey(new JSONObject(), "nonExistentKey", String.class); - Assert.assertFalse((boolean) result2.get(ConsentExtensionConstants.IS_VALID)); - Assert.assertEquals("Mandatory parameter 'nonExistentKey' is not present in payload", - result2.get(ConsentExtensionConstants.ERRORS)); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPTestConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPTestConstants.java deleted file mode 100644 index f8c8535e..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/manage/vrp/VRPTestConstants.java +++ /dev/null @@ -1,1122 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.manage.vrp; - -/** - * Constant class for consent manage tests. - */ -public class VRPTestConstants { - - public static String vrpInitiationPayloadWithoutData = "{\n" + - " \"\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static String vrpInitiationPayloadWithoutDate = "{\n" + - " \"\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"\",\n" + - " \"ValidToDateTime\": null, // Set to null instead of an empty string\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static String vrpInitiationPayloadWithStringData = "{\n" + - " \"\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static String vrpInitiationPayloadWithOutJsonObject = "{\n" + - " \"\": { }" + - ",\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_CREDITOR_ACCOUNT = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_DEBTOR_ACCOUNT = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - ; - - - public static final String METADATA_VRP_DEBTOR_ACCOUNT_SCHEME_NAME = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_CREDITOR_ACCOUNT_SCHEME_NAME = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_DEBTOR_ACCOUNT_IDENTIFICATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_CREDITOR_ACCOUNT_IDENTIFICATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_INITIATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_CONTROL_PARAMETERS = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_CURRENCY = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITHOUT_PERIODIC_LIMIT_CURRENCY = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITHOUT_PERIODIC_LIMIT_AMOUNT = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_PERIODIC_TYPE = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_PERIODIC_TYPE_CURRENCY = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"\": \"\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodicType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITHOUT_VALID_TO_DATE = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITH_INVALID_VALID_FROM_DATETIME = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"\": \"2023-09-12T\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITH_INVALID_MAX_INDIVIDUAL_AMOUNT = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": \"\",\n" + // Empty string for MaximumIndividualAmount - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_RISK = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITH_EMPTY_CONTROL_PARAMETERS = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": \"\",\n" + // Empty string for ControlParameters - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_EMPTY_INITIATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": \"\",\n" + // Empty string for Initiation - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITH_EMPTY_MAX_INDIVIDUAL_AMOUNT = "{\n" + - " \"\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": \"\",\n" + // Empty string for MaximumIndividualAmount - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITHOUT_VALID_FROM_DATE = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String METADATA_VRP_WITHOUT_DEB_ACC = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": \"\",\n" + // Change DebtorAccount to an empty string - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_DEBTOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"\": \"\",\n" + // Change DebtorAccount to an empty string - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - - public static final String METADATA_VRP_WITHOUT_CREDITOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": \"\", // Change CreditorAccount to an empty string\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - } diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/AuthServletTestConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/AuthServletTestConstants.java deleted file mode 100644 index a2d462af..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/AuthServletTestConstants.java +++ /dev/null @@ -1,256 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.utils; - -/** - * Constant class for OB Auth Servlet tests. - */ -public class AuthServletTestConstants { - public static final String ACCOUNT_DATA = "{" + - " \"consentData\": [" + - " {" + - " \"data\":[" + - " \"ReadAccountsBasic\"," + - " \"ReadAccountsDetail\"," + - " \"ReadBalances\"," + - " ]," + - " \"title\":\"Permissions\"" + - " }," + - " {" + - " \"data\":[\"2021-07-19T13:51:43.347+05:30\"]," + - " \"title\":\"Expiration Date Time\"" + - " }," + - " {" + - " \"data\":[\"2021-07-14T13:51:43.397+05:30\"]," + - " \"title\":\"Transaction From Date Time\"" + - " }," + - " {" + - " \"data\":[\"2021-07-17T13:51:43.397+05:30\"]," + - " \"title\":\"Transaction To Date Time\"}," + - " ]," + - " \"application\":\"9b5usDpbNtmxDcTzs7GzKp\"," + - " \"accounts\":[" + - " {" + - " \"accountId\":\"30080012343456\"," + - " \"account_id\":\"30080012343456\"," + - " \"authorizationMethod\":\"single\"," + - " \"accountName\":\"account_1\"," + - " \"nickName\":\"not-working\"," + - " \"display_name\":\"account_1\"" + - " }," + - " {" + - " \"accountId\":\"30080098763459\"," + - " \"account_id\":\"30080098763459\"," + - " \"authorizationMethod\":\"single\"," + - " \"accountName\":\"account_2\"," + - " \"display_name\":\"account_2\"" + - " }" + - " ]," + - " \"type\":\"accounts\"" + - "}"; - - public static final String COF_DATA = "{" + - " \"consentData\":[" + - " {" + - " \"data\":[\"2021-07-19T20:14:11.069+05:30\"]," + - " \"title\":\"Expiration Date Time\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 1234\"," + - " \"Name : Account1\"," + - " \"Secondary Identification : Account1\"" + - " ]," + - " \"title\":\"Debtor Account\"" + - " }," + - " ]," + - " \"application\":\"9b5usDpbNtmxDcTzs7GzKp\"," + - " \"type\":\"fundsconfirmations\"," + - " \"debtor_account\":\"1234\"" + - "}"; - - public static final String PAYMENT_DATA = "{" + - " \"consentData\":[" + - " {" + - " \"data\":[\"Domestic Payments\"]," + - " \"title\":\"Payment Type\"" + - " }," + - " {" + - " \"data\":[\"ACME412\"]," + - " \"title\":\"Instruction Identification\"" + - " }," + - " {" + - " \"data\":[\"FRESCO.21302.GFX.20\"]," + - " \"title\":\"End to End Identification\"" + - " }," + - " {" + - " \"data\":[\"Amount : 30.80\",\"Currency : GBP\"]," + - " \"title\":\"Instructed Amount\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 30080012343456\"," + - " \"Name : Andrea Smith\"," + - " \"Secondary Identification : 30080012343456\"" + - " ]," + - " \"title\":\"Debtor Account\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 08080021325698\"," + - " \"Name : ACME Inc\"," + - " \"Secondary Identification : 0002\"" + - " ]," + - " \"title\":\"Creditor Account\"" + - " }," + - " ]," + - " \"application\":\"9b5usDpbNtmxDcTzs7GzKp\"," + - " \"type\":\"payments\"," + - " \"debtor_account\":\"30080012343456\"" + - "}"; - - public static final String PAYMENT_DATA_WITHOUT_DEBTOR_ACC = "{\n" + - " \"consentData\":[\n" + - " {\n" + - " \"data\":[\n" + - " \"Domestic Payments\"\n" + - " ],\n" + - " \"title\":\"Payment Type\"\n" + - " },\n" + - " {\n" + - " \"data\":[\n" + - " \"ACME412\"\n" + - " ],\n" + - " \"title\":\"Instruction Identification\"\n" + - " },\n" + - " {\n" + - " \"data\":[\n" + - " \"FRESCO.21302.GFX.20\"\n" + - " ],\n" + - " \"title\":\"End to End Identification\"\n" + - " },\n" + - " {\n" + - " \"data\":[\n" + - " \"Amount : 30.80\",\n" + - " \"Currency : GBP\"\n" + - " ],\n" + - " \"title\":\"Instructed Amount\"\n" + - " },\n" + - " {\n" + - " \"data\":[\n" + - " \"Scheme Name : OB.SortCodeAccountNumber\",\n" + - " \"Identification : 08080021325698\",\n" + - " \"Name : ACME Inc\"\n" + - " ],\n" + - " \"title\":\"Creditor Account\"\n" + - " },\n" + - " ]," + - " \"type\":\"Payments\"\n" + - "}"; - - - public static final String VRP_DATA = "{" + - " \"consentData\":[" + - " {" + - " \"data\":[\"Domestic VRP\"]," + - " \"title\":\"Payment Type\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 30080012343456\"," + - " \"Name : Andrea Smith\"," + - " \"Secondary Identification : 30080012343456\"" + - " ]," + - " \"title\":\"Debtor Account\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 08080021325698\"," + - " \"Name : ACME Inc\"," + - " \"Secondary Identification : 0002\"" + - " ]," + - " \"title\":\"Creditor Account\"" + - " }," + - " {" + - " \"data\":[\"100\"]," + - " \"title\":\"Maximum amount per payment\"" + - " }," + - " {" + - " \"data\":[\"Consent\"]," + - " \"title\":\"Period Alignment\"" + - " }," + - " {" + - " \"data\":[\"200\"]," + - " \"title\":\"Maximum payment amount per Week\"" + - " }," + - " ]," + - " \"application\":\"9b5usDpbNtmxDcTzs7GzKp\"," + - " \"type\":\"vrp\"," + - " \"debtor_account\":\"30080012343456\"" + - "}"; - - - public static final String VRP_DATA_WITHOUT_DEBTOR_ACC = "{" + - " \"consentData\":[" + - " {" + - " \"data\":[\"Domestic VRP\"]," + - " \"title\":\"Payment Type\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 30080012343456\"," + - " \"Name : Andrea Smith\"," + - " \"Secondary Identification : 30080012343456\"" + - " ]," + - " \"title\":\"Debtor Account\"" + - " }," + - " {" + - " \"data\":[" + - " \"Scheme Name : OB.SortCodeAccountNumber\"," + - " \"Identification : 08080021325698\"," + - " \"Name : ACME Inc\"," + - " \"Secondary Identification : 0002\"" + - " ]," + - " \"title\":\"Creditor Account\"" + - " }," + - " {" + - " \"data\":[\"100\"]," + - " \"title\":\"Maximum amount per payment\"" + - " }," + - " {" + - " \"data\":[\"Consent\"]," + - " \"title\":\"Period Alignment\"" + - " }," + - " {" + - " \"data\":[\"200\"]," + - " \"title\":\"Maximum payment amount per Week\"" + - " }," + - " ]," + - " \"type\":\"vrp\"," + - "}"; - - public static final String JSON_WITH_TYPE = "{" + - " \"type\":\"test\"" + - "}"; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentAuthorizeTestConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentAuthorizeTestConstants.java deleted file mode 100644 index 71bac8ce..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentAuthorizeTestConstants.java +++ /dev/null @@ -1,405 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.utils; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; - -import java.time.Instant; -import java.time.OffsetDateTime; - -/** - * Constant class for consent authorize tests. - */ -public class ConsentAuthorizeTestConstants { - public static final String INVALID_REQUEST_OBJECT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.aWF0.TIygRaBn7MUFR9Zzy3" + - "yu9K8uKVe8KXdAty0Ckrg2vFI"; - public static final String VALID_REQUEST_OBJECT = "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkR3TUtkV01tajdQV2" + - "ludm9xZlF5WFZ6eVo2USJ9.eyJtYXhfYWdlIjo4NjQwMCwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6OTQ0Ni9vYXV0aDIvdG9rZW4iL" + - "CJzY29wZSI6Im9wZW5pZCBhY2NvdW50cyIsImlzcyI6InF3ZGZnaGpwbG1nZmRhYWhrZ2pvcGhuayIsImNsYWltcyI6eyJpZF90b2tlb" + - "iI6eyJhY3IiOnsidmFsdWVzIjpbInVybjpvcGVuYmFua2luZzpwc2QyOnNjYSIsInVybjpvcGVuYmFua2luZzpwc2QyOmNhIl0sImVzc" + - "2VudGlhbCI6dHJ1ZX0sIm9wZW5iYW5raW5nX2ludGVudF9pZCI6eyJ2YWx1ZSI6IjEyMzQ1Njc3NjU0MzIxMjM0MjM0IiwiZXNzZW50a" + - "WFsIjp0cnVlfX0sInVzZXJpbmZvIjp7Im9wZW5iYW5raW5nX2ludGVudF9pZCI6eyJ2YWx1ZSI6IjEyMzQ1Njc3NjU0MzIxMjM0MjM0I" + - "iwiZXNzZW50aWFsIjp0cnVlfX19LCJyZXNwb25zZV90eXBlIjoiY29kZSBpZF90b2tlbiIsInJlZGlyZWN0X3VyaSI6Imh0dHBzOi8vd" + - "3NvMi5jb20iLCJzdGF0ZSI6IllXbHpjRG96TVRRMiIsImV4cCI6MTY1MzcxNzQ3OCwibm9uY2UiOiJuLTBTNl9XekEyTSIsImNsaWVud" + - "F9pZCI6InF3ZGZnaGpwbG1nZmRhYWhrZ2pvcGhuayJ9.lOvcc81dqjqdv4dslB_Kg4K3TKd13UQWaUKl3dBiPPlnu9y-R84Xfx-bMMnH" + - "atYyW9hYWJcUlprIm_dqgFXauCSTgBz6-vacrXLzuaGtj07d-8bL_qta45qbpbKPTY2pnM_PXe7fzs4RMCGEoiRLRs7lJUBfIbV9GzlS" + - "pHkOZiOjiFxxeYm0cNpZRvXkZNd59_GLdW2kKmWaGQHpQ9Ci_QpQENRzF8KEV1QtNd3cK2DjL5tKSw824C6AmXp-PKfvhurqPaVkz5p-" + - "iPA6bRaNBPY4hj_nsZpfuCnE8-V7YXWXXzWbK3gWo_dMOV1CZcHS6KqP7DANqDEEP4LoN081uQ"; - - public static final OffsetDateTime EXP_DATE = OffsetDateTime.now().plusDays(50); - - public static final OffsetDateTime INVALID_EXP_DATE = OffsetDateTime.now().plusDays(0); - - public static final OffsetDateTime NULL_EXP_DATE = null; - public static final String VALID_INITIATION_OBJECT = "{\"Data\": {\"Permissions\": [\"ReadAccountsDetail\"," + - "\"ReadBalances\",\"ReadBeneficiariesDetail\",\"ReadDirectDebits\",\"ReadProducts\"," + - "\"ReadStandingOrdersDetail\",\"ReadTransactionsCredits\",\"ReadTransactionsDebits\"," + - "\"ReadTransactionsDetail\",\"ReadOffers\",\"ReadPAN\",\"ReadParty\",\"ReadPartyPSU\"," + - " \"ReadScheduledPaymentsDetail\",\"ReadStatementsDetail\"],\"ExpirationDateTime\": " + - "\"" + EXP_DATE + "\",\"TransactionFromDateTime\": \"2021-05-03T00:00:00+00:00\"," + - "\"TransactionToDateTime\": \"2021-12-03T00:00:00+00:00\"},\"Risk\": {}}"; - - public static final String INVALID_INITIATION_OBJECT = "{\"Data\": {\"Permissions\": [\"ReadAccountsDetail\"," + - "\"ReadBalances\",\"ReadBeneficiariesDetail\",\"ReadDirectDebits\",\"ReadProducts\"," + - "\"ReadStandingOrdersDetail\",\"ReadTransactionsCredits\",\"ReadTransactionsDebits\"," + - "\"ReadTransactionsDetail\",\"ReadOffers\",\"ReadPAN\",\"ReadParty\",\"ReadPartyPSU\"," + - " \"ReadScheduledPaymentsDetail\",\"ReadStatementsDetail\"],\"ExpirationDateTime\": " + - "\"" + INVALID_EXP_DATE + "\",\"TransactionFromDateTime\": \"2021-05-03T00:00:00+00:00\"," + - "\"TransactionToDateTime\": \"2021-12-03T00:00:00+00:00\"},\"Risk\": {}}"; - - - public static final String AWAITING_AUTH_STATUS = "awaitingAuthorisation"; - public static final long CREATED_TIME = Instant.now().toEpochMilli(); - public static final String ACCOUNTS = "accounts"; - public static final String PAYMENTS = "payments"; - public static final String FUNDS_CONFIRMATIONS = "fundsconfirmations"; - public static final String VRP = "vrp"; - public static final String PAYLOAD_WITH_NON_STRING_ACCOUNTID = "{\"accountIds\": [1234, 2345]}"; - public static final String CONSENT_ID = "4ae1e012-eaa7-4994-a055-c6454f0aeeb4"; - public static final String USER_ID = "admin@wso2.com"; - public static final String CLIENT_ID = "9vblw2uUr7FOfQzI0_XGzM7IRxAa"; - public static final String COF_RECEIPT = "{" + - " \"Data\": {" + - " \"DebtorAccount\": {" + - " \"SchemeName\": \"OB.IBAN\"," + - " \"Identification\": \"GB76LOYD30949301273801\"," + - " \"Name\": \"Andrea Smith\"," + - " \"SecondaryIdentification\": \"Roll 56988\"" + - " }," + - " \"ExpirationDateTime\": \"" + EXP_DATE + "\"" + - " }" + - "}"; - - public static final String INVALID_COF_RECEIPT = "{" + - " \"Data\": {" + - " \"DebtorAccount\": {" + - " \"SchemeName\": \"OB.IBAN\"," + - " \"Identification\": \"GB76LOYD30949301273801\"," + - " \"Name\": \"Andrea Smith\"," + - " \"SecondaryIdentification\": \"Roll 56988\"" + - " }," + - " \"ExpirationDateTime\": \"" + INVALID_EXP_DATE + "\"" + - " }" + - "}"; - - public static final String NULL_COF_RECEIPT = "{" + - " \"Data\": {" + - " \"DebtorAccount\": {" + - " \"SchemeName\": \"OB.IBAN\"," + - " \"Identification\": \"GB76LOYD30949301273801\"," + - " \"Name\": \"Andrea Smith\"," + - " \"SecondaryIdentification\": \"Roll 56988\"" + - " }," + - " \"ExpirationDateTime\": \"" + NULL_EXP_DATE + "\"" + - " }" + - "}"; - public static final String VRP_INITIATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"Yes\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2017-06-05T15:15:13+00:00\",\n" + - " \"ValidToDateTime\": \"2022-07-05T15:15:13+00:00\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"100.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"200.00\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Week\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {" + - " \"Name\": \"Andrea Smith\", " + - " \"SchemeName\": \"OB.SortCodeAccountNumber\", " + - " \"Identification\": \"30080012343456\", " + - " \"SecondaryIdentification\": \"30080012343456\"" + - " }," + - " \"CreditorAccount\": {" + - " \"Name\": \"Andrea Smith\", " + - " \"SchemeName\": \"OB.SortCodeAccountNumber\", " + - " \"Identification\": \"30080012343456\", " + - " \"SecondaryIdentification\": \"30080012343456\"" + - " }," + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_WITHOUT_CONTROLPARAMETERS = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"Yes\",\n" + - " \"\": {\n" + - " \"ValidFromDateTime\": \"2017-06-05T15:15:13+00:00\",\n" + - " \"ValidToDateTime\": \"2022-07-05T15:15:13+00:00\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"100.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"200.00\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Week\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {" + - " \"Name\": \"Andrea Smith\", " + - " \"SchemeName\": \"OB.SortCodeAccountNumber\", " + - " \"Identification\": \"30080012343456\", " + - " \"SecondaryIdentification\": \"30080012343456\"" + - " }," + - " \"CreditorAccount\": {" + - " \"Name\": \"Andrea Smith\", " + - " \"SchemeName\": \"OB.SortCodeAccountNumber\", " + - " \"Identification\": \"30080012343456\", " + - " \"SecondaryIdentification\": \"30080012343456\"" + - " }," + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_WITHOUT_DATA = "{\n" + - " \"\": {\n" + - " \"ReadRefundAccount\": \"Yes\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2017-06-05T15:15:13+00:00\",\n" + - " \"ValidToDateTime\": \"2022-07-05T15:15:13+00:00\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"100.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"200.00\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Week\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {" + - " \"Name\": \"Andrea Smith\", " + - " \"SchemeName\": \"OB.SortCodeAccountNumber\", " + - " \"Identification\": \"30080012343456\", " + - " \"SecondaryIdentification\": \"30080012343456\"" + - " }," + - " \"CreditorAccount\": {" + - " \"Name\": \"Andrea Smith\", " + - " \"SchemeName\": \"OB.SortCodeAccountNumber\", " + - " \"Identification\": \"30080012343456\", " + - " \"SecondaryIdentification\": \"30080012343456\"" + - " }," + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - static OffsetDateTime expirationInstant = OffsetDateTime.now().plusDays(50); - public static final String PAYMENT_INITIATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"Yes\",\n" + - " \"Authorisation\": {\n" + - " \"AuthorisationType\": \"Any\",\n" + - " \"CompletionDateTime\": \"" + expirationInstant + "\"\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"165\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"DebtorAccount\": {\n" + - "\"SchemeName\": \"OB.SortCodeAccountNumber\",\n" + - "\"Identification\": \"30080012343456\",\n" + - "\"Name\": \"Andrea Smith\",\n" + - "\"SecondaryIdentification\": \"30080012343456\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.SortCodeAccountNumber\",\n" + - " \"Identification\": \"08080021325698\",\n" + - " \"Name\": \"ACME Inc\",\n" + - " \"SecondaryIdentification\": \"0002\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"FRESCO-101\",\n" + - " \"Unstructured\": \"Internal ops code 5120101\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"EcommerceGoods\",\n" + - " \"MerchantCategoryCode\": \"5967\",\n" + - " \"MerchantCustomerIdentification\": \"053598653254\",\n" + - " \"DeliveryAddress\": {\n" + - " \"AddressLine\": [\n" + - " \"Flat 7\",\n" + - " \"Acacia Lodge\"\n" + - " ],\n" + - " \"StreetName\": \"Acacia Avenue\",\n" + - " \"BuildingNumber\": \"27\",\n" + - " \"PostCode\": \"GU31 2ZZ\",\n" + - " \"TownName\": \"Sparsholt\",\n" + - " \"CountySubDivision\": [\n" + - " \"Wessex\"\n" + - " ],\n" + - " \"Country\": \"UK\"\n" + - " }\n" + - " }\n" + - "}"; - public static final String INTERNATIONAL_PAYMENT_INITIATION = "" + - "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"Yes\",\n" + - " \"Initiation\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"InstructionPriority\": \"Normal\",\n" + - " \"CurrencyOfTransfer\": \"USD\",\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"165.88\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.SortCodeAccountNumber\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Andrea Smith\",\n" + - " \"SecondaryIdentification\": \"30080012343456\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.SortCodeAccountNumber\",\n" + - " \"Identification\": \"08080021325698\",\n" + - " \"Name\": \"ACME Inc\",\n" + - " \"SecondaryIdentification\": \"0002\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"FRESCO-101\",\n" + - " \"Unstructured\": \"Internal ops code 5120101\"\n" + - " },\n" + - " \"ExchangeRateInformation\": {\n" + - " \"UnitCurrency\": \"GBP\",\n" + - " \"RateType\": \"Actual\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"TransferToThirdParty\"\n" + - " }\n" + - "}"; - - public static final String ACCOUNT_PERSIST_PAYLOAD_WITHOUT_ACCOUNT_ID = " " + - "{" + - " \"metadata\": {" + - " \"commonAuthId\":\"b37b9c9b-b5ce-4889-966e-9cb30f70cc78\"" + - " }," + - " \"cofAccount\":\"\"," + - " \"approval\":\"true\"," + - " \"accountIds\": \"\"," + - " \"isReauthorization\":\"false\"," + - " \"type\":\"accounts\"," + - " \"paymentAccount\":\"\"" + - "}"; - - public static final String COF_PERSIST_PAYLOAD = " " + - "{" + - " \"metadata\": {" + - " \"commonAuthId\":\"b37b9c9b-b5ce-4889-966e-9cb30f70cc78\"" + - " }," + - " \"approval\":\"true\"," + - " \"cofAccount\":\"1234\"," + - " \"accountIds\": \"\"," + - " \"type\":\"accounts\"," + - "}"; - - public static final String COF_PERSIST_PAYLOAD_WITHOUT_COF_ACC = " " + - "{" + - " \"metadata\": {" + - " \"commonAuthId\":\"b37b9c9b-b5ce-4889-966e-9cb30f70cc78\"" + - " }," + - " \"approval\":\"true\"," + - " \"accountIds\": \"\"," + - " \"isReauthorization\":\"false\"," + - " \"type\":\"accounts\"," + - " \"paymentAccount\":\"\"" + - "}"; - - public static final String COF_PERSIST_PAYLOAD_WITH_NON_STRING_COF_ACC = " " + - "{" + - " \"metadata\": {" + - " \"commonAuthId\":\"b37b9c9b-b5ce-4889-966e-9cb30f70cc78\"" + - " }," + - " \"cofAccount\":1234," + - " \"approval\":\"true\"," + - " \"accountIds\": \"\"," + - " \"isReauthorization\":\"false\"," + - " \"type\":\"accounts\"," + - " \"paymentAccount\":\"\"" + - "}"; - - public static AuthorizationResource getAuthResource() { - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setAuthorizationID("1234"); - authorizationResource.setConsentID(ConsentAuthorizeTestConstants.CONSENT_ID); - authorizationResource.setAuthorizationStatus("created"); - authorizationResource.setAuthorizationType("authorization"); - - return authorizationResource; - } - - public static final String ACCOUNT_PERSIST_PAYLOAD = " " + - "{" + - " \"metadata\": {" + - " \"commonAuthId\":\"b37b9c9b-b5ce-4889-966e-9cb30f70cc78\"" + - " }," + - " \"cofAccount\":\"\"," + - " \"approval\":\"true\"," + - " \"accountIds\":[" + - " \"30080012343456\"" + - " ]," + - " \"type\":\"accounts\"," + - " \"paymentAccount\":\"\"" + - "}"; - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionDataProvider.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionDataProvider.java deleted file mode 100644 index 19ea53c5..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionDataProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.utils; - -import org.testng.annotations.DataProvider; - -/** - * Data Provider for Consent Executor Tests. - */ -public class ConsentExtensionDataProvider { - - @DataProvider(name = "VRPInvalidSubmissionPayloadsDataProvider") - Object[][] getVRPInvalidSubmissionPayloadsDataProvider() { - - return new Object[][]{ - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_INSTRUCTION_IDENTIFICATION}, - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_END_TO_IDENTIFICATION}, - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_INSTRUCTED_AMOUNT}, - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_INSTRUCTION_CREDITOR_ACC}, - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_INSTRUCTION_REMITTANCE_INFO}, - }; - } - - @DataProvider(name = "VRPInvalidInitiationSubmissionPayloadsDataProvider") - Object[][] getVRPInvalidInitiationSubmissionPayloadsDataProvider() { - - return new Object[][]{ - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_CREDITOR_ACC}, - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_REMITTANCE_INFO}, - {ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_DEBTOR_ACC}, - }; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionTestConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionTestConstants.java deleted file mode 100644 index d7ccaa71..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionTestConstants.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.utils; - -/** -comment. - */ -public class ConsentExtensionTestConstants { - - public static final String VALID_INITIATION_OBJECT = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionTestUtils.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionTestUtils.java deleted file mode 100644 index b945da8d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentExtensionTestUtils.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.extensions.utils; - -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; - -import java.lang.reflect.Field; -import java.time.OffsetDateTime; -import java.util.HashMap; -import java.util.Map; - - -/** - * Utils class for consent executor tests. - */ -public class ConsentExtensionTestUtils { - - static JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - - public static void injectEnvironmentVariable(String key, String value) - throws ReflectiveOperationException { - - Class processEnvironment = Class.forName("java.lang.ProcessEnvironment"); - - Field unmodifiableMapField = getAccessibleField(processEnvironment, "theUnmodifiableEnvironment"); - Object unmodifiableMap = unmodifiableMapField.get(null); - injectIntoUnmodifiableMap(key, value, unmodifiableMap); - - Field mapField = getAccessibleField(processEnvironment, "theEnvironment"); - Map map = (Map) mapField.get(null); - map.put(key, value); - } - - private static Field getAccessibleField(Class clazz, String fieldName) - throws NoSuchFieldException { - - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - return field; - } - - private static void injectIntoUnmodifiableMap(String key, String value, Object map) - throws ReflectiveOperationException { - - Class unmodifiableMap = Class.forName("java.util.Collections$UnmodifiableMap"); - Field field = getAccessibleField(unmodifiableMap, "m"); - Object obj = field.get(map); - ((Map) obj).put(key, value); - } - - public static JSONObject getInitiationPayload(JSONObject payload) { - return (JSONObject) ((JSONObject) payload.get(ConsentExtensionConstants.DATA)) - .get(ConsentExtensionConstants.INITIATION); - } - - public static JSONObject getJsonPayload(String payload) throws ParseException { - return (JSONObject) parser.parse(payload); - } - - public static ConsentAttributes getConsentAttributes(String paymentType) { - - Map consentAttributesMap = new HashMap(); - consentAttributesMap.put(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT, "100.00"); - consentAttributesMap.put(ConsentExtensionConstants.PAYMENT_TYPE, paymentType); - consentAttributesMap.put(ConsentExtensionConstants.PAID_AMOUNT, "20.00"); - consentAttributesMap.put(ConsentExtensionConstants.LAST_PAYMENT_DATE, - OffsetDateTime.now().minusDays(50).toString()); - consentAttributesMap.put(ConsentExtensionConstants.PREVIOUS_PAID_AMOUNT, "20.00"); - consentAttributesMap.put(ConsentExtensionConstants.PREVIOUS_LAST_PAYMENT_DATE, - OffsetDateTime.now().minusDays(50).toString()); - - ConsentAttributes consentAttributes = new ConsentAttributes(); - consentAttributes.setConsentAttributes(consentAttributesMap); - - return consentAttributes; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentValidateTestConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentValidateTestConstants.java deleted file mode 100644 index 0411286d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/utils/ConsentValidateTestConstants.java +++ /dev/null @@ -1,1091 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.utils; - -import java.time.OffsetDateTime; - -/** - * comment. - */ -public class ConsentValidateTestConstants { - public static final OffsetDateTime EXPIRATION_DATE = OffsetDateTime.now().plusDays(50); - public static final String CONSENT_ID = "0ba972a9-08cd-4cad-b7e2-20655bcbd9e0"; - public static final String INVALID_CONSENT_ID = "0ba972a9-08cd-4cad-b7e2-20655bcbd9e0"; - public static final String INVALID_CONSENT_TYPE = "InvalidConsentType"; - public static final String VRP_PATH = "/domestic-vrps"; - public static final String PAYMENT_PATH = "/domestic-payments"; - public static final String USER_ID = "admin@wso2.com"; - public static final String CLIENT_ID = "xzX8t9fx6VxYMx_B6Lgpd5_yyUEa"; - public static final String SAMPLE_AUTHORIZATION_TYPE = "authorizationType"; - public static final String VRP_INITIATION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_INITIATION_WITHOUT_DEBTOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_INITIATION_WITHOUT_CREDITOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - public static final String VRP_SUBMISSION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_RISK = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - "}"; - - public static final String VRP_SUBMISSION_WITH_INVALID_INSTRUCTION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"UK.OBIE.IBAN\",\n" + - " \"Identification\": \"GB76LOYD30949301273801\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"SortCodeAccountNumber\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITH_INVALID_RISK = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"CreditToThirdParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_INSTRUCTION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - " \"PSUInteractionType\": \"OffSession\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"GB76LOYD30949301273801\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"SortCodeAccountNumber\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_CREDITOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_INSTRUCTION_REMITTANCE_INFO = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_DEBTOR_ACC_MISMATCH = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_REMITTANCE_INFO = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_REMITTANCE_INFO_MISMATCH = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"ThirdParty\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_INSTRUCTED_AMOUNT = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_INSTRUCTION_IDENTIFICATION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_END_TO_IDENTIFICATION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_DEBTOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITH_INTEGER_INSTRUCTION_IDENTIFICATION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": 788,\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITH_INTEGER_END_TO_IDENTIFICATION = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": 5666,\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_INSTRUCTION_REMITTANCE_INFO_MISMATCH = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"ThirdParty\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITH_DEBTOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITH_INSTRUCTION_CREDITOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_SUBMISSION_WITHOUT_INSTRUCTION_CREDITOR_ACC = "{\n" + - " \"Data\": {\n" + - " \"ConsentId\": \"" + CONSENT_ID + "\",\n" + - " \"PSUAuthenticationMethod\": \"OB.SCA\",\n" + - "\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " },\n" + - "\n" + - " \"Instruction\": {\n" + - " \"InstructionIdentification\": \"ACME412\",\n" + - " \"EndToEndIdentification\": \"FRESCO.21302.GFX.20\",\n" + - " \"\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - "\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; - - public static final String VRP_INSTRUCTION = "{\n" + - " \"Data\": {\n" + - " \"ReadRefundAccount\": \"true\",\n" + - " \"ControlParameters\": {\n" + - " \"ValidFromDateTime\": \"2023-09-12T12:43:07.956Z\",\n" + - " \"ValidToDateTime\": \"2024-05-12T12:43:07.956Z\",\n" + - " \"MaximumIndividualAmount\": {\n" + - " \"Amount\": \"9\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"PeriodicLimits\": [\n" + - " {\n" + - " \"Amount\": \"1000\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"PeriodAlignment\": \"Consent\",\n" + - " \"PeriodType\": \"Half-year\"\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Initiation\": {\n" + - " \"DebtorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30080012343456\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"CreditorAccount\": {\n" + - " \"SchemeName\": \"OB.IBAN\",\n" + - " \"Identification\": \"30949330000010\",\n" + - " \"SecondaryIdentification\": \"Roll 90210\",\n" + - " \"Name\": \"Marcus Sweepimus\"\n" + - " },\n" + - " \"RemittanceInformation\": {\n" + - " \"Reference\": \"Sweepco\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"Risk\": {\n" + - " \"PaymentContextCode\": \"PartyToParty\"\n" + - " }\n" + - "}"; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/validate/VRPSubmissionTest.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/validate/VRPSubmissionTest.java deleted file mode 100644 index 70c17895..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/java/com/wso2/openbanking/accelerator/consent/extensions/validate/VRPSubmissionTest.java +++ /dev/null @@ -1,887 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.extensions.validate; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.common.util.ErrorConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentServiceUtil; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionDataProvider; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestConstants; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentExtensionTestUtils; -import com.wso2.openbanking.accelerator.consent.extensions.utils.ConsentValidateTestConstants; -import com.wso2.openbanking.accelerator.consent.extensions.validate.impl.DefaultConsentValidator; -import com.wso2.openbanking.accelerator.consent.extensions.validate.impl.VRPSubmissionPayloadValidator; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidateData; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidationResult; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.joda.time.Instant; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -/** - * Test class for validating Variable Recurring Payment submission requests. - */ -@PrepareForTest({OpenBankingConfigParser.class, OpenBankingConfigParser.class, ConsentServiceUtil.class}) -@PowerMockIgnore({"com.wso2.openbanking.accelerator.consent.extensions.common.*", "net.minidev.*", - "jdk.internal.reflect.*"}) -public class VRPSubmissionTest { - VRPSubmissionPayloadValidator validator = new VRPSubmissionPayloadValidator(); - DefaultConsentValidator consentValidator; - @Mock - ConsentValidateData consentValidateDataMock; - @Mock - DetailedConsentResource detailedConsentResourceMock; - @Mock - ConsentCoreServiceImpl consentCoreServiceMock; - @Mock - ConsentValidationResult consentValidationResultMock; - Map resourceParams = new HashMap<>(); - JSONObject headers = new JSONObject(); - private static Map configMap; - Map consentAttributes = new HashMap<>(); - ArrayList authorizationResources = new ArrayList(); - - @BeforeClass - public void initClass() throws ReflectiveOperationException { - MockitoAnnotations.initMocks(this); - - //to execute util class initialization - new CarbonUtils(); - System.setProperty("some.property", "property.value"); - System.setProperty("carbon.home", "."); - ConsentExtensionTestUtils.injectEnvironmentVariable("CARBON_HOME", "."); - - configMap = new HashMap<>(); - configMap.put("ErrorURL", "https://localhost:8243/error"); - - consentValidator = new DefaultConsentValidator(); - consentValidateDataMock = mock(ConsentValidateData.class); - authorizationResources.add(getAuthorizationResource()); - detailedConsentResourceMock = mock(DetailedConsentResource.class); - consentCoreServiceMock = mock(ConsentCoreServiceImpl.class); - } - - @BeforeMethod - public void initMethod() { - - OpenBankingConfigParser openBankingConfigParserMock = mock(OpenBankingConfigParser.class); - doReturn(configMap).when(openBankingConfigParserMock).getConfiguration(); - - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - @Test - public void testValidateInitiation() throws ParseException { - - JSONObject initPayload = ConsentExtensionTestUtils.getJsonPayload( - ConsentValidateTestConstants.VRP_INITIATION); - JSONObject subPayload = ConsentExtensionTestUtils.getJsonPayload( - ConsentValidateTestConstants.VRP_SUBMISSION); - - JSONObject validationResult = validator.validateInitiation( - ConsentExtensionTestUtils.getInitiationPayload(subPayload), - ConsentExtensionTestUtils.getInitiationPayload(initPayload)); - - Assert.assertTrue((Boolean) validationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD)); - } - - @Test - public void testCreditorAccInInstruction() throws ParseException { - - JSONObject initPayload = ConsentExtensionTestUtils.getJsonPayload( - ConsentValidateTestConstants.VRP_INITIATION_WITHOUT_CREDITOR_ACC); - JSONObject subPayload = ConsentExtensionTestUtils.getJsonPayload( - ConsentValidateTestConstants.VRP_SUBMISSION); - - JSONObject validationResult = validator.validateCreditorAcc( - ConsentExtensionTestUtils.getInitiationPayload(subPayload), - ConsentExtensionTestUtils.getInitiationPayload(initPayload)); - - Assert.assertTrue((Boolean) validationResult.get(ConsentExtensionConstants.IS_VALID_PAYLOAD)); - } - - @Test - public void testValidateVRPSubmission() throws ParseException, ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertTrue(consentValidationResult.isValid()); - } - @Test - public void testValidateVRPSubmissionWithoutRisk() throws ParseException, ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_RISK); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.RISK_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testConsentValidateWithUserIdMismatch() { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionTestConstants.VALID_INITIATION_OBJECT).when(detailedConsentResourceMock) - .getReceipt(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn("psu1@wso2.com").when(consentValidateDataMock).getUserId(); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.INVALID_USER_ID);; - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_CONSENT_MISMATCH); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithInvalidStatus() { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentExtensionTestConstants.VALID_INITIATION_OBJECT).when(detailedConsentResourceMock) - .getReceipt(); - doReturn(ConsentExtensionConstants.AWAITING_AUTH_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.VRP_CONSENT_STATUS_INVALID); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_INVALID_CONSENT_STATUS); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithInvalidInstruction() throws ParseException, ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITH_INVALID_INSTRUCTION); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), - ErrorConstants.CREDITOR_ACC_SCHEME_NAME_MISMATCH); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_CONSENT_MISMATCH); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithInvalidRisk() throws ParseException, ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITH_INVALID_RISK); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.RISK_PARAMETER_MISMATCH); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_CONSENT_MISMATCH); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithoutInstruction() throws ParseException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_INSTRUCTION); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.INSTRUCTION_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - private Map getVRPConsentAttributes() { - consentAttributes.put(ConsentExtensionConstants.PAYMENT_TYPE, "domestic-vrp-consents"); - consentAttributes.put(ConsentExtensionConstants.MAXIMUM_INDIVIDUAL_AMOUNT, "100.00"); - consentAttributes.put(ConsentExtensionConstants.PERIOD_ALIGNMENT, "Consent"); - consentAttributes.put(ConsentExtensionConstants.PERIOD_TYPE, "Week"); - consentAttributes.put(ConsentExtensionConstants.LAST_PAYMENT_DATE, - Long.toString(ConsentValidateTestConstants.EXPIRATION_DATE.toEpochSecond())); - consentAttributes.put(ConsentExtensionConstants.AMOUNT, "100.00"); - - return consentAttributes; - } - - private AuthorizationResource getAuthorizationResource() { - return new AuthorizationResource(ConsentValidateTestConstants.CONSENT_ID, - ConsentValidateTestConstants.USER_ID, "awaitingAuthorization", - ConsentValidateTestConstants.SAMPLE_AUTHORIZATION_TYPE, Instant.now().getMillis()); - } - - @Test - public void testValidateVRPSubmissionWithoutCreditorAccount() throws ParseException, ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_CREDITOR_ACC); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.CREDITOR_ACC_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithDebtorAccountMisMatch() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_DEBTOR_ACC_MISMATCH); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.DEBTOR_ACC_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithoutRemittanceInfo() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_REMITTANCE_INFO); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), - ErrorConstants.REMITTANCE_INFO_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithRemittanceInfoMisMatch() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_REMITTANCE_INFO_MISMATCH); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), - ErrorConstants.REMITTANCE_INFO_MISMATCH); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_CONSENT_MISMATCH); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test(dataProvider = "VRPInvalidInitiationSubmissionPayloadsDataProvider", - dataProviderClass = ConsentExtensionDataProvider.class) - public void testValidateVRPSubmissionForInvalidInitiation(String payload) throws ParseException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(payload); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - // Using VRPInvalidInitiationSubmissionPayloadsDataProvider dataProvider three test scenarios are been tested. - // Relevant error messages will be returned respectively. - } - - @Test - public void testValidateVRPSubmissionWithIntegerInstructionIdentification() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITH_INTEGER_INSTRUCTION_IDENTIFICATION); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.INVALID_SUBMISSION_TYPE); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_INVALID); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithIntegerEndToEndIdentification() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITH_INTEGER_END_TO_IDENTIFICATION); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), - ErrorConstants.INVALID_END_TO_END_IDENTIFICATION_TYPE); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_INVALID); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithoutDebtorAccInSubmission() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION_WITHOUT_DEBTOR_ACC).when(detailedConsentResourceMock) - .getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITH_DEBTOR_ACC); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.DEBTOR_ACC_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testValidateVRPSubmissionWithoutCreditorAccInInitiation() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION_WITHOUT_CREDITOR_ACC).when(detailedConsentResourceMock). - getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITH_INSTRUCTION_CREDITOR_ACC); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.CREDITOR_ACC_NOT_FOUND); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.FIELD_MISSING); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test(dataProvider = "VRPInvalidSubmissionPayloadsDataProvider", - dataProviderClass = ConsentExtensionDataProvider.class) - public void testValidateVRPSubmissionForInvalidInstruction(String payload) throws ParseException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(payload); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - // Using the VRPInvalidSubmissionPayloadsDataProvider dataProvider five test scenarios are been tested. - // Relevant error messages will be returned respectively. - } - - @Test - public void testValidateVRPSubmissionWithInstructionRemittanceMismatch() throws ParseException, - ConsentManagementException { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentValidateTestConstants.VRP_INITIATION).when(detailedConsentResourceMock).getReceipt(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - - doReturn(getVRPConsentAttributes()).when(detailedConsentResourceMock).getConsentAttributes(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - doReturn(ConsentValidateTestConstants.VRP_PATH).when(consentValidateDataMock).getRequestPath(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.CONSENT_ID).when(consentValidateDataMock).getConsentId(); - JSONObject submissionPayload = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(ConsentValidateTestConstants.VRP_SUBMISSION_WITHOUT_REMITTANCE_INFO_MISMATCH); - doReturn(submissionPayload).when(consentValidateDataMock).getPayload(); - - doReturn(ConsentExtensionTestUtils.getConsentAttributes("vrp")) - .when(consentCoreServiceMock).getConsentAttributes(Mockito.anyString()); - doReturn(true).when(consentCoreServiceMock).deleteConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - doReturn(true).when(consentCoreServiceMock).storeConsentAttributes(Mockito.anyString(), - Mockito.>anyObject()); - - PowerMockito.mockStatic(ConsentServiceUtil.class); - PowerMockito.when(ConsentServiceUtil.getConsentService()).thenReturn(consentCoreServiceMock); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.REMITTANCE_INFO_MISMATCH); - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_CONSENT_MISMATCH); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - - @Test - public void testConsentValidateVRPvWithInvalidConsentId() { - - doReturn(authorizationResources).when(detailedConsentResourceMock).getAuthorizationResources(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(detailedConsentResourceMock).getClientID(); - doReturn(detailedConsentResourceMock).when(consentValidateDataMock).getComprehensiveConsent(); - doReturn(ConsentExtensionConstants.VRP).when(detailedConsentResourceMock).getConsentType(); - doReturn(ConsentExtensionConstants.AUTHORIZED_STATUS).when(detailedConsentResourceMock).getCurrentStatus(); - doReturn(ConsentValidateTestConstants.INVALID_CONSENT_ID).when(detailedConsentResourceMock).getConsentID(); - doReturn(ConsentExtensionTestConstants.VALID_INITIATION_OBJECT).when(detailedConsentResourceMock) - .getReceipt(); - doReturn(resourceParams).when(consentValidateDataMock).getResourceParams(); - doReturn(headers).when(consentValidateDataMock).getHeaders(); - doReturn(ConsentValidateTestConstants.USER_ID).when(consentValidateDataMock).getUserId(); - doReturn(ConsentValidateTestConstants.CLIENT_ID).when(consentValidateDataMock).getClientId(); - - ConsentValidationResult consentValidationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateDataMock, consentValidationResult); - - Assert.assertFalse(consentValidationResult.isValid()); - Assert.assertEquals(consentValidationResult.getErrorMessage(), ErrorConstants.MSG_INVALID_CONSENT_ID);; - Assert.assertEquals(consentValidationResult.getErrorCode(), ErrorConstants.RESOURCE_CONSENT_MISMATCH); - Assert.assertEquals(consentValidationResult.getHttpCode(), 400); - } - -} - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/resources/testng.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/resources/testng.xml deleted file mode 100644 index ddc3905f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.extensions/src/test/resources/testng.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/pom.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/pom.xml deleted file mode 100644 index bae5d5ee..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/pom.xml +++ /dev/null @@ -1,207 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.consent.dao - WSO2 Open Banking - Consent DAO - WSO2 Open Banking - Consent DAO Module - jar - - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.apache.commons - commons-lang3 - - - commons-dbcp - commons-dbcp - - - commons-logging - commons-logging - - - org.testng - testng - - - com.h2database - h2 - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - org.mockito - mockito-all - test - - - org.powermock - powermock-api-mockito - test - - - org.powermock - powermock-module-testng - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - target/jacoco.exec - - true - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - **/*Constants.class - **/*Component.class - **/*Exception.class - - **/ConsentStoreInitializer.class - **/ConsentRetentionDataStoreInitializer.class - **/MssqlConsentCoreDAOImpl.class - **/ConsentMgtMssqlDBQueries.class - **/OracleConsentCoreDAOImpl.class - **/ConsentMgtOracleDBQueries.class - **/ConsentMgtPostgresDBQueries.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - COMPLEXITY - COVEREDRATIO - 0.79 - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - false - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/ConsentCoreDAO.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/ConsentCoreDAO.java deleted file mode 100644 index bc6b66ed..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/ConsentCoreDAO.java +++ /dev/null @@ -1,506 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao; - - -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataDeletionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataInsertionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataUpdationException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; - -import java.sql.Connection; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This interface access the data storage layer to retrieve, store, delete and update consent management related. - * resources. - */ -public interface ConsentCoreDAO { - - /** - * This method is used to store the consent resource in the database. The request consent resource object must - * contain all data in it without the consent ID. A consent ID will be generated and set to the response object - * if the insertion is successful. - * - * @param connection connection object - * @param consentResource consent resource with all required data - * @return returns the consent resource with the consent ID and created time if insertion is successful - * @throws OBConsentDataInsertionException thrown if a database error occur or an insertion failure - */ - ConsentResource storeConsentResource(Connection connection, ConsentResource consentResource) - throws OBConsentDataInsertionException; - - /** - * This method is used to store the authorization resource in the database. The request authorization resource - * object must contain data all in it without the authorization ID and the updated time. Both of them will be - * generated and set to the response object if the insertion is successful. - * - * @param connection connection object - * @param authorizationResource authorization resource with all required data - * @return returns the authorization resource with the updated time if insertion is successful - * @throws OBConsentDataInsertionException thrown if a database error occur or an insertion failure - */ - AuthorizationResource storeAuthorizationResource(Connection connection, AuthorizationResource authorizationResource) - throws OBConsentDataInsertionException; - - /** - * This method is used to store the consent mapping resource in the database. The request consent mapping object - * must contain all the data in it without the consent mapping ID. It will be generated and set to the response - * object if the insertion is successful. - * - * @param connection connection object - * @param consentMappingResource consent mapping resource with all required data - * @return returns the consent mapping resource if the insertion is successful - * @throws OBConsentDataInsertionException thrown if a database error occur or an insertion failure - */ - ConsentMappingResource storeConsentMappingResource(Connection connection, - ConsentMappingResource consentMappingResource) - throws OBConsentDataInsertionException; - - /** - * This method is used to store the consent status audit record in the database. The request consent status audit - * record object must contain all the data in it without the status audit ID and actionTime. They will be generated - * and set to the response object if the insertion is successful. - * - * @param connection connection object - * @param consentStatusAuditRecord consent status audit record with all required data - * @return returns the consent status audit record if the insertion is successful - * @throws OBConsentDataInsertionException thrown if a database error occur or an insertion failure - */ - ConsentStatusAuditRecord storeConsentStatusAuditRecord(Connection connection, - ConsentStatusAuditRecord consentStatusAuditRecord) - throws OBConsentDataInsertionException; - - /** - * This method is used to store the consent attributes in the database. The request consent attributes object - * must be set with a consent ID and consent attribute map. - * - * @param connection connection object - * @param consentAttributes consent attributes object with consent ID and attributes map - * @return returns true if insertion is successful - * @throws OBConsentDataInsertionException thrown if a database error occur or an insertion failure - */ - boolean storeConsentAttributes(Connection connection, ConsentAttributes consentAttributes) - throws OBConsentDataInsertionException; - - /** - * This method is used to store the consent file in the database. The request consent file object must be set - * with a consent ID and the file that needed to be stored. - * - * @param connection connection object - * @param consentFileResource consent file resource with consent ID and the file content - * @return returns true if insertion is successful - * @throws OBConsentDataInsertionException thrown if a database error occur or an insertion failure - */ - boolean storeConsentFile(Connection connection, ConsentFile consentFileResource) - throws OBConsentDataInsertionException; - - /** - * This method is used to update the status of a consent resource. The request consent resource object must be - * set with a consent ID and the new consent status. - * - * @param connection connection object - * @param consentID consent ID of the consent needed to be updated - * @param consentStatus the new status that should be updated with - * @return returns the consent resource with the consent ID and the new status - * @throws OBConsentDataUpdationException thrown if a database error occur or an update failure - */ - ConsentResource updateConsentStatus(Connection connection, String consentID, String consentStatus) - throws OBConsentDataUpdationException; - - /** - * This method is used to update given consent mapping resources. All the mapping resources of provided mapping - * IDs will be updated with the new mapping status provided. - * - * @param connection connection object - * @param mappingIDs a list of mapping IDs that needed to be updated - * @param mappingStatus the new mapping status that should be updated with - * @return returns true if the update is successful - * @throws OBConsentDataUpdationException thrown if a database error occur or an update failure - */ - boolean updateConsentMappingStatus(Connection connection, ArrayList mappingIDs, - String mappingStatus) - throws OBConsentDataUpdationException; - - /** - * This method is used to update given consent mapping resource permissions. All the mapping resources of provided - * map will be updated with the new mapping permission provided. - * - * @param connection - Connection object - * @param mappingIDPermissionMap - A map of mapping IDs against new permissions - * @return - true if the update is successful - * @throws OBConsentDataUpdationException - Thrown of a database level error occurs - */ - boolean updateConsentMappingPermission(Connection connection, Map mappingIDPermissionMap) - throws OBConsentDataUpdationException; - - /** - * This method is used to update a given authorization object. The status of the authorization resource provided - * will be updated with the new status. - * - * @param connection connection object - * @param authorizationID authorization ID of the resource needed to be updated - * @param newAuthorizationStatus the new authorization status that should be updated with - * @return returns authorization resource with authorizationID, new status and updated time - * @throws OBConsentDataUpdationException thrown if a database error occur or an update failure - */ - AuthorizationResource updateAuthorizationStatus(Connection connection, String authorizationID, - String newAuthorizationStatus) - throws OBConsentDataUpdationException; - - /** - * This method is used for updating the user of a given authorization resource. The user ID of the authorization - * resource provided will be updated with the new user ID. - * - * @param connection connection object - * @param authorizationID authorization ID of the resource needed to be updated - * @param userID the new user ID that should be updated with - * @return returns authorization resource with authorization ID, user ID and updated time - * @throws OBConsentDataUpdationException thrown if a database error occur or an update failure - */ - AuthorizationResource updateAuthorizationUser(Connection connection, String authorizationID, String userID) - throws OBConsentDataUpdationException; - - /** - * This method is used to retrieve the consent file from the database. - * - * @param connection connection object - * @param consentID consent ID of the file needed to be retrieved - * @param fetchFromRetentionTables boolean value to fetch from retention tables (temporary purged data) - * @return returns the requested consent file resource - * @throws OBConsentDataRetrievalException thrown if a database error occur or an retrieval failure - */ - ConsentFile getConsentFile(Connection connection, String consentID, boolean fetchFromRetentionTables) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve the consent attributes from the database for given attribute keys. - * - * @param connection connection object - * @param consentID consent ID - * @param consentAttributeKeys the keys of the consent attributes that need to be retrieved - * @return returns the consent attributes that matches the provided consentID and consent attribute keys - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ConsentAttributes getConsentAttributes(Connection connection, String consentID, - ArrayList consentAttributeKeys) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve all the consent attributes from the database for the given consent ID. - * - * @param connection connection object - * @param consentID consent ID - * @return returns the consent attributes that matches the provided consentID and consent attribute keys - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ConsentAttributes getConsentAttributes(Connection connection, String consentID) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve consent attribute using the attribute name. - * - * @param connection connection object - * @param attributeName attribute name - * @return a map with the conesnt ID and the related attribute value - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - Map getConsentAttributesByName(Connection connection, String attributeName) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve consent id using the attribute name and value. - * - * @param connection connection object - * @param attributeName attribute name - * @param attributeValue attribute value - * @return Consent ID related to the given attribute key and value - * @throws OBConsentDataRetrievalException `thrown if a database error occurs - */ - ArrayList getConsentIdByConsentAttributeNameAndValue(Connection connection, String attributeName, - String attributeValue) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve a consent resource for the provided consent ID (without associated consent - * attributes). - * - * @param connection connection object - * @param consentID consent ID - * @return returns the consent resource related to the provided consent ID with additional consent attributes or - * not - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ConsentResource getConsentResource(Connection connection, String consentID) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve a detailed consent resource for the provided consent ID (includes - * authorization resources, account mapping resources and consent attributes). - * - * @param connection connection object - * @param consentID consent ID - * @param fetchFromRetentionTables boolean value to fetch from retention tables (temporary purged data) - * @return returns a detailed consent resource related to the provided consent ID - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - DetailedConsentResource getDetailedConsentResource(Connection connection, String consentID, - boolean fetchFromRetentionTables) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve a consent resource for the provided consent ID with associated attributes. - * - * @param connection connection object - * @param consentID consent ID - * @return returns the consent resource related to the provided consent ID with additional consent attributes or - * not - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ConsentResource getConsentResourceWithAttributes(Connection connection, String consentID) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve an authorization resource for the provided authorization ID. - * - * @param connection connection object - * @param authorizationID authorization ID - * @return the relevant authorization resource - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - AuthorizationResource getAuthorizationResource(Connection connection, String authorizationID) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve consent status audit records. It queries the consent audit records by the - * parameter that is provided. All parameters are optional. If no parameters are provided, all the records will - * be queried. - * - * @param connection connection object - * @param consentID consent ID - * @param currentStatus current status of the consent - * @param actionBy the user who performed the status update - * @param fromTime lower bound of the time of the needed records - * @param toTime upper bound of the time of the needed records - * @param statusAuditID status audit ID - * @param fetchFromRetentionTables boolean value to fetch from retention tables (temporary purged data) - * @return a list of retrieved audit records that matches the provided parameters - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ArrayList getConsentStatusAuditRecords(Connection connection, String consentID, - String currentStatus, String actionBy, - Long fromTime, Long toTime, - String statusAuditID, - boolean fetchFromRetentionTables) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve consent mapping resources for a given authorization ID. - * - * @param connection connection object - * @param authorizationID authorization ID - * @return a list of all consent mapping resources for the given authorization ID - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ArrayList getConsentMappingResources(Connection connection, String authorizationID) - throws OBConsentDataRetrievalException; - - /** - * This method is used to retrieve consent mapping resources for a given authorization ID and mapping status. - * - * @param connection connection object - * @param authorizationID authorization ID - * @param mappingStatus mapping status - * @return a list of all consent mapping resources for the given authorization ID - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ArrayList getConsentMappingResources(Connection connection, String authorizationID, - String mappingStatus) - throws OBConsentDataRetrievalException; - - /** - * This method is used to delete a given list of consent attributes. - * - * @param connection connection object - * @param consentID consent ID - * @param consentAttributeKeys a list of attribute keys that should be deleted - * @return true if the deletion is successful - * @throws OBConsentDataDeletionException thrown if a database error occurs - */ - boolean deleteConsentAttributes(Connection connection, String consentID, ArrayList consentAttributeKeys) - throws OBConsentDataDeletionException; - - /** - * This method is used to search detailed consents for the given lists of parameters. The search will be - * performed according to the provided input. Any list can contain any number of elements. The conjunctive result - * will be returned. If all lists are passed as null, all the consents related to other search parameters will be - * returned. "fromTime" and "toTime" are also optional. "limit" and "offset" are optional combined. If all - * parameters are null, all the consents will be returned. - * - * @param connection connection object - * @param consentIDs consent IDs optional list - * @param clientIDs client IDs optional list - * @param consentTypes consent types optional list - * @param consentStatuses consent statuses optional list - * @param userIDs user IDs optional list - * @param fromTime from time - * @param toTime to time - * @param limit limit - * @param offset offset - * @return a list of detailed consent resources according to the provided parameters or the list of all consents - * if all parameters are null - * @throws OBConsentDataRetrievalException thrown if any error occur - */ - ArrayList searchConsents(Connection connection, ArrayList consentIDs, - ArrayList clientIDs, ArrayList consentTypes, - ArrayList consentStatuses, ArrayList userIDs, - Long fromTime, Long toTime, Integer limit, Integer offset) - throws OBConsentDataRetrievalException; - - /** - * This method is used to search authorization resources using following optional parameters. If all the input - * parameters are null, all the relevant authorization resources will be returned. - * - * 1. Consent ID - * 2. User ID - * - * @param connection connection object - * @param consentID consent ID (optional) - * @param userID user ID (optional) - * @return a list of authorization resources - * @throws OBConsentDataRetrievalException thrown if an error occurs in the process - */ - ArrayList searchConsentAuthorizations(Connection connection, String consentID, String userID) - throws OBConsentDataRetrievalException; - - /** - * This method is used to update consent receipt. - * - * @param connection connection object - * @param consentID ID of the consent to be amended - * @param consentReceipt new consent receipt - * @throws OBConsentDataUpdationException thrown if an error occur in the process - */ - boolean updateConsentReceipt(Connection connection, String consentID, String consentReceipt) - throws OBConsentDataUpdationException; - - /** - * This method is used to update consent validity time. - * - * @param connection connection object - * @param consentID consent ID - * @param validityTime new validity time - * @return true if update successful - * @throws OBConsentDataUpdationException thrown if any error occurs in the process - */ - boolean updateConsentValidityTime(Connection connection, String consentID, long validityTime) - throws OBConsentDataUpdationException; - - /** - * This method is used to store the changed attribute values of the consent into consent history when an - * amendment happens to the consent. - * - * @param connection connection object - * @param historyID An identifier for consent history uniquely assigned per consent amendment - * @param timestamp The timestamp at which the consent amendment happened - * @param recordID Identifier for each history record (can be ConsentID or MappingID) - * @param consentDataType The consent data type stored in each history record (can be ConsentData, - * ConsentAttributesData or ConsentMappingData) - * @param changedAttributesJsonString The key-value pair json string that represents the changes - * relevant to each history record - * @param amendmentReason A string that indicates the reason that caused the amendment of the consent - * @return true if insertion successful - * @throws OBConsentDataInsertionException thrown if any error occurs in the process - */ - boolean storeConsentAmendmentHistory(Connection connection, String historyID, long timestamp, String recordID, - String consentDataType, String changedAttributesJsonString, String amendmentReason) - throws OBConsentDataInsertionException; - - /** - * This method is used to retrieve consent amendment history for a given consentID provided with its mappingIDs, - * AuthorizationIDs. - * - * @param connection connection object - * @param recordIDsList the list of recordIDs relevant to the consent (includes consentID, MappingIDs, AuthIDs) - * @return a comprehensive map of consent history data - * @throws OBConsentDataRetrievalException thrown if any error occurs in the process - */ - Map retrieveConsentAmendmentHistory(Connection connection, - List recordIDsList) throws OBConsentDataRetrievalException; - - /** - * This method is used to fetch consents which has a expiring time as a consent attribute - * (eligible for expiration). - * @throws OBConsentDataRetrievalException thrown if any error occurs in the process - */ - ArrayList getExpiringConsents(Connection connection, - String statusesEligibleForExpiration) - throws OBConsentDataRetrievalException; - - /** - * This method is used to delete the consent details completely from consent database. - * This include deletion of consent attributes, auth resources, consent mappings, audit records and consent file. - * - * @param connection connection object - * @param consentID consent ID - * @param executeOnRetentionTables boolean value to execute query on retention tables (temporary purged data) - * @return true if the deletion is successful - * @throws OBConsentDataDeletionException thrown if a database error occurs - */ - boolean deleteConsentData(Connection connection, String consentID, boolean executeOnRetentionTables) - throws OBConsentDataDeletionException; - - - /** - * This method is used to retrieve a list of consent_ids in consent table. - * - * @param connection connection object - * @param fetchFromRetentionTable boolean value to fetch from retention tables (temporary purged data) - * @return returns a list of consent_ids in consent table. - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ArrayList getListOfConsentIds(Connection connection, boolean fetchFromRetentionTable) - throws OBConsentDataRetrievalException; - - - /** - * This method is used to retrieve a list of consent status audit records by consent_ids. - * - * @param connection connection object - * @param consentIDs consentIDs - * @param fetchFromRetentionTable boolean value to fetch from retention tables (temporary purged data) - * @return returns a list of consent status audit records. - * @throws OBConsentDataRetrievalException thrown if a database error occurs - */ - ArrayList getConsentStatusAuditRecordsByConsentId(Connection connection, - ArrayList consentIDs, - Integer limit, Integer offset, - boolean fetchFromRetentionTable) - throws OBConsentDataRetrievalException; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/constants/ConsentMgtDAOConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/constants/ConsentMgtDAOConstants.java deleted file mode 100644 index 171e4910..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/constants/ConsentMgtDAOConstants.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.constants; - -/** - * This class contains all the constants needed for the consent management DAO layer. - */ -public class ConsentMgtDAOConstants { - - public static final String CONSENT_ID = "CONSENT_ID"; - public static final String CONSENT_FILE = "CONSENT_FILE"; - public static final String ATT_KEY = "ATT_KEY"; - public static final String ATT_VALUE = "ATT_VALUE"; - public static final String RECEIPT = "RECEIPT"; - public static final String CREATED_TIME = "CREATED_TIME"; - public static final String CONSENT_CREATED_TIME = "CONSENT_CREATED_TIME"; - public static final String CONSENT_UPDATED_TIME = "CONSENT_UPDATED_TIME"; - public static final String CLIENT_ID = "CLIENT_ID"; - public static final String CONSENT_TYPE = "CONSENT_TYPE"; - public static final String CURRENT_STATUS = "CURRENT_STATUS"; - public static final String CONSENT_FREQUENCY = "CONSENT_FREQUENCY"; - public static final String VALIDITY_TIME = "VALIDITY_TIME"; - public static final String RECURRING_INDICATOR = "RECURRING_INDICATOR"; - public static final String AUTH_ID = "AUTH_ID"; - public static final String AUTH_TYPE = "AUTH_TYPE"; - public static final String USER_ID = "USER_ID"; - public static final String AUTH_STATUS = "AUTH_STATUS"; - public static final String UPDATED_TIME = "UPDATED_TIME"; - public static final String AUTH_UPDATED_TIME = "AUTH_UPDATED_TIME"; - public static final String MAPPING_ID = "MAPPING_ID"; - public static final String ACCOUNT_ID = "ACCOUNT_ID"; - public static final String PERMISSION = "PERMISSION"; - public static final String MAPPING_STATUS = "MAPPING_STATUS"; - public static final String ACTION_BY = "ACTION_BY"; - public static final String ACTION_TIME = "ACTION_TIME"; - public static final String STATUS_AUDIT_ID = "STATUS_AUDIT_ID"; - public static final String PREVIOUS_STATUS = "PREVIOUS_STATUS"; - public static final String REASON = "REASON"; - public static final String EFFECTIVE_TIMESTAMP = "EFFECTIVE_TIMESTAMP"; - public static final String CONSENT_IDS = "consentIDs"; - public static final String CLIENT_IDS = "clientIDs"; - public static final String CONSENT_TYPES = "consentTypes"; - public static final String CONSENT_STATUSES = "consentStatuses"; - public static final String USER_IDS = "userIDs"; - public static final String IN = "inOperator"; - public static final String AND = "andOperator"; - public static final String OR = "orOperator"; - public static final String WHERE = "where"; - public static final String PLACEHOLDER = "placeholder"; - public static final String PLAIN_PLACEHOLDER = "plainPlaceholder"; - public static final String EQUALS = "equals"; - public static final String CONSENT_EXPIRY_TIME_ATTRIBUTE = "ExpirationDateTime"; - public static final String SESSION_DATA_KEY = "sessionDataKey"; - public static final String AUTH_MAPPING_ID = "AUTH_MAPPING_ID"; - - public static final String RETENTION_TABLE_NAME_PREFIX = "RET_"; - - public static final String CONSENT_MAPPING_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent mapping " + - "resources from the database"; - public static final String CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent " + - "attributes from the database for the given consent ID and attribute keys"; - public static final String NO_RECORDS_FOUND_ERROR_MSG = "No records are found for the given inputs"; - public static final String CONSENT_RESOURCE_STORE_ERROR_MSG = "Error occurred while storing consent resource in " + - "the database"; - public static final String AUTHORIZATION_RESOURCE_STORE_ERROR_MSG = "Error occurred while storing authorization " + - "resource in the database"; - public static final String CONSENT_MAPPING_RESOURCE_STORE_ERROR_MSG = "Error occurred while storing consent " + - "mapping resource in the database"; - public static final String AUDIT_RECORD_STORE_ERROR_MSG = "Error occurred while storing consent status audit " + - "record in the database"; - public static final String CONSENT_ATTRIBUTES_STORE_ERROR_MSG = "Error occurred while storing consent attributes " + - "in the database"; - public static final String CONSENT_FILE_STORE_ERROR_MSG = "Error occurred while storing consent file resource in " + - "the database"; - public static final String CONSENT_STATUS_UPDATE_ERROR_MSG = "Error occurred while updating consent status in the" + - " database"; - public static final String CONSENT_MAPPING_STATUS_UPDATE_ERROR_MSG = "Error occurred while updating consent " + - "mapping status in the database"; - public static final String CONSENT_MAPPING_PERMISSION_UPDATE_ERROR_MSG = "Error occurred while updating consent " + - "mapping permission in the database"; - public static final String CONSENT_AUTHORIZATION_STATUS_UPDATE_ERROR_MSG = "Error occurred while updating " + - "authorization status in the database"; - public static final String CONSENT_AUTHORIZATION_USER_UPDATE_ERROR_MSG = "Error occurred while updating " + - "authorization user in the database"; - public static final String CONSENT_FILE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent file " + - "resource from the database"; - public static final String CONSENT_RESOURCE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent " + - "resource from the database"; - public static final String DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving " + - "detailed consent resource from the database"; - public static final String CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving " + - "consent authorization resource from the database"; - public static final String AUDIT_RECORDS_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent status " + - "audit records"; - public static final String CONSENT_ATTRIBUTES_DELETE_ERROR_MSG = "Error occurred while deleting consent " + - "attributes in the database"; - public static final String CONSENT_DATA_DELETE_ERROR_MSG = "Error occurred while deleting the consent " + - "data in the database"; - public static final String CONSENT_SEARCH_ERROR_MSG = "Error occurred while searching consents"; - public static final String CONSENT_ID_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent id from the " + - "database for the given attribute key and attribute value"; - public static final String CONSENT_AMENDMENT_HISTORY_RETRIEVE_ERROR_MSG = "Error occurred while retrieving " + - "consent amendment history records from the database for the given consent ID"; - - // Consent Database Table Identifiers - public static final String TABLE_OB_CONSENT = "OB_CONSENT"; - public static final String TABLE_OB_CONSENT_AUTH_RESOURCE = "OB_CONSENT_AUTH_RESOURCE"; - public static final String TABLE_OB_CONSENT_MAPPING = "OB_CONSENT_MAPPING"; - public static final String TABLE_OB_CONSENT_ATTRIBUTE = "OB_CONSENT_ATTRIBUTE"; - public static final String TABLE_OB_CONSENT_FILE = "OB_CONSENT_FILE"; - - // Categorizations of the consent data according to the consent db tables to be used in CA history processing - public static final String TYPE_CONSENT_BASIC_DATA = "ConsentData"; - public static final String TYPE_CONSENT_AUTH_RESOURCE_DATA = "ConsentAuthResourceData"; - public static final String TYPE_CONSENT_ATTRIBUTES_DATA = "ConsentAttributesData"; - public static final String TYPE_CONSENT_MAPPING_DATA = "ConsentMappingData"; - - public static final String TABLE_ID = "TABLE_ID"; - public static final String RECORD_ID = "RECORD_ID"; - public static final String HISTORY_ID = "HISTORY_ID"; - public static final String CHANGED_VALUES = "CHANGED_VALUES"; - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataDeletionException.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataDeletionException.java deleted file mode 100644 index d4f7a08a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataDeletionException.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OBConsentDataDeletionException. - */ -public class OBConsentDataDeletionException extends OpenBankingException { - - public OBConsentDataDeletionException(String message) { - super(message); - } - - public OBConsentDataDeletionException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataInsertionException.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataInsertionException.java deleted file mode 100644 index 2ca03daf..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataInsertionException.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OBConsentDataInsertionException. - */ -public class OBConsentDataInsertionException extends OpenBankingException { - - public OBConsentDataInsertionException(String message) { - super(message); - } - - public OBConsentDataInsertionException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataRetrievalException.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataRetrievalException.java deleted file mode 100644 index 5db1399f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataRetrievalException.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OBConsentDataRetrievalException. - */ -public class OBConsentDataRetrievalException extends OpenBankingException { - - public OBConsentDataRetrievalException(String message) { - super(message); - } - - public OBConsentDataRetrievalException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataUpdationException.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataUpdationException.java deleted file mode 100644 index 80d31e73..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/exceptions/OBConsentDataUpdationException.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OBConsentDataUpdationException. - */ -public class OBConsentDataUpdationException extends OpenBankingException { - - public OBConsentDataUpdationException(String message) { - super(message); - } - - public OBConsentDataUpdationException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/ConsentCoreDAOImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/ConsentCoreDAOImpl.java deleted file mode 100644 index 9d225758..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/ConsentCoreDAOImpl.java +++ /dev/null @@ -1,2151 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.impl; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.ConsentCoreDAO; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataDeletionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataInsertionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataUpdationException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtCommonDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.utils.ConsentDAOUtils; -import net.minidev.json.JSONValue; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants.SESSION_DATA_KEY; - -/** - * This class only implements the data access methods for the consent management accelerator. It implements all the - * methods defined in the ConsentCoreDAO interface and is only responsible for reading and writing data from/to the - * database. The incoming data are pre-validated in the upper service layer. Therefore, no validations are done in - * this layer. - */ -public class ConsentCoreDAOImpl implements ConsentCoreDAO { - - private static Log log = LogFactory.getLog(ConsentCoreDAOImpl.class); - private static final String GROUP_BY_SEPARATOR = "\\|\\|"; - ConsentMgtCommonDBQueries sqlStatements; - //Numbers are assigned to each consent DB table & used as the reference for each table when storing CA history - static final Map TABLES_MAP = new HashMap() { - { - put(ConsentMgtDAOConstants.TABLE_OB_CONSENT, "01"); - put(ConsentMgtDAOConstants.TABLE_OB_CONSENT_AUTH_RESOURCE, "02"); - put(ConsentMgtDAOConstants.TABLE_OB_CONSENT_MAPPING, "03"); - put(ConsentMgtDAOConstants.TABLE_OB_CONSENT_ATTRIBUTE, "04"); - put(ConsentMgtDAOConstants.TABLE_OB_CONSENT_FILE, "05"); - } - }; - static final Map COLUMNS_MAP = new HashMap() { - { - put(ConsentMgtDAOConstants.CONSENT_IDS, "CONSENT_ID"); - put(ConsentMgtDAOConstants.CLIENT_IDS, "CLIENT_ID"); - put(ConsentMgtDAOConstants.CONSENT_TYPES, "CONSENT_TYPE"); - put(ConsentMgtDAOConstants.CONSENT_STATUSES, "CURRENT_STATUS"); - put(ConsentMgtDAOConstants.USER_IDS, "OCAR.USER_ID"); - } - }; - - public ConsentCoreDAOImpl(ConsentMgtCommonDBQueries sqlStatements) { - - this.sqlStatements = sqlStatements; - } - - @Override - public ConsentResource storeConsentResource(Connection connection, ConsentResource consentResource) - throws OBConsentDataInsertionException { - - int result; - String consentID = ""; - if (StringUtils.isEmpty(consentResource.getConsentID())) { - consentID = UUID.randomUUID().toString(); - } else { - consentID = consentResource.getConsentID(); - } - // Unix time in seconds - long createdTime; - if (consentResource.getCreatedTime() == 0) { - createdTime = System.currentTimeMillis() / 1000; - } else { - createdTime = consentResource.getCreatedTime(); - } - long updatedTime; - if (consentResource.getUpdatedTime() == 0) { - updatedTime = System.currentTimeMillis() / 1000; - } else { - updatedTime = consentResource.getUpdatedTime(); - } - String storeConsentPrepStatement = sqlStatements.getStoreConsentPreparedStatement(); - - try (PreparedStatement storeConsentPreparedStmt = connection.prepareStatement(storeConsentPrepStatement)) { - - log.debug("Setting parameters to prepared statement to store consent resource"); - - storeConsentPreparedStmt.setString(1, consentID); - storeConsentPreparedStmt.setString(2, consentResource.getReceipt()); - storeConsentPreparedStmt.setLong(3, createdTime); - storeConsentPreparedStmt.setLong(4, updatedTime); - storeConsentPreparedStmt.setString(5, consentResource.getClientID()); - storeConsentPreparedStmt.setString(6, consentResource.getConsentType()); - storeConsentPreparedStmt.setString(7, consentResource.getCurrentStatus()); - storeConsentPreparedStmt.setLong(8, consentResource.getConsentFrequency()); - storeConsentPreparedStmt.setLong(9, consentResource.getValidityPeriod()); - storeConsentPreparedStmt.setBoolean(10, consentResource.isRecurringIndicator()); - - // with result, we can determine whether the insertion was successful or not - result = storeConsentPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_RESOURCE_STORE_ERROR_MSG, e); - throw new OBConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_RESOURCE_STORE_ERROR_MSG, e); - } - - // Confirm that the data are inserted successfully - if (result > 0) { - log.debug("Stored the consent resource successfully"); - consentResource.setConsentID(consentID); - consentResource.setCreatedTime(createdTime); - consentResource.setUpdatedTime(createdTime); - return consentResource; - } else { - throw new OBConsentDataInsertionException("Failed to store consent data properly."); - } - } - - @Override - public AuthorizationResource storeAuthorizationResource(Connection connection, - AuthorizationResource authorizationResource) - throws OBConsentDataInsertionException { - - int result; - if (authorizationResource == null) { - throw new OBConsentDataInsertionException("Failed to store authorization resource due to null value."); - } - String authorizationID = UUID.randomUUID().toString(); - if (!StringUtils.isEmpty(authorizationResource.getAuthorizationID())) { - authorizationID = authorizationResource.getAuthorizationID(); - } - // Unix time in seconds - long updatedTime = System.currentTimeMillis() / 1000; - if (authorizationResource.getUpdatedTime() != 0) { - updatedTime = authorizationResource.getUpdatedTime(); - } - String storeAuthorizationPrepStatement = sqlStatements.getStoreAuthorizationPreparedStatement(); - - try (PreparedStatement storeAuthorizationPreparedStmt = - connection.prepareStatement(storeAuthorizationPrepStatement)) { - - log.debug("Setting parameters to prepared statement to store authorization resource"); - - storeAuthorizationPreparedStmt.setString(1, authorizationID); - storeAuthorizationPreparedStmt.setString(2, authorizationResource.getConsentID()); - storeAuthorizationPreparedStmt.setString(3, authorizationResource.getAuthorizationType()); - storeAuthorizationPreparedStmt.setString(4, authorizationResource.getUserID()); - storeAuthorizationPreparedStmt.setString(5, authorizationResource.getAuthorizationStatus()); - storeAuthorizationPreparedStmt.setLong(6, updatedTime); - - // with result, we can determine whether the insertion was successful or not - result = storeAuthorizationPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.AUTHORIZATION_RESOURCE_STORE_ERROR_MSG, e); - throw new OBConsentDataInsertionException(ConsentMgtDAOConstants.AUTHORIZATION_RESOURCE_STORE_ERROR_MSG, e); - } - - // Confirm that the data are inserted successfully - if (result > 0) { - log.debug("Stored the authorization resource successfully"); - authorizationResource.setAuthorizationID(authorizationID); - authorizationResource.setUpdatedTime(updatedTime); - return authorizationResource; - } else { - throw new OBConsentDataInsertionException("Failed to store authorization resource data properly."); - } - } - - @Override - public ConsentMappingResource storeConsentMappingResource(Connection connection, - ConsentMappingResource consentMappingResource) - throws OBConsentDataInsertionException { - - int result; - if (consentMappingResource == null) { - throw new OBConsentDataInsertionException("Failed to store consent mapping resource due to null value."); - } - String consentMappingID = UUID.randomUUID().toString(); - if (!StringUtils.isEmpty(consentMappingResource.getMappingID())) { - consentMappingID = consentMappingResource.getMappingID(); - } - String storeConsentMappingPrepStatement = sqlStatements.getStoreConsentMappingPreparedStatement(); - - try (PreparedStatement storeConsentMappingPreparedStmt = - connection.prepareStatement(storeConsentMappingPrepStatement)) { - - log.debug("Setting parameters to prepared statement to store consent mapping resource"); - - storeConsentMappingPreparedStmt.setString(1, consentMappingID); - storeConsentMappingPreparedStmt.setString(2, consentMappingResource.getAuthorizationID()); - storeConsentMappingPreparedStmt.setString(3, consentMappingResource.getAccountID()); - storeConsentMappingPreparedStmt.setString(4, consentMappingResource.getPermission()); - storeConsentMappingPreparedStmt.setString(5, consentMappingResource.getMappingStatus()); - - // with result, we can determine whether the insertion was successful or not - result = storeConsentMappingPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_RESOURCE_STORE_ERROR_MSG, e); - throw new OBConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_MAPPING_RESOURCE_STORE_ERROR_MSG, - e); - } - - // Confirm that the data are inserted successfully - if (result > 0) { - log.debug("Stored the consent mapping resource successfully"); - consentMappingResource.setMappingID(consentMappingID); - return consentMappingResource; - } else { - throw new OBConsentDataInsertionException("Failed to store consent mapping resource data properly."); - } - } - - @Override - public ConsentStatusAuditRecord storeConsentStatusAuditRecord(Connection connection, - ConsentStatusAuditRecord consentStatusAuditRecord) - throws OBConsentDataInsertionException { - - int result; - if (consentStatusAuditRecord == null) { - throw new OBConsentDataInsertionException("Failed to store consent audit record due to null value."); - } - String statusAuditID = UUID.randomUUID().toString(); - if (!StringUtils.isEmpty(consentStatusAuditRecord.getStatusAuditID())) { - statusAuditID = consentStatusAuditRecord.getStatusAuditID(); - } - // Unix time in seconds - long actionTime = System.currentTimeMillis() / 1000; - if (consentStatusAuditRecord.getActionTime() != 0) { - actionTime = consentStatusAuditRecord.getActionTime(); - } - String storeConsentStatusAuditRecordPrepStatement = - sqlStatements.getStoreConsentStatusAuditRecordPreparedStatement(); - - try (PreparedStatement storeConsentStatusAuditRecordPreparedStmt = - connection.prepareStatement(storeConsentStatusAuditRecordPrepStatement)) { - - log.debug("Setting parameters to prepared statement to store consent audit record"); - - storeConsentStatusAuditRecordPreparedStmt.setString(1, statusAuditID); - storeConsentStatusAuditRecordPreparedStmt.setString(2, consentStatusAuditRecord - .getConsentID()); - storeConsentStatusAuditRecordPreparedStmt.setString(3, consentStatusAuditRecord - .getCurrentStatus()); - storeConsentStatusAuditRecordPreparedStmt.setLong(4, actionTime); - storeConsentStatusAuditRecordPreparedStmt.setString(5, consentStatusAuditRecord.getReason()); - storeConsentStatusAuditRecordPreparedStmt.setString(6, consentStatusAuditRecord - .getActionBy()); - storeConsentStatusAuditRecordPreparedStmt.setString(7, consentStatusAuditRecord - .getPreviousStatus()); - - // with result, we can determine whether the insertion was successful or not - result = storeConsentStatusAuditRecordPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.AUDIT_RECORD_STORE_ERROR_MSG, e); - throw new OBConsentDataInsertionException(ConsentMgtDAOConstants.AUDIT_RECORD_STORE_ERROR_MSG, e); - } - - // Confirm that the data are inserted successfully - if (result > 0) { - log.debug("Stored the consent status audit record successfully"); - consentStatusAuditRecord.setStatusAuditID(statusAuditID); - consentStatusAuditRecord.setActionTime(actionTime); - return consentStatusAuditRecord; - } else { - throw new OBConsentDataInsertionException("Failed to store consent status audit record data properly."); - } - } - - @Override - public boolean storeConsentAttributes(Connection connection, ConsentAttributes consentAttributes) - throws OBConsentDataInsertionException { - - int[] result; - String storeConsentAttributesPrepStatement = sqlStatements.getStoreConsentAttributesPreparedStatement(); - Map consentAttributesMap = consentAttributes.getConsentAttributes(); - - try (PreparedStatement storeConsentAttributesPreparedStmt = - connection.prepareStatement(storeConsentAttributesPrepStatement)) { - - for (Map.Entry entry : consentAttributesMap.entrySet()) { - storeConsentAttributesPreparedStmt.setString(1, consentAttributes.getConsentID()); - storeConsentAttributesPreparedStmt.setString(2, entry.getKey()); - storeConsentAttributesPreparedStmt.setString(3, entry.getValue()); - storeConsentAttributesPreparedStmt.addBatch(); - } - - // with result, we can determine whether the updating was successful or not - result = storeConsentAttributesPreparedStmt.executeBatch(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_STORE_ERROR_MSG, e); - throw new OBConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_STORE_ERROR_MSG, e); - } - - /* - An empty array or an array with value -3 means the batch execution is failed. - If an array contains value -2, it means the command completed successfully but the number of rows affected - are unknown. Therefore, only checking for the existence of -3. - */ - if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { - log.debug("Stored the consent attributes successfully"); - return true; - } else { - throw new OBConsentDataInsertionException("Failed to store consent attribute data properly."); - } - } - - @Override - public boolean storeConsentFile(Connection connection, ConsentFile consentFileResource) - throws OBConsentDataInsertionException { - - int result; - String storeConsentMappingPrepStatement = sqlStatements.getStoreConsentFilePreparedStatement(); - - try (PreparedStatement storeConsentFilePreparedStmt = - connection.prepareStatement(storeConsentMappingPrepStatement)) { - - log.debug("Setting parameters to prepared statement to store consent file resource"); - - storeConsentFilePreparedStmt.setString(1, consentFileResource.getConsentID()); - storeConsentFilePreparedStmt.setString(2, consentFileResource.getConsentFile()); - - // with result, we can determine whether the insertion was successful or not - result = storeConsentFilePreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_FILE_STORE_ERROR_MSG, e); - throw new OBConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_FILE_STORE_ERROR_MSG, e); - } - - // Confirm that the data are inserted successfully - if (result > 0) { - log.debug("Stored the consent file resource successfully"); - return true; - } else { - throw new OBConsentDataInsertionException("Failed to store consent file resource data properly."); - } - } - - @Override - public ConsentResource updateConsentStatus(Connection connection, String consentID, String newConsentStatus) - throws OBConsentDataUpdationException { - - int result; - long updatedTime = System.currentTimeMillis() / 1000; - ConsentResource consentResource = new ConsentResource(); - String updateConsentStatusPrepStatement = sqlStatements.getUpdateConsentStatusPreparedStatement(); - - try (PreparedStatement updateConsentStatusPreparedStmt = - connection.prepareStatement(updateConsentStatusPrepStatement)) { - - log.debug("Setting parameters to prepared statement to update consent status"); - - updateConsentStatusPreparedStmt.setString(1, newConsentStatus); - updateConsentStatusPreparedStmt.setLong(2, updatedTime); - updateConsentStatusPreparedStmt.setString(3, consentID); - - // with result, we can determine whether the updating was successful or not - result = updateConsentStatusPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_STATUS_UPDATE_ERROR_MSG, e); - throw new OBConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_STATUS_UPDATE_ERROR_MSG, e); - } - - // Confirm that the data are updated successfully - if (result > 0) { - log.debug("Updated the consent status successfully"); - consentResource.setConsentID(consentID); - consentResource.setCurrentStatus(newConsentStatus); - return consentResource; - } else { - throw new OBConsentDataUpdationException("Failed to update consent status properly."); - } - } - - @Override - public boolean updateConsentMappingStatus(Connection connection, ArrayList mappingIDs, String mappingStatus) - throws OBConsentDataUpdationException { - - int[] result; - String updateConsentMappingStatusPrepStatement = sqlStatements.getUpdateConsentMappingStatusPreparedStatement(); - - try (PreparedStatement updateConsentMappingStatusPreparedStmt = - connection.prepareStatement(updateConsentMappingStatusPrepStatement)) { - - log.debug("Setting parameters to prepared statement to update consent mapping status"); - - for (String mappingID : mappingIDs) { - updateConsentMappingStatusPreparedStmt.setString(1, mappingStatus); - updateConsentMappingStatusPreparedStmt.setString(2, mappingID); - updateConsentMappingStatusPreparedStmt.addBatch(); - } - - // with result, we can determine whether the updating was successful or not - result = updateConsentMappingStatusPreparedStmt.executeBatch(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_STATUS_UPDATE_ERROR_MSG, e); - throw new OBConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_MAPPING_STATUS_UPDATE_ERROR_MSG, e); - } - - // An empty array or an array with value -3 means the batch execution is failed - if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { - log.debug("Updated the consent mapping statuses of matching records successfully"); - return true; - } else { - throw new OBConsentDataUpdationException("Failed to update consent mapping status properly."); - } - } - - @Override - public boolean updateConsentMappingPermission(Connection connection, Map mappingIDPermissionMap) - throws OBConsentDataUpdationException { - - int[] result; - String updateConsentMappingPermissionQuery = - sqlStatements.getUpdateConsentMappingPermissionPreparedStatement(); - - try (PreparedStatement updateConsentMappingPermissionPreparedStmt = - connection.prepareStatement(updateConsentMappingPermissionQuery)) { - - log.debug("Setting parameters to prepared statement to update consent mapping permissions"); - - for (String mappingID : mappingIDPermissionMap.keySet()) { - updateConsentMappingPermissionPreparedStmt.setString(1, mappingIDPermissionMap.get(mappingID)); - updateConsentMappingPermissionPreparedStmt.setString(2, mappingID); - updateConsentMappingPermissionPreparedStmt.addBatch(); - } - - // With result, we can determine whether the updating was successful or not - result = updateConsentMappingPermissionPreparedStmt.executeBatch(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_PERMISSION_UPDATE_ERROR_MSG, e); - throw new OBConsentDataUpdationException( - ConsentMgtDAOConstants.CONSENT_MAPPING_PERMISSION_UPDATE_ERROR_MSG, e); - } - - // An empty array or an array with value -3 means the batch execution is failed - if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { - log.debug("Updated the consent mapping permissions of matching records successfully"); - return true; - } else { - throw new OBConsentDataUpdationException("Failed to update consent mapping permissions properly."); - } - } - - @Override - public AuthorizationResource updateAuthorizationStatus(Connection connection, String authorizationID, - String newAuthorizationStatus) - throws OBConsentDataUpdationException { - - int result; - - // Unix time in seconds - long updatedTime = System.currentTimeMillis() / 1000; - String updateAuthorizationStatusPrepStatement = sqlStatements.getUpdateAuthorizationStatusPreparedStatement(); - - try (PreparedStatement updateAuthorizationStatusPreparedStmt = - connection.prepareStatement(updateAuthorizationStatusPrepStatement)) { - - log.debug("Setting parameters to prepared statement to update authorization status"); - - updateAuthorizationStatusPreparedStmt.setString(1, newAuthorizationStatus); - updateAuthorizationStatusPreparedStmt.setLong(2, updatedTime); - updateAuthorizationStatusPreparedStmt.setString(3, authorizationID); - - // with result, we can determine whether the updating was successful or not - result = updateAuthorizationStatusPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_STATUS_UPDATE_ERROR_MSG, e); - throw new OBConsentDataUpdationException(ConsentMgtDAOConstants - .CONSENT_AUTHORIZATION_STATUS_UPDATE_ERROR_MSG, e); - } - - // Confirm that the data are updated successfully - if (result > 0) { - log.debug("Updated the authorization status successfully"); - AuthorizationResource authorizationResource = new AuthorizationResource(); - - authorizationResource.setAuthorizationStatus(newAuthorizationStatus); - authorizationResource.setAuthorizationID(authorizationID); - authorizationResource.setUpdatedTime(updatedTime); - return authorizationResource; - } else { - throw new OBConsentDataUpdationException("Failed to update consent status properly."); - } - } - - @Override - public AuthorizationResource updateAuthorizationUser(Connection connection, String authorizationID, String userID) - throws OBConsentDataUpdationException { - - int result; - - // Unix time in seconds - long updatedTime = System.currentTimeMillis() / 1000; - String updateAuthorizationUserPrepStatement = sqlStatements.getUpdateAuthorizationUserPreparedStatement(); - - try (PreparedStatement updateAuthorizationUserPreparedStmt = - connection.prepareStatement(updateAuthorizationUserPrepStatement)) { - - log.debug("Setting parameters to prepared statement to update authorization user"); - - updateAuthorizationUserPreparedStmt.setString(1, userID); - updateAuthorizationUserPreparedStmt.setLong(2, updatedTime); - updateAuthorizationUserPreparedStmt.setString(3, authorizationID); - - // with result, we can determine whether the updating was successful or not - result = updateAuthorizationUserPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_USER_UPDATE_ERROR_MSG, e); - throw new OBConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_USER_UPDATE_ERROR_MSG, - e); - } - - // Confirm that the data are updated successfully - if (result > 0) { - log.debug("Updated the authorization user successfully"); - AuthorizationResource authorizationResource = new AuthorizationResource(); - - authorizationResource.setUserID(userID); - authorizationResource.setAuthorizationID(authorizationID); - authorizationResource.setUpdatedTime(updatedTime); - return authorizationResource; - } else { - throw new OBConsentDataUpdationException("Failed to update authorization user properly."); - } - } - - @Override - public ConsentFile getConsentFile(Connection connection, String consentID, boolean fetchFromRetentionTables) - throws OBConsentDataRetrievalException { - - ConsentFile receivedConsentFileResource = new ConsentFile(); - String getConsentFilePrepStatement = sqlStatements.getGetConsentFileResourcePreparedStatement( - fetchFromRetentionTables); - - try (PreparedStatement getConsentFileResourcePreparedStmt = - connection.prepareStatement(getConsentFilePrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent file resource"); - - getConsentFileResourcePreparedStmt.setString(1, consentID); - - try (ResultSet resultSet = getConsentFileResourcePreparedStmt.executeQuery()) { - if (resultSet.next()) { - String storedConsentID = resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID); - String consentFile = resultSet.getString(ConsentMgtDAOConstants.CONSENT_FILE); - - receivedConsentFileResource.setConsentID(storedConsentID); - receivedConsentFileResource.setConsentFile(consentFile); - } else { - log.error("No records are found for consent ID :" + consentID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent file resource"); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent file" + - " resource for consent ID : %s", consentID), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent file resource for consent ID : " + consentID); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_FILE_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_FILE_RETRIEVE_ERROR_MSG, e); - } - return receivedConsentFileResource; - } - - @Override - public ConsentAttributes getConsentAttributes(Connection connection, String consentID, - ArrayList consentAttributeKeys) - throws OBConsentDataRetrievalException { - - Map retrievedConsentAttributesMap = new HashMap<>(); - ConsentAttributes retrievedConsentAttributesResource; - String getConsentAttributesPrepStatement = sqlStatements.getGetConsentAttributesPreparedStatement(); - - try (PreparedStatement getConsentAttributesPreparedStmt = - connection.prepareStatement(getConsentAttributesPrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent attributes"); - - getConsentAttributesPreparedStmt.setString(1, consentID); - - try (ResultSet resultSet = getConsentAttributesPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - String attributeKey = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY); - String attributeValue = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE); - - // Filter the needed attributes - if (consentAttributeKeys.contains(attributeKey)) { - retrievedConsentAttributesMap.put(attributeKey, attributeValue); - if (retrievedConsentAttributesMap.size() == consentAttributeKeys.size()) { - break; - } - } - } - retrievedConsentAttributesResource = new ConsentAttributes(); - retrievedConsentAttributesResource.setConsentID(consentID); - retrievedConsentAttributesResource.setConsentAttributes(retrievedConsentAttributesMap); - } else { - log.error("No records are found for consent ID : " + consentID + " and consent attribute keys"); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent attributes", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "attributes for consent ID : %s and provided consent attributes", consentID), e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentAttributesResource; - } - - @Override - public ConsentAttributes getConsentAttributes(Connection connection, String consentID) - throws OBConsentDataRetrievalException { - - Map retrievedConsentAttributesMap = new HashMap<>(); - ConsentAttributes retrievedConsentAttributesResource; - String getConsentAttributesPrepStatement = sqlStatements.getGetConsentAttributesPreparedStatement(); - - try (PreparedStatement getConsentAttributesPreparedStmt = - connection.prepareStatement(getConsentAttributesPrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent attributes"); - - getConsentAttributesPreparedStmt.setString(1, consentID); - - try (ResultSet resultSet = getConsentAttributesPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - retrievedConsentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), - resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE)); - } - retrievedConsentAttributesResource = new ConsentAttributes(); - retrievedConsentAttributesResource.setConsentID(consentID); - retrievedConsentAttributesResource.setConsentAttributes(retrievedConsentAttributesMap); - } else { - log.error("No records are found for consent ID :" + consentID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent attributes", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "attributes for consent ID : %s", consentID), e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentAttributesResource; - } - - @Override - public Map getConsentAttributesByName(Connection connection, String attributeName) - throws OBConsentDataRetrievalException { - - Map retrievedConsentAttributesMap = new HashMap<>(); - String getConsentAttributesByNamePrepStatement = sqlStatements.getGetConsentAttributesByNamePreparedStatement(); - - try (PreparedStatement getConsentAttributesByNamePreparedStmt = - connection.prepareStatement(getConsentAttributesByNamePrepStatement)) { - - if (log.isDebugEnabled()) { - log.debug("Setting parameters to prepared statement to retrieve consent attributes for the provided " + - "key: " + attributeName); - } - getConsentAttributesByNamePreparedStmt.setString(1, attributeName); - - try (ResultSet resultSet = getConsentAttributesByNamePreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - retrievedConsentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID), - resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE)); - } - } - } catch (SQLException e) { - log.error("Error occurred while reading consent attributes for the given key: " - + attributeName, e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "attributes for attribute key: %s", attributeName), e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentAttributesMap; - } - - @Override - public ArrayList getConsentIdByConsentAttributeNameAndValue(Connection connection, String attributeName, - String attributeValue) - throws OBConsentDataRetrievalException { - - ArrayList retrievedConsentIdList = new ArrayList<>(); - String getConsentIdByConsentAttributeNameAndValuePrepStatement = sqlStatements - .getConsentIdByConsentAttributeNameAndValuePreparedStatement(); - - try (PreparedStatement getConsentAttributesByNamePreparedStmt = - connection.prepareStatement(getConsentIdByConsentAttributeNameAndValuePrepStatement)) { - - if (log.isDebugEnabled()) { - log.debug("Setting parameters to prepared statement to retrieve consent id for the provided " + - "key: " + attributeName + " and value: " + attributeValue); - } - getConsentAttributesByNamePreparedStmt.setString(1, attributeName); - getConsentAttributesByNamePreparedStmt.setString(2, attributeValue); - - try (ResultSet resultSet = getConsentAttributesByNamePreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - retrievedConsentIdList.add(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - } - } else { - log.error("No records are found for the provided attribute key :" + attributeName + - " and value: " + attributeValue); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent attributes for the given key: " + attributeName + - " and value: " + attributeValue); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "attributes for attribute key: %s and value: %s", attributeName, attributeValue), e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ID_RETRIEVE_ERROR_MSG); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ID_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentIdList; - } - - @Override - public ConsentResource getConsentResource(Connection connection, String consentID) - throws OBConsentDataRetrievalException { - - ConsentResource retrievedConsentResource = new ConsentResource(); - - String getConsentResourcePrepStatement = sqlStatements.getGetConsentPreparedStatement(); - - try (PreparedStatement getConsentResourcePreparedStmt = - connection.prepareStatement(getConsentResourcePrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent resource"); - - getConsentResourcePreparedStmt.setString(1, consentID); - - try (ResultSet resultSet = getConsentResourcePreparedStmt.executeQuery()) { - if (resultSet.next()) { - setDataToConsentResource(resultSet, retrievedConsentResource); - } else { - log.error("No records are found for consent ID :" + consentID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent resource", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "resource for consent ID : %s", consentID), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent resource from OB_CONSENT table for consent ID : " + consentID); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentResource; - } - - @Override - public DetailedConsentResource getDetailedConsentResource(Connection connection, String consentID, - boolean fetchFromRetentionTables) - throws OBConsentDataRetrievalException { - - DetailedConsentResource retrievedDetailedConsentResource = new DetailedConsentResource(); - - String getDetailedConsentResourcePrepStatement = sqlStatements.getGetDetailedConsentPreparedStatement( - fetchFromRetentionTables); - - try (PreparedStatement getDetailedConsentResourcePreparedStmt = connection - .prepareStatement(getDetailedConsentResourcePrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve detailed consent resource"); - - getDetailedConsentResourcePreparedStmt.setString(1, consentID); - - try (ResultSet resultSet = getDetailedConsentResourcePreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - setDataToDetailedConsentResource(resultSet, retrievedDetailedConsentResource); - } else { - log.error("No records are found for consent ID :" + consentID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading detailed consent resource", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving " + - "detailed consent resource for consent ID : %s", consentID), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the detailed consent resource for consent ID : " + - consentID); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants - .DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); - } - return retrievedDetailedConsentResource; - } - - @Override - public ConsentResource getConsentResourceWithAttributes(Connection connection, String consentID) - throws OBConsentDataRetrievalException { - - Map retrievedConsentAttributeMap = new HashMap<>(); - ConsentResource retrievedConsentResource = new ConsentResource(); - - String getConsentResourcePrepStatement = sqlStatements.getGetConsentWithConsentAttributesPreparedStatement(); - - try (PreparedStatement getConsentResourcePreparedStmt = - connection.prepareStatement(getConsentResourcePrepStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY)) { - - log.debug("Setting parameters to prepared statement to retrieve consent resource with consent attributes"); - - getConsentResourcePreparedStmt.setString(1, consentID); - - try (ResultSet resultSet = getConsentResourcePreparedStmt.executeQuery()) { - if (resultSet.next()) { - setDataToConsentResource(resultSet, retrievedConsentResource); - - // Point the cursor to the beginning of the result set to read attributes - resultSet.beforeFirst(); - while (resultSet.next()) { - retrievedConsentAttributeMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), - resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE)); - } - retrievedConsentResource.setConsentAttributes(retrievedConsentAttributeMap); - } else { - log.error("No records are found for consent ID :" + consentID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent resource with consent attributes", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "resource with consent attributes for consent ID : %s", consentID), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent resource with consent attributes for consent ID : " + consentID); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentResource; - } - - @Override - public AuthorizationResource getAuthorizationResource(Connection connection, String authorizationID) - throws OBConsentDataRetrievalException { - - AuthorizationResource retrievedAuthorizationResource = new AuthorizationResource(); - String getAuthorizationResourcePrepStatement = sqlStatements.getGetAuthorizationResourcePreparedStatement(); - - try (PreparedStatement getConsentResourcePreparedStmt = - connection.prepareStatement(getAuthorizationResourcePrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent authorization resource"); - - getConsentResourcePreparedStmt.setString(1, authorizationID); - - try (ResultSet resultSet = getConsentResourcePreparedStmt.executeQuery()) { - if (resultSet.next()) { - setAuthorizationData(retrievedAuthorizationResource, resultSet); - } else { - log.error("No records are found for authorization ID :" + authorizationID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent authorization resource", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "authorization resource for authorization ID : %s", authorizationID), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent authorization resource for authorization ID : " + authorizationID); - } - - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants. - CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); - } - return retrievedAuthorizationResource; - } - - @Override - public ArrayList getConsentStatusAuditRecords(Connection connection, String consentID, - String currentStatus, String actionBy, - Long fromTime, Long toTime, - String statusAuditID, - boolean fetchFromRetentionTables) - throws OBConsentDataRetrievalException { - - ArrayList retrievedAuditRecords = new ArrayList<>(); - String getConsentStatusAuditRecordsPrepStatement = - sqlStatements.getGetConsentStatusAuditRecordsPreparedStatement(fetchFromRetentionTables); - - try (PreparedStatement getConsentStatusAuditRecordPreparedStmt = - connection.prepareStatement(getConsentStatusAuditRecordsPrepStatement)) { - - if (log.isDebugEnabled()) { - log.debug("Setting parameters to prepared statement to retrieve consent status audit records"); - } - - // consentID - if (StringUtils.trimToNull(consentID) != null) { - getConsentStatusAuditRecordPreparedStmt.setString(1, consentID); - } else { - getConsentStatusAuditRecordPreparedStmt.setNull(1, Types.VARCHAR); - } - - // currentStatus - if (StringUtils.trimToNull(currentStatus) != null) { - getConsentStatusAuditRecordPreparedStmt.setString(2, currentStatus); - } else { - getConsentStatusAuditRecordPreparedStmt.setNull(2, Types.VARCHAR); - } - - // actionBy - if (StringUtils.trimToNull(actionBy) != null) { - getConsentStatusAuditRecordPreparedStmt.setString(3, actionBy); - } else { - getConsentStatusAuditRecordPreparedStmt.setNull(3, Types.VARCHAR); - } - - // statusAuditID - if (StringUtils.trimToNull(statusAuditID) != null) { - getConsentStatusAuditRecordPreparedStmt.setString(4, statusAuditID); - } else { - getConsentStatusAuditRecordPreparedStmt.setNull(4, Types.VARCHAR); - } - - // fromTime - if (fromTime != null) { - getConsentStatusAuditRecordPreparedStmt.setLong(5, fromTime); - } else { - getConsentStatusAuditRecordPreparedStmt.setNull(5, Types.BIGINT); - } - - // toTime - if (toTime != null) { - getConsentStatusAuditRecordPreparedStmt.setLong(6, toTime); - } else { - getConsentStatusAuditRecordPreparedStmt.setNull(6, Types.BIGINT); - } - - try (ResultSet resultSet = getConsentStatusAuditRecordPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord - .setStatusAuditID(resultSet.getString(ConsentMgtDAOConstants.STATUS_AUDIT_ID)); - consentStatusAuditRecord.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - consentStatusAuditRecord - .setCurrentStatus(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS)); - consentStatusAuditRecord.setActionBy(resultSet.getString(ConsentMgtDAOConstants.ACTION_BY)); - consentStatusAuditRecord.setActionTime(resultSet.getLong(ConsentMgtDAOConstants.ACTION_TIME)); - consentStatusAuditRecord.setReason(resultSet.getString(ConsentMgtDAOConstants.REASON)); - consentStatusAuditRecord - .setPreviousStatus(resultSet.getString(ConsentMgtDAOConstants.PREVIOUS_STATUS)); - retrievedAuditRecords.add(consentStatusAuditRecord); - } - } else { - log.error("No records are found for the provided inputs"); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent status audit records", e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); - } - - log.debug("Retrieved the consent status audit records successfully"); - - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); - } - return retrievedAuditRecords; - } - - @Override - public ArrayList getConsentMappingResources(Connection connection, String authorizationID) - throws OBConsentDataRetrievalException { - - ArrayList retrievedConsentMappingResources = new ArrayList<>(); - String getMappingResourcePrepStatement = sqlStatements.getGetConsentMappingResourcesPreparedStatement(); - - try (PreparedStatement getConsentMappingResourcePreparedStmt = - connection.prepareStatement(getMappingResourcePrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent mapping resources"); - - getConsentMappingResourcePreparedStmt.setString(1, authorizationID); - - try (ResultSet resultSet = getConsentMappingResourcePreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - retrievedConsentMappingResources.add(getConsentMappingResourceWithData(resultSet)); - } - } else { - log.error("No records are found for authorization ID : " + authorizationID); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent mapping resources", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "mapping resources for authorization ID : %s", authorizationID), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent mapping resources for authorization ID : " + authorizationID); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_MAPPING_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentMappingResources; - } - - @Override - public ArrayList getConsentMappingResources(Connection connection, String authorizationID, - String mappingStatus) - throws OBConsentDataRetrievalException { - - ArrayList retrievedConsentMappingResources = new ArrayList<>(); - String getMappingResourcePrepStatement - = sqlStatements.getGetConsentMappingResourcesForStatusPreparedStatement(); - - try (PreparedStatement getConsentMappingResourcePreparedStmt = - connection.prepareStatement(getMappingResourcePrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent mapping resources"); - - getConsentMappingResourcePreparedStmt.setString(1, authorizationID); - getConsentMappingResourcePreparedStmt.setString(2, mappingStatus); - - try (ResultSet resultSet = getConsentMappingResourcePreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - retrievedConsentMappingResources.add(getConsentMappingResourceWithData(resultSet)); - } - } else { - log.error("No records are found for authorization ID : " + authorizationID + " and mapping " + - "status " + mappingStatus); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent mapping resources", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "mapping resources for authorization ID : %s and mapping status : %s", authorizationID, - mappingStatus), e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent mapping resources for authorization ID : " + authorizationID + " and" + - " mapping status : " + mappingStatus); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_MAPPING_RETRIEVE_ERROR_MSG, e); - } - return retrievedConsentMappingResources; - } - - @Override - public boolean deleteConsentAttributes(Connection connection, String consentID, - ArrayList consentAttributeKeys) - throws OBConsentDataDeletionException { - - int[] result; - String deleteConsentAttributePrepStatement = sqlStatements.getDeleteConsentAttributePreparedStatement(); - - try (PreparedStatement deleteConsentAttributesPreparedStmt = - connection.prepareStatement(deleteConsentAttributePrepStatement)) { - - if (log.isDebugEnabled()) { - log.debug("Setting parameters to prepared statement to delete the provided consent attributes"); - } - - for (String key : consentAttributeKeys) { - deleteConsentAttributesPreparedStmt.setString(1, consentID); - deleteConsentAttributesPreparedStmt.setString(2, key); - deleteConsentAttributesPreparedStmt.addBatch(); - } - - result = deleteConsentAttributesPreparedStmt.executeBatch(); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG, e); - throw new OBConsentDataDeletionException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG, e); - } - - if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { - if (log.isDebugEnabled()) { - log.debug("Deleted the consent attribute of key " + consentAttributeKeys); - } - return true; - } else { - throw new OBConsentDataDeletionException("Failed to delete consent attribute properly."); - } - } - - @Override - public ArrayList searchConsents(Connection connection, ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, Long toTime, - Integer limit, Integer offset) - throws OBConsentDataRetrievalException { - - boolean shouldLimit = true; - boolean shouldOffset = true; - int parameterIndex = 0; - Map applicableConditionsMap = new HashMap<>(); - - validateAndSetSearchConditions(applicableConditionsMap, consentIDs, clientIDs, consentTypes, consentStatuses); - - // Don't limit if either of limit or offset is null - if (limit == null) { - shouldLimit = false; - } - if (offset == null) { - shouldOffset = false; - } - - // logic to set the prepared statement - log.debug("Constructing the prepared statement"); - String constructedConditions = - ConsentDAOUtils.constructConsentSearchPreparedStatement(applicableConditionsMap); - - String userIDFilterCondition = ""; - Map userIdMap = new HashMap<>(); - if (CollectionUtils.isNotEmpty(userIDs)) { - userIdMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.USER_IDS), userIDs); - userIDFilterCondition = ConsentDAOUtils.constructUserIdListFilterCondition(userIdMap); - } - - String searchConsentsPreparedStatement = - sqlStatements.getSearchConsentsPreparedStatement(constructedConditions, shouldLimit, shouldOffset, - userIDFilterCondition); - - try (PreparedStatement searchConsentsPreparedStmt = - connection.prepareStatement(searchConsentsPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_UPDATABLE)) { - - /* Since we don't know the order of the set condition clauses, have to determine the order of them to set - the actual values to the prepared statement */ - Map orderedParamsMap = ConsentDAOUtils - .determineOrderOfParamsToSet(constructedConditions, applicableConditionsMap, COLUMNS_MAP); - - log.debug("Setting parameters to prepared statement to search consents"); - - parameterIndex = setDynamicConsentSearchParameters(searchConsentsPreparedStmt, orderedParamsMap, - ++parameterIndex); - parameterIndex = parameterIndex - 1; - - //determine order of user Ids to set - if (CollectionUtils.isNotEmpty(userIDs)) { - Map orderedUserIdsMap = ConsentDAOUtils - .determineOrderOfParamsToSet(userIDFilterCondition, userIdMap, COLUMNS_MAP); - parameterIndex = setDynamicConsentSearchParameters(searchConsentsPreparedStmt, orderedUserIdsMap, - ++parameterIndex); - parameterIndex = parameterIndex - 1; - } - - if (fromTime != null) { - searchConsentsPreparedStmt.setLong(++parameterIndex, fromTime); - } else { - searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); - } - - if (toTime != null) { - searchConsentsPreparedStmt.setLong(++parameterIndex, toTime); - } else { - searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); - } - - if (limit != null && offset != null) { - searchConsentsPreparedStmt.setInt(++parameterIndex, limit); - searchConsentsPreparedStmt.setInt(++parameterIndex, offset); - } else if (limit != null) { - searchConsentsPreparedStmt.setInt(++parameterIndex, limit); - } - ArrayList detailedConsentResources = new ArrayList<>(); - - try (ResultSet resultSet = searchConsentsPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - int resultSetSize = getResultSetSize(resultSet); - detailedConsentResources = constructDetailedConsentsSearchResult(resultSet, resultSetSize); - } - return detailedConsentResources; - } catch (SQLException e) { - log.error("Error occurred while searching detailed consent resources", e); - throw new OBConsentDataRetrievalException("Error occurred while searching detailed " + - "consent resources", e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG); - } - } - - @Override - public ArrayList searchConsentAuthorizations(Connection connection, String consentID, - String userID) - throws OBConsentDataRetrievalException { - - ArrayList retrievedAuthorizationResources = new ArrayList<>(); - Map conditions = new HashMap<>(); - if (StringUtils.trimToNull(consentID) != null) { - conditions.put("CONSENT_ID", consentID); - } - if (StringUtils.trimToNull(userID) != null) { - conditions.put("USER_ID", userID); - } - String whereClause = ConsentDAOUtils.constructAuthSearchPreparedStatement(conditions); - String searchAuthorizationResourcesPrepStatement = - sqlStatements.getSearchAuthorizationResourcesPreparedStatement(whereClause); - - try (PreparedStatement getSearchAuthorizationResourcesPreparedStmt = - connection.prepareStatement(searchAuthorizationResourcesPrepStatement)) { - - if (log.isDebugEnabled()) { - log.debug("Setting parameters to prepared statement to search authorization resources"); - } - - Iterator> conditionIterator = conditions.entrySet().iterator(); - - for (int count = 1; count <= conditions.size(); count++) { - getSearchAuthorizationResourcesPreparedStmt.setString(count, conditionIterator.next().getValue()); - } - - try (ResultSet resultSet = getSearchAuthorizationResourcesPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource - .setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); - authorizationResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - authorizationResource - .setUserID(resultSet.getString(ConsentMgtDAOConstants.USER_ID)); - authorizationResource.setAuthorizationStatus(resultSet - .getString(ConsentMgtDAOConstants.AUTH_STATUS)); - authorizationResource - .setAuthorizationType(resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE)); - authorizationResource.setUpdatedTime(resultSet.getLong(ConsentMgtDAOConstants.UPDATED_TIME)); - retrievedAuthorizationResources.add(authorizationResource); - } - } else { - log.error("No records are found for the provided inputs"); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - log.error("Error occurred while searching authorization resources", e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants - .CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); - } - log.debug("Retrieved the authorization resources successfully"); - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants - .CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); - } - return retrievedAuthorizationResources; - } - - /** - * Set data from the result set to ConsentResource object. - * - * @param resultSet result set - * @param consentResource consent resource - * @throws SQLException thrown if an error occurs when getting data from the result set - */ - private void setDataToConsentResource(ResultSet resultSet, ConsentResource consentResource) throws SQLException { - - consentResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - consentResource.setReceipt(resultSet.getString(ConsentMgtDAOConstants.RECEIPT)); - consentResource.setCreatedTime(resultSet.getLong(ConsentMgtDAOConstants.CREATED_TIME)); - consentResource.setUpdatedTime(resultSet.getLong(ConsentMgtDAOConstants.UPDATED_TIME)); - consentResource.setClientID(resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID)); - consentResource.setConsentType(resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE)); - consentResource. - setCurrentStatus(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS)); - consentResource.setConsentFrequency(resultSet - .getInt(ConsentMgtDAOConstants.CONSENT_FREQUENCY)); - consentResource.setValidityPeriod(resultSet.getLong(ConsentMgtDAOConstants.VALIDITY_TIME)); - consentResource.setRecurringIndicator(resultSet.getBoolean( - ConsentMgtDAOConstants.RECURRING_INDICATOR)); - } - - /** - * Set data from the result set to DetaildConsentResource object. - * - * @param resultSet result set - * @param detailedConsentResource consent resource - * @throws SQLException thrown if an error occurs when getting data from the result set - */ - private void setDataToDetailedConsentResource(ResultSet resultSet, DetailedConsentResource detailedConsentResource) - throws SQLException { - - Map consentAttributesMap = new HashMap<>(); - ArrayList authorizationResources = new ArrayList<>(); - ArrayList consentMappingResources = new ArrayList<>(); - ArrayList authIds = new ArrayList<>(); - ArrayList consentMappingIds = new ArrayList<>(); - - while (resultSet.next()) { - // Set data related to the consent resource - setConsentDataToDetailedConsentResource(resultSet, detailedConsentResource); - - // Set data related to consent attributes - if (StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY))) { - String attributeValue = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE); - - // skip adding all temporary session data to consent attributes - if (!(JSONValue.isValidJson(attributeValue) && attributeValue.contains(SESSION_DATA_KEY))) { - consentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), - attributeValue); - } - } - - // Set data related to authorization resources - if (authIds.isEmpty()) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); - authorizationResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - authorizationResource.setAuthorizationStatus(resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS)); - authorizationResource.setAuthorizationType(resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE)); - authorizationResource.setUserID(resultSet.getString(ConsentMgtDAOConstants.USER_ID)); - authorizationResource.setUpdatedTime(resultSet.getLong(ConsentMgtDAOConstants.AUTH_UPDATED_TIME)); - authorizationResources.add(authorizationResource); - authIds.add(authorizationResource.getAuthorizationID()); - } else { - if (!authIds.contains(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID))) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); - authorizationResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - authorizationResource - .setAuthorizationStatus(resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS)); - authorizationResource.setAuthorizationType(resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE)); - authorizationResource.setUserID(resultSet.getString(ConsentMgtDAOConstants.USER_ID)); - authorizationResource.setUpdatedTime(resultSet.getLong(ConsentMgtDAOConstants.AUTH_UPDATED_TIME)); - authorizationResources.add(authorizationResource); - authIds.add(authorizationResource.getAuthorizationID()); - } - } - - // Set data related to consent account mappings - // Check whether consentMappingIds is empty and result set consists a mapping id since at this moment - // there can be a situation where an auth resource is created and mapping resource is not created - if (consentMappingIds.isEmpty() && resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); - consentMappingResource.setAccountID(resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID)); - consentMappingResource.setMappingID(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)); - consentMappingResource.setMappingStatus(resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS)); - consentMappingResource.setPermission(resultSet.getString(ConsentMgtDAOConstants.PERMISSION)); - consentMappingResources.add(consentMappingResource); - consentMappingIds.add(consentMappingResource.getMappingID()); - } else { - // Check whether result set consists a mapping id since at this moment, there can be a situation - // where an auth resource is created and mapping resource is not created - if (!consentMappingIds.contains(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)) && - resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); - consentMappingResource.setAccountID(resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID)); - consentMappingResource.setMappingID(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)); - consentMappingResource.setMappingStatus(resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS)); - consentMappingResource.setPermission(resultSet.getString(ConsentMgtDAOConstants.PERMISSION)); - consentMappingResources.add(consentMappingResource); - consentMappingIds.add(consentMappingResource.getMappingID()); - } - } - } - - // Set consent attributes, auth resources and account mappings to detailed consent resource - detailedConsentResource.setConsentAttributes(consentAttributesMap); - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - } - - void setConsentDataToDetailedConsentResource(ResultSet resultSet, - DetailedConsentResource detailedConsentResource) - throws SQLException { - - detailedConsentResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - detailedConsentResource.setClientID(resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID)); - detailedConsentResource.setReceipt(resultSet.getString(ConsentMgtDAOConstants.RECEIPT)); - detailedConsentResource.setCreatedTime(resultSet.getLong(ConsentMgtDAOConstants.CONSENT_CREATED_TIME)); - detailedConsentResource.setUpdatedTime(resultSet.getLong(ConsentMgtDAOConstants.CONSENT_UPDATED_TIME)); - detailedConsentResource.setConsentType(resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE)); - detailedConsentResource.setCurrentStatus(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS)); - detailedConsentResource.setConsentFrequency(resultSet.getInt(ConsentMgtDAOConstants.CONSENT_FREQUENCY)); - detailedConsentResource.setValidityPeriod(resultSet.getLong(ConsentMgtDAOConstants.VALIDITY_TIME)); - detailedConsentResource.setRecurringIndicator(resultSet - .getBoolean(ConsentMgtDAOConstants.RECURRING_INDICATOR)); - } - - /** - * Return a consent mapping resource with data set from the result set. - * - * @param resultSet result set - * @return a consent mapping resource - * @throws SQLException thrown if an error occurs when getting data from the result set - */ - private ConsentMappingResource getConsentMappingResourceWithData(ResultSet resultSet) throws SQLException { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); - consentMappingResource.setMappingID(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)); - consentMappingResource.setAccountID(resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID)); - consentMappingResource.setPermission(resultSet.getString(ConsentMgtDAOConstants.PERMISSION)); - consentMappingResource.setMappingStatus(resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS)); - - return consentMappingResource; - } - - /** - * Sets search parameters to dynamically constructed prepared statement. The outer loop is used to iterate the - * different AND clauses and the inner loop is to iterate the number of placeholders of the current AND clause. - * - * @param preparedStatement dynamically constructed prepared statement - * @param orderedParamsMap map with ordered AND conditions - * @param parameterIndex index which the parameter should be set - * @return the final parameter index - * @throws SQLException thrown if an error occurs in the process - */ - int setDynamicConsentSearchParameters(PreparedStatement preparedStatement, Map orderedParamsMap, - int parameterIndex) - throws SQLException { - - for (Map.Entry entry : orderedParamsMap.entrySet()) { - for (int valueIndex = 0; valueIndex < entry.getValue().size(); valueIndex++) { - preparedStatement.setString(parameterIndex, ((String) entry.getValue().get(valueIndex)).trim()); - parameterIndex++; - } - } - return parameterIndex; - } - - int getResultSetSize(ResultSet resultSet) throws SQLException { - - resultSet.last(); - int resultSetSize = resultSet.getRow(); - - // Point result set back before first - resultSet.beforeFirst(); - return resultSetSize; - } - - void setAuthorizationData(AuthorizationResource authorizationResource, ResultSet resultSet) - throws SQLException { - - authorizationResource.setAuthorizationID(resultSet - .getString(ConsentMgtDAOConstants.AUTH_ID)); - authorizationResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - authorizationResource.setAuthorizationType(resultSet - .getString(ConsentMgtDAOConstants.AUTH_TYPE)); - authorizationResource.setAuthorizationStatus(resultSet - .getString(ConsentMgtDAOConstants.AUTH_STATUS)); - authorizationResource.setUpdatedTime(resultSet - .getLong(ConsentMgtDAOConstants.UPDATED_TIME)); - authorizationResource.setUserID(resultSet.getString(ConsentMgtDAOConstants.USER_ID)); - } - - protected void setAuthorizationDataInResponseForGroupedQuery(ArrayList - authorizationResources, - ResultSet resultSet, String consentId) - throws SQLException { - - //identify duplicate auth data - Set authIdSet = new HashSet<>(); - - // fetch values from group_concat - String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_ID).split(GROUP_BY_SEPARATOR) : null; - String[] authTypes = resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE).split(GROUP_BY_SEPARATOR) : null; - String[] authStatues = resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS).split(GROUP_BY_SEPARATOR) : null; - String[] updatedTimes = resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME) != null ? - resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME).split(GROUP_BY_SEPARATOR) : null; - String[] userIds = resultSet.getString(ConsentMgtDAOConstants.USER_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.USER_ID).split(GROUP_BY_SEPARATOR) : null; - - for (int index = 0; index < (authIds != null ? authIds.length : 0); index++) { - if (!authIdSet.contains(authIds[index])) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authIdSet.add(authIds[index]); - authorizationResource.setAuthorizationID(authIds[index]); - authorizationResource.setConsentID(consentId); - if (authTypes != null && authTypes.length > index) { - authorizationResource.setAuthorizationType(authTypes[index]); - } - if (authStatues != null && authStatues.length > index) { - authorizationResource.setAuthorizationStatus(authStatues[index]); - } - if (updatedTimes != null && updatedTimes.length > index) { - authorizationResource.setUpdatedTime(Long.parseLong(updatedTimes[index])); - } - if (userIds != null && userIds.length > index) { - authorizationResource.setUserID(userIds[index]); - } - authorizationResources.add(authorizationResource); - } - } - - } - - protected void setAccountConsentMappingDataInResponse(ArrayList consentMappingResources, - ResultSet resultSet) throws SQLException { - - //identify duplicate mappingIds - Set mappingIdSet = new HashSet<>(); - - // fetch values from group_concat - String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; - String[] mappingIds = resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; - String[] accountIds = resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID).split(GROUP_BY_SEPARATOR) : null; - String[] mappingStatues = resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) != null ? - resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS).split(GROUP_BY_SEPARATOR) : null; - String[] permissions = resultSet.getString(ConsentMgtDAOConstants.PERMISSION) != null ? - resultSet.getString(ConsentMgtDAOConstants.PERMISSION).split(GROUP_BY_SEPARATOR) : null; - - for (int index = 0; index < (mappingIds != null ? mappingIds.length : 0); index++) { - if (!mappingIdSet.contains(mappingIds[index])) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - if (authIds != null && authIds.length > index) { - consentMappingResource.setAuthorizationID(authIds[index]); - } - consentMappingResource.setMappingID(mappingIds[index]); - if (accountIds != null && accountIds.length > index) { - consentMappingResource.setAccountID(accountIds[index]); - } - if (mappingStatues != null && mappingStatues.length > index) { - consentMappingResource.setMappingStatus(mappingStatues[index]); - } - if (permissions != null && permissions.length > index) { - consentMappingResource.setPermission(permissions[index]); - } - consentMappingResources.add(consentMappingResource); - mappingIdSet.add(mappingIds[index]); - } - } - - } - - void validateAndSetSearchConditions(Map applicableConditionsMap, ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses) { - - log.debug("Validate applicable search conditions"); - - if (CollectionUtils.isNotEmpty(consentIDs)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_IDS), consentIDs); - } - if (CollectionUtils.isNotEmpty(clientIDs)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CLIENT_IDS), clientIDs); - } - if (CollectionUtils.isNotEmpty(consentTypes)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_TYPES), consentTypes); - } - if (CollectionUtils.isNotEmpty(consentStatuses)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_STATUSES), consentStatuses); - } - } - - ArrayList constructDetailedConsentsSearchResult(ResultSet resultSet, int resultSetSize) - throws SQLException { - - ArrayList detailedConsentResources = new ArrayList<>(); - - while (resultSet.next()) { - - Map consentAttributesMap = new HashMap<>(); - ArrayList consentMappingResources = new ArrayList<>(); - ArrayList authorizationResources = new ArrayList<>(); - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - - setConsentDataToDetailedConsentResource(resultSet, detailedConsentResource); - - // Set consent attributes to map if available - if (resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) != null && - StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY)) - && StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE))) { - // fetch attribute keys and values from group_concat - String[] attributeKeys = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY).split(GROUP_BY_SEPARATOR); - String[] attributeValues = resultSet - .getString(ConsentMgtDAOConstants.ATT_VALUE).split(GROUP_BY_SEPARATOR); - // check if all attribute keys has values - if (attributeKeys.length == attributeValues.length) { - for (int index = 0; index < attributeKeys.length; index++) { - consentAttributesMap.put(attributeKeys[index], attributeValues[index]); - } - } - } - // Set authorization data - setAuthorizationDataInResponseForGroupedQuery(authorizationResources, resultSet, - detailedConsentResource.getConsentID()); - // Set consent account mapping data if available - setAccountConsentMappingDataInResponse(consentMappingResources, resultSet); - - detailedConsentResource.setConsentAttributes(consentAttributesMap); - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - detailedConsentResources.add(detailedConsentResource); - - } - return detailedConsentResources; - } - - @Override - public boolean updateConsentReceipt(Connection connection, String consentID, String consentReceipt) - throws OBConsentDataUpdationException { - - int result; - String updateConsentReceiptPrepStatement = sqlStatements.getUpdateConsentReceiptPreparedStatement(); - - try (PreparedStatement updateConsentReceiptPreparedStmt = - connection.prepareStatement(updateConsentReceiptPrepStatement)) { - - log.debug("Setting parameters to prepared statement to update consent receipt"); - - updateConsentReceiptPreparedStmt.setString(1, consentReceipt); - updateConsentReceiptPreparedStmt.setString(2, consentID); - - // with result, we can determine whether the updating was successful or not - result = updateConsentReceiptPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error("Error while updating consent receipt", e); - throw new OBConsentDataUpdationException("Error while updating consent receipt for consent ID: " - + consentID, e); - } - - // Confirm that the data are updated successfully - if (result > 0) { - return true; - } else { - throw new OBConsentDataUpdationException("Failed to update consent receipt properly."); - } - } - - @Override - public boolean updateConsentValidityTime(Connection connection, String consentID, long validityTime) - throws OBConsentDataUpdationException { - - int result; - String updateConsentReceiptPrepStatement = sqlStatements.getUpdateConsentValidityTimePreparedStatement(); - long updatedTime = System.currentTimeMillis() / 1000; - - try (PreparedStatement updateConsentValidityTimePreparedStmt = - connection.prepareStatement(updateConsentReceiptPrepStatement)) { - - log.debug("Setting parameters to prepared statement to update consent receipt"); - - updateConsentValidityTimePreparedStmt.setLong(1, validityTime); - updateConsentValidityTimePreparedStmt.setLong(2, updatedTime); - updateConsentValidityTimePreparedStmt.setString(3, consentID); - - // with result, we can determine whether the updating was successful or not - result = updateConsentValidityTimePreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error("Error while updating consent validity time", e); - throw new OBConsentDataUpdationException("Error while updating consent validity time for consent ID: " - + consentID, e); - } - - // Confirm that the data are updated successfully - if (result > 0) { - return true; - } else { - throw new OBConsentDataUpdationException("Failed to update consent validity time properly."); - } - } - - @Override - public boolean storeConsentAmendmentHistory(Connection connection, String historyID, long timestamp, - String recordID, String consentDataType, String changedAttributesJsonString, String amendmentReason) - throws OBConsentDataInsertionException { - - String tableID = generateConsentTableId(consentDataType); - - int result; - String insertConsentHistoryPrepStatement = sqlStatements.getInsertConsentHistoryPreparedStatement(); - - try (PreparedStatement insertConsentHistoryPreparedStmt = - connection.prepareStatement(insertConsentHistoryPrepStatement)) { - - if (log.isDebugEnabled()) { - log.debug(String.format("Setting parameters to prepared statement to store consent amendment history " + - "of %s", consentDataType)); - } - - insertConsentHistoryPreparedStmt.setString(1, tableID); - insertConsentHistoryPreparedStmt.setString(2, recordID); - insertConsentHistoryPreparedStmt.setString(3, historyID); - insertConsentHistoryPreparedStmt.setString(4, changedAttributesJsonString); - insertConsentHistoryPreparedStmt.setString(5, amendmentReason); - insertConsentHistoryPreparedStmt.setLong(6, timestamp); - - // with result, we can determine whether the updating was successful or not - result = insertConsentHistoryPreparedStmt.executeUpdate(); - } catch (SQLException e) { - log.error("Error while storing consent amendment history", e); - throw new OBConsentDataInsertionException(String.format("Error while storing consent amendment history of" + - " %s for record ID: %s", consentDataType, recordID), e); - } - - // Confirm that the data are inserted successfully - if (result > 0) { - return true; - } else { - log.error("Failed to store consent amendment history data."); - throw new OBConsentDataInsertionException("Failed to store consent amendment history data properly."); - } - } - - @Override - public Map retrieveConsentAmendmentHistory(Connection connection, - List recordIDsList) throws OBConsentDataRetrievalException { - - String whereClause = ConsentDAOUtils.constructConsentHistoryPreparedStatement(recordIDsList.size()); - String getConsentHistoryPrepStatement = sqlStatements.getGetConsentHistoryPreparedStatement(whereClause); - - try (PreparedStatement getConsentHistoryPreparedStmt = - connection.prepareStatement(getConsentHistoryPrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent history data"); - - for (int count = 1; count <= recordIDsList.size(); count++) { - getConsentHistoryPreparedStmt.setString(count, recordIDsList.get(count - 1)); - } - - String consentID = recordIDsList.get(0); - try (ResultSet resultSet = getConsentHistoryPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - return constructConsentHistoryRetrievalResult(consentID, resultSet); - } else { - log.error("No records are found for consent ID : " + consentID); - return new HashMap<>(); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent amendment history", e); - throw new OBConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + - "amendment history for consent ID : %s", consentID), e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_AMENDMENT_HISTORY_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException( - ConsentMgtDAOConstants.CONSENT_AMENDMENT_HISTORY_RETRIEVE_ERROR_MSG, e); - } - } - - /** - * construct a data map that includes the changed attributes of each consent amendment history entry and. - * return a map of ConsentHistoryResources including this changed attributes data map - * - * @param consentId consent Id - * @param resultSet result set - * @return a map of ConsentHistoryResources - * @throws SQLException thrown if an error occurs when getting data from the result set - */ - private Map constructConsentHistoryRetrievalResult(String consentId, - ResultSet resultSet) - throws SQLException { - - Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); - - while (resultSet.next()) { - String tableID = resultSet.getString(ConsentMgtDAOConstants.TABLE_ID); - String recordID = resultSet.getString(ConsentMgtDAOConstants.RECORD_ID); - String historyId = resultSet.getString(ConsentMgtDAOConstants.HISTORY_ID); - String changedAttributesString = resultSet.getString(ConsentMgtDAOConstants.CHANGED_VALUES); - String amendmentReason = resultSet.getString(ConsentMgtDAOConstants.REASON); - Long timestamp = resultSet.getLong(ConsentMgtDAOConstants.EFFECTIVE_TIMESTAMP); - - ConsentHistoryResource consentHistoryResource; - Map changedAttributesJsonDataMap; - if (consentAmendmentHistoryDataMap.containsKey(historyId)) { - consentHistoryResource = consentAmendmentHistoryDataMap.get(historyId); - } else { - consentHistoryResource = new ConsentHistoryResource(consentId, historyId); - consentHistoryResource.setTimestamp(timestamp); - consentHistoryResource.setReason(amendmentReason); - } - - changedAttributesJsonDataMap = consentHistoryResource.getChangedAttributesJsonDataMap(); - - if (TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT).equalsIgnoreCase(tableID)) { - changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, - changedAttributesString); - } else if (TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT_ATTRIBUTE).equalsIgnoreCase(tableID)) { - changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, - changedAttributesString); - } else if (TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT_AUTH_RESOURCE) - .equalsIgnoreCase(tableID)) { - Map consentAuthResources; - if (changedAttributesJsonDataMap.containsKey(ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA)) { - consentAuthResources = (Map) changedAttributesJsonDataMap - .get(ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA); - } else { - consentAuthResources = new HashMap<>(); - } - consentAuthResources.put(recordID, changedAttributesString); - changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, - consentAuthResources); - } else if (TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT_MAPPING).equalsIgnoreCase(tableID)) { - Map consentMappingResources; - if (changedAttributesJsonDataMap.containsKey(ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA)) { - consentMappingResources = (Map) changedAttributesJsonDataMap - .get(ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA); - } else { - consentMappingResources = new HashMap<>(); - } - consentMappingResources.put(recordID, changedAttributesString); - changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, - consentMappingResources); - } else { - log.error(String.format("The retrieved tableId : %s has no corresponding consent data type to be" + - " matched", tableID)); - } - consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJsonDataMap); - consentAmendmentHistoryDataMap.put(historyId, consentHistoryResource); - } - return consentAmendmentHistoryDataMap; - } - - public ArrayList getExpiringConsents(Connection connection, - String statusesEligibleForExpiration) - throws OBConsentDataRetrievalException { - - List statusesEligibleForExpirationList = Arrays.asList(statusesEligibleForExpiration.split(",")) - .stream().filter(status -> !status.isEmpty()) - .collect(Collectors.toList()); - - String statusesEligibleForExpirationCondition = ConsentDAOUtils.constructStatusesEligibleForExpirationCondition( - statusesEligibleForExpirationList); - String expiringConsentStatement = sqlStatements.getSearchExpiringConsentPreparedStatement( - statusesEligibleForExpirationCondition); - - try (PreparedStatement preparedStatement = - connection.prepareStatement(expiringConsentStatement)) { - - log.debug("Setting parameters to prepared statement to fetch consents eligible for expiration"); - - ArrayList consentIdList = new ArrayList<>(); - - // populate prepared statement - int parameterIndex = 0; - preparedStatement.setString(++parameterIndex, ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE); - for (String status : statusesEligibleForExpirationList) { - preparedStatement.setString(++parameterIndex, status); - } - - try (ResultSet resultSet = preparedStatement.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - consentIdList.add(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - } - } else { - log.debug("No consents found for expiration check eligibility."); - } - if (!consentIdList.isEmpty()) { - return searchConsents(connection, consentIdList, null, null, null, - null, null, null, null, null); - } else { - return new ArrayList<>(); - } - - } catch (SQLException e) { - log.error("Error occurred while searching consents eligible for expiration", e); - throw new OBConsentDataRetrievalException("Error occurred while searching consents" + - " eligible for expiration", e); - } - } catch (SQLException e) { - log.error("Error while searching consents eligible for expiration", e); - throw new OBConsentDataRetrievalException("Error while updating searching consents eligible for" + - " expiration", e); - } - } - - @Override - public boolean deleteConsentData(Connection connection, String consentID, boolean executeOnRetentionTables) - throws OBConsentDataDeletionException { - - if (log.isDebugEnabled()) { - log.debug(String.format("Deleting consent details for consent_id : %s", consentID)); - } - - int results; - - String deleteConsentAttributePrepStatement = sqlStatements - .getDeleteConsentAttributeByConsentIdPreparedStatement(executeOnRetentionTables); - String deleteConsentFilePrepStatement = sqlStatements - .getDeleteConsentFileResourcePreparedStatement(executeOnRetentionTables); - String deleteConsentMappingPrepStatement = sqlStatements - .getDeleteConsentMappingByAuthIdPreparedStatement(executeOnRetentionTables); - String deleteConsentAuthResourcePrepStatement = sqlStatements - .getDeleteAuthorizationResourcePreparedStatement(executeOnRetentionTables); - String deleteConsentStatusAuditRecordPrepStatement = sqlStatements - .getDeleteConsentStatusAuditRecordsPreparedStatement(executeOnRetentionTables); - String deleteConsentResourcePrepStatement = sqlStatements - .getDeleteConsentPreparedStatement(executeOnRetentionTables); - - try (PreparedStatement deleteConsentAttributesPreparedStmt = - connection.prepareStatement(deleteConsentAttributePrepStatement); - PreparedStatement deleteConsentFilePreparedStmt = - connection.prepareStatement(deleteConsentFilePrepStatement); - PreparedStatement deleteConsentMappingPreparedStmt = - connection.prepareStatement(deleteConsentMappingPrepStatement); - PreparedStatement deleteConsentAuthResourcePreparedStmt = - connection.prepareStatement(deleteConsentAuthResourcePrepStatement); - PreparedStatement deleteConsentStatusAuditPreparedStmt = - connection.prepareStatement(deleteConsentStatusAuditRecordPrepStatement); - PreparedStatement deleteConsentResourcePreparedStmt = - connection.prepareStatement(deleteConsentResourcePrepStatement)) { - - // deleting consent attributes. - log.debug("Setting parameters to prepared statement to delete consent attributes"); - deleteConsentAttributesPreparedStmt.setString(1, consentID); - deleteConsentAttributesPreparedStmt.executeUpdate(); - - // deleting consent file. - log.debug("Setting parameters to prepared statement to delete consent files"); - deleteConsentFilePreparedStmt.setString(1, consentID); - deleteConsentFilePreparedStmt.executeUpdate(); - - // deleting consent mappings - log.debug("Setting parameters to prepared statement to delete consent mappings"); - deleteConsentMappingPreparedStmt.setString(1, consentID); - deleteConsentMappingPreparedStmt.executeUpdate(); - - // deleting consent auth resource. - log.debug("Setting parameters to prepared statement to delete consent auth resource"); - deleteConsentAuthResourcePreparedStmt.setString(1, consentID); - deleteConsentAuthResourcePreparedStmt.executeUpdate(); - - // deleting consent status audit. - log.debug("Setting parameters to prepared statement to delete consent files"); - deleteConsentStatusAuditPreparedStmt.setString(1, consentID); - deleteConsentStatusAuditPreparedStmt.executeUpdate(); - - // deleting consent resource. - log.debug("Setting parameters to prepared statement to delete consent resource"); - deleteConsentResourcePreparedStmt.setString(1, consentID); - results = deleteConsentResourcePreparedStmt.executeUpdate(); - - return results > 0; - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_DATA_DELETE_ERROR_MSG, e); - throw new OBConsentDataDeletionException(ConsentMgtDAOConstants.CONSENT_DATA_DELETE_ERROR_MSG, e); - } - } - - @Override - public ArrayList getListOfConsentIds(Connection connection, boolean fetchFromRetentionTable) - throws OBConsentDataRetrievalException { - - String getConsentIdsPrepStatement = - sqlStatements.getListOfConsentIdsPreparedStatement(fetchFromRetentionTable); - ArrayList consentIDs = new ArrayList<>(); - - try (PreparedStatement getConsentIdsPreparedStmt = - connection.prepareStatement(getConsentIdsPrepStatement)) { - - try (ResultSet resultSet = getConsentIdsPreparedStmt.executeQuery()) { - while (resultSet.next()) { - consentIDs.add(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - } - } catch (SQLException e) { - log.error("Error occurred while reading consent_id list", e); - throw new OBConsentDataRetrievalException("Error occurred while retrieving consent consent IDs list", - e); - } - - if (log.isDebugEnabled()) { - log.debug("Retrieved the consent id list from consent table"); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); - } - return consentIDs; - } - - @Override - public ArrayList getConsentStatusAuditRecordsByConsentId(Connection connection, - ArrayList consentIDs, - Integer limit, Integer offset, - boolean fetchFromRetentionTable) - throws OBConsentDataRetrievalException { - - boolean shouldLimit = true; - boolean shouldOffset = true; - int parameterIndex = 0; - - // Don't limit if either of limit or offset is null - if (limit == null) { - shouldLimit = false; - } - if (offset == null) { - shouldOffset = false; - } - - ArrayList retrievedAuditRecords = new ArrayList<>(); - String constructedConditions = - ConsentDAOUtils.constructConsentAuditRecordSearchPreparedStatement(consentIDs); - - String getConsentStatusAuditRecordsPrepStatement = - sqlStatements.getConsentStatusAuditRecordsByConsentIdsPreparedStatement(constructedConditions, - shouldLimit, shouldOffset, fetchFromRetentionTable); - - try (PreparedStatement getConsentStatusAuditRecordPreparedStmt = - connection.prepareStatement(getConsentStatusAuditRecordsPrepStatement)) { - - log.debug("Setting parameters to prepared statement to retrieve consent status audit records"); - if (!CollectionUtils.isEmpty(consentIDs)) { - for (String consentId : consentIDs) { - parameterIndex++; - getConsentStatusAuditRecordPreparedStmt.setString(parameterIndex, consentId); - } - } - if (limit != null && offset != null) { - getConsentStatusAuditRecordPreparedStmt.setInt(++parameterIndex, - sqlStatements.isLimitBeforeThanOffset() ? limit : offset); - getConsentStatusAuditRecordPreparedStmt.setInt(++parameterIndex, - sqlStatements.isLimitBeforeThanOffset() ? offset : limit); - } else if (limit != null) { - getConsentStatusAuditRecordPreparedStmt.setInt(++parameterIndex, limit); - } - - try (ResultSet resultSet = getConsentStatusAuditRecordPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord - .setStatusAuditID(resultSet.getString(ConsentMgtDAOConstants.STATUS_AUDIT_ID)); - consentStatusAuditRecord.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); - consentStatusAuditRecord - .setCurrentStatus(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS)); - consentStatusAuditRecord.setActionBy(resultSet.getString(ConsentMgtDAOConstants.ACTION_BY)); - consentStatusAuditRecord.setActionTime(resultSet.getLong(ConsentMgtDAOConstants.ACTION_TIME)); - consentStatusAuditRecord.setReason(resultSet.getString(ConsentMgtDAOConstants.REASON)); - consentStatusAuditRecord - .setPreviousStatus(resultSet.getString(ConsentMgtDAOConstants.PREVIOUS_STATUS)); - retrievedAuditRecords.add(consentStatusAuditRecord); - } - } - } catch (SQLException e) { - log.error("Error occurred while reading consent status audit records", e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); - } - - log.debug("Retrieved the consent status audit records successfully"); - - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); - } - return retrievedAuditRecords; - } - - /** - * Generate the tableID based on the type of the consent data record to be stored in consent history table. - * - * @param consentDataType A predefined consent data category based on each consent database table - * @return A identifier assigned for the relevant consent database table - */ - private String generateConsentTableId(String consentDataType) throws OBConsentDataInsertionException { - - String tableId; - if (ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA.equalsIgnoreCase(consentDataType)) { - tableId = TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT); - } else if (ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA.equalsIgnoreCase(consentDataType)) { - tableId = TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT_AUTH_RESOURCE); - } else if (ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA.equalsIgnoreCase(consentDataType)) { - tableId = TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT_ATTRIBUTE); - } else if (ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA.equalsIgnoreCase(consentDataType)) { - tableId = TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_OB_CONSENT_MAPPING); - } else { - log.error(String.format("Can not find a table matching to the provided consentDataType : %s", - consentDataType)); - throw new OBConsentDataInsertionException("Error occurred while preparing to store consent amendment " + - "history data. Invalid consentDataType provided"); - } - return tableId; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/MssqlConsentCoreDAOImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/MssqlConsentCoreDAOImpl.java deleted file mode 100644 index c966ba8f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/MssqlConsentCoreDAOImpl.java +++ /dev/null @@ -1,360 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.impl; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtMssqlDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.utils.ConsentDAOUtils; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * DAO implementation for MSSQL specific methods. - */ -public class MssqlConsentCoreDAOImpl extends ConsentCoreDAOImpl { - - private static Log log = LogFactory.getLog(MssqlConsentCoreDAOImpl.class); - private static final String GROUP_BY_SEPARATOR = "\\|\\|"; - static final Map COLUMNS_MAP = new HashMap() { - { - put(ConsentMgtDAOConstants.CONSENT_IDS, "OBC.CONSENT_ID"); - put(ConsentMgtDAOConstants.CLIENT_IDS, "OBC.CLIENT_ID"); - put(ConsentMgtDAOConstants.CONSENT_TYPES, "OBC.CONSENT_TYPE"); - put(ConsentMgtDAOConstants.CONSENT_STATUSES, "OBC.CURRENT_STATUS"); - put(ConsentMgtDAOConstants.USER_IDS, "OCAR.USER_ID"); - } - }; - - public MssqlConsentCoreDAOImpl(ConsentMgtMssqlDBQueries sqlStatements) { - - super(sqlStatements); - } - - @Override - public ArrayList searchConsents(Connection connection, ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, - Long toTime, Integer limit, Integer offset) - throws OBConsentDataRetrievalException { - - boolean shouldLimit = true; - boolean shouldOffset = true; - int parameterIndex = 0; - Map applicableConditionsMap = new HashMap<>(); - - validateAndSetSearchConditions(applicableConditionsMap, consentIDs, clientIDs, consentTypes, consentStatuses); - - if (limit == null) { - shouldLimit = false; - } - if (offset == null) { - shouldOffset = false; - } - - // logic to set the prepared statement - String constructedConditions = - ConsentDAOUtils.constructConsentSearchPreparedStatement(applicableConditionsMap); - - String userIDFilterCondition = ""; - Map userIdMap = new HashMap<>(); - if (CollectionUtils.isNotEmpty(userIDs)) { - userIdMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.USER_IDS), userIDs); - userIDFilterCondition = ConsentDAOUtils.constructUserIdListFilterCondition(userIdMap); - } - String searchConsentsPreparedStatement = - sqlStatements.getSearchConsentsPreparedStatement(constructedConditions, shouldLimit, - shouldOffset, userIDFilterCondition); - - try (PreparedStatement searchConsentsPreparedStmt = - connection.prepareStatement(searchConsentsPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY)) { - - /* Since we don't know the order of the set condition clauses, have to determine the order of them to set - the actual values to the prepared statement */ - Map orderedParamsMap = ConsentDAOUtils - .determineOrderOfParamsToSet(constructedConditions, applicableConditionsMap, COLUMNS_MAP); - - log.debug("Setting parameters to prepared statement to search consents"); - - //determine order of user Ids to set - if (CollectionUtils.isNotEmpty(userIDs)) { - Map orderedUserIdsMap = ConsentDAOUtils - .determineOrderOfParamsToSet(userIDFilterCondition, userIdMap, COLUMNS_MAP); - parameterIndex = setDynamicConsentSearchParameters(searchConsentsPreparedStmt, orderedUserIdsMap, - ++parameterIndex); - parameterIndex = parameterIndex - 1; - } - - parameterIndex = setDynamicConsentSearchParameters(searchConsentsPreparedStmt, orderedParamsMap, - ++parameterIndex); - parameterIndex = parameterIndex - 1; - - if (fromTime != null) { - searchConsentsPreparedStmt.setLong(++parameterIndex, fromTime); - } else { - searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); - } - - if (toTime != null) { - searchConsentsPreparedStmt.setLong(++parameterIndex, toTime); - } else { - searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); - } - - if (offset != null && limit != null) { - searchConsentsPreparedStmt.setInt(++parameterIndex, offset); - } - if (limit != null) { - searchConsentsPreparedStmt.setInt(++parameterIndex, limit); - } - - ArrayList detailedConsentResources = new ArrayList<>(); - - try (ResultSet resultSet = searchConsentsPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - int resultSetSize = getResultSetSize(resultSet); - detailedConsentResources = constructDetailedConsentsSearchResult(resultSet, resultSetSize); - } - return detailedConsentResources; - } catch (SQLException e) { - log.error("Error occurred while searching detailed consent resources", e); - throw new OBConsentDataRetrievalException("Error occurred while searching detailed " + - "consent resources", e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); - } - } - - ArrayList constructDetailedConsentsSearchResult(ResultSet resultSet, int resultSetSize) - throws SQLException { - - ArrayList detailedConsentResources = new ArrayList<>(); - - while (resultSet.next()) { - - Map consentAttributesMap = new HashMap<>(); - ArrayList consentMappingResources = new ArrayList<>(); - ArrayList authorizationResources = new ArrayList<>(); - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - - setConsentDataToDetailedConsentInSearchResponse(resultSet, detailedConsentResource); - - // Set consent attributes to map if available - if (resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) != null && - StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY))) { - // fetch attribute keys and values from group_concat - String[] attKeys = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY).split(GROUP_BY_SEPARATOR); - String[] attValues = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE).split(GROUP_BY_SEPARATOR); - // check if all attribute keys has values - if (attKeys.length == attValues.length) { - for (int index = 0; index < attKeys.length; index++) { - if (!attKeys[index].isEmpty()) { - consentAttributesMap.put(attKeys[index], attValues[index]); - } - } - } - } - // Set authorization data - setAuthorizationDataInResponseForGroupedQuery(authorizationResources, resultSet, - detailedConsentResource.getConsentID()); - // Set consent account mapping data if available - setAccountConsentMappingDataInResponse(consentMappingResources, resultSet); - - detailedConsentResource.setConsentAttributes(consentAttributesMap); - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - detailedConsentResources.add(detailedConsentResource); - - } - return detailedConsentResources; - } - - void setConsentDataToDetailedConsentInSearchResponse(ResultSet resultSet, - DetailedConsentResource detailedConsentResource) - throws SQLException { - - Optional consentId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional clientId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional receipt = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.RECEIPT) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional createdTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_CREATED_TIME) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional consentUpdatedTime = Arrays.stream( - resultSet.getString(ConsentMgtDAOConstants.CONSENT_UPDATED_TIME) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional consentType = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional currentStatus = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional frequency = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_FREQUENCY) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional validityTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.VALIDITY_TIME) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional recurringIndicator = Arrays.stream( - resultSet.getString(ConsentMgtDAOConstants.RECURRING_INDICATOR) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - - if (consentId.isPresent() && clientId.isPresent()) { - detailedConsentResource.setConsentID(consentId.get()); - detailedConsentResource.setClientID(clientId.get()); - } else { - throw new SQLException("CLIENT_ID and CONSENT_ID could not be null."); - } - receipt.ifPresent(detailedConsentResource::setReceipt); - consentType.ifPresent(detailedConsentResource::setConsentType); - currentStatus.ifPresent(detailedConsentResource::setCurrentStatus); - createdTime.ifPresent(e -> detailedConsentResource.setCreatedTime(Long.parseLong(e))); - consentUpdatedTime.ifPresent(e -> detailedConsentResource.setUpdatedTime(Long.parseLong(e))); - frequency.ifPresent(e -> detailedConsentResource.setConsentFrequency(Integer.parseInt(e))); - validityTime.ifPresent(e -> detailedConsentResource.setValidityPeriod(Long.parseLong(e))); - recurringIndicator.ifPresent(e -> detailedConsentResource.setRecurringIndicator(Integer.parseInt(e) != 0)); - } - - protected void setAuthorizationDataInResponseForGroupedQuery(ArrayList - authorizationResources, - ResultSet resultSet, String consentId) - throws SQLException { - - //identify duplicate auth data - Set authIdSet = new HashSet<>(); - - // fetch values from group_concat - String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_ID).split(GROUP_BY_SEPARATOR) : null; - String[] authTypes = resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE).split(GROUP_BY_SEPARATOR) : null; - String[] authStatues = resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS).split(GROUP_BY_SEPARATOR) : null; - String[] updatedTimes = resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME) != null ? - resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME).split(GROUP_BY_SEPARATOR) : null; - String[] userIds = resultSet.getString(ConsentMgtDAOConstants.USER_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.USER_ID).split(GROUP_BY_SEPARATOR) : null; - - for (int index = 0; index < (authIds != null ? authIds.length : 0); index++) { - if (!authIdSet.contains(authIds[index])) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authIdSet.add(authIds[index]); - authorizationResource.setAuthorizationID(authIds[index]); - authorizationResource.setConsentID(consentId); - if (authTypes != null && authTypes.length > index) { - authorizationResource.setAuthorizationType(authTypes[index]); - } - if (authStatues != null && authStatues.length > index) { - authorizationResource.setAuthorizationStatus(authStatues[index]); - } - if (updatedTimes != null && updatedTimes.length > index) { - authorizationResource.setUpdatedTime(Long.parseLong(updatedTimes[index])); - } - if (userIds != null && userIds.length > index) { - authorizationResource.setUserID(userIds[index]); - } - authorizationResources.add(authorizationResource); - } - } - - } - - protected void setAccountConsentMappingDataInResponse(ArrayList consentMappingResources, - ResultSet resultSet) throws SQLException { - - //identify duplicate mappingIds - Set mappingIdSet = new HashSet<>(); - - // fetch values from group_concat - String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; - String[] mappingIds = resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; - String[] accountIds = resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID).split(GROUP_BY_SEPARATOR) : null; - String[] mappingStatues = resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) != null ? - resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS).split(GROUP_BY_SEPARATOR) : null; - String[] permissions = resultSet.getString(ConsentMgtDAOConstants.PERMISSION) != null ? - resultSet.getString(ConsentMgtDAOConstants.PERMISSION).split(GROUP_BY_SEPARATOR) : null; - - for (int index = 0; index < (mappingIds != null ? mappingIds.length : 0); index++) { - if (!mappingIdSet.contains(mappingIds[index])) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - if (authIds != null && authIds.length > index) { - consentMappingResource.setAuthorizationID(authIds[index]); - } - consentMappingResource.setMappingID(mappingIds[index]); - if (accountIds != null && accountIds.length > index) { - consentMappingResource.setAccountID(accountIds[index]); - } - if (mappingStatues != null && mappingStatues.length > index) { - consentMappingResource.setMappingStatus(mappingStatues[index]); - } - if (permissions != null && permissions.length > index) { - consentMappingResource.setPermission(permissions[index]); - } - consentMappingResources.add(consentMappingResource); - mappingIdSet.add(mappingIds[index]); - } - } - - } - - void validateAndSetSearchConditions(Map applicableConditionsMap, ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses) { - - log.debug("Validate applicable search conditions"); - - if (CollectionUtils.isNotEmpty(consentIDs)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_IDS), consentIDs); - } - if (CollectionUtils.isNotEmpty(clientIDs)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CLIENT_IDS), clientIDs); - } - if (CollectionUtils.isNotEmpty(consentTypes)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_TYPES), consentTypes); - } - if (CollectionUtils.isNotEmpty(consentStatuses)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_STATUSES), consentStatuses); - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/OracleConsentCoreDAOImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/OracleConsentCoreDAOImpl.java deleted file mode 100644 index 0e98044d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/OracleConsentCoreDAOImpl.java +++ /dev/null @@ -1,359 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.impl; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtOracleDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.utils.ConsentDAOUtils; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * DAO implementation for Oracle specific methods. - */ -public class OracleConsentCoreDAOImpl extends ConsentCoreDAOImpl { - - private static Log log = LogFactory.getLog(OracleConsentCoreDAOImpl.class); - private static final String GROUP_BY_SEPARATOR = "\\|\\|"; - static final Map COLUMNS_MAP = new HashMap() { - { - put(ConsentMgtDAOConstants.CONSENT_IDS, "OBC.CONSENT_ID"); - put(ConsentMgtDAOConstants.CLIENT_IDS, "OBC.CLIENT_ID"); - put(ConsentMgtDAOConstants.CONSENT_TYPES, "OBC.CONSENT_TYPE"); - put(ConsentMgtDAOConstants.CONSENT_STATUSES, "OBC.CURRENT_STATUS"); - put(ConsentMgtDAOConstants.USER_IDS, "OCAR.USER_ID"); - } - }; - - public OracleConsentCoreDAOImpl(ConsentMgtOracleDBQueries sqlStatements) { - - super(sqlStatements); - } - - @Override - public ArrayList searchConsents(Connection connection, ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, - Long toTime, Integer limit, Integer offset) - throws OBConsentDataRetrievalException { - - boolean shouldLimit = true; - boolean shouldOffset = true; - int parameterIndex = 0; - Map applicableConditionsMap = new HashMap<>(); - - validateAndSetSearchConditions(applicableConditionsMap, consentIDs, clientIDs, consentTypes, consentStatuses); - - if (limit == null) { - shouldLimit = false; - } - if (offset == null) { - shouldOffset = false; - } - - // logic to set the prepared statement - String constructedConditions = - ConsentDAOUtils.constructConsentSearchPreparedStatement(applicableConditionsMap); - - String userIDFilterCondition = ""; - Map userIdMap = new HashMap<>(); - if (CollectionUtils.isNotEmpty(userIDs)) { - userIdMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.USER_IDS), userIDs); - userIDFilterCondition = ConsentDAOUtils.constructUserIdListFilterCondition(userIdMap); - } - String searchConsentsPreparedStatement = - sqlStatements.getSearchConsentsPreparedStatement(constructedConditions, shouldLimit, - shouldOffset, userIDFilterCondition); - - try (PreparedStatement searchConsentsPreparedStmt = - connection.prepareStatement(searchConsentsPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_UPDATABLE)) { - - //determine order of user Ids to set - if (CollectionUtils.isNotEmpty(userIDs)) { - Map orderedUserIdsMap = ConsentDAOUtils - .determineOrderOfParamsToSet(userIDFilterCondition, userIdMap, COLUMNS_MAP); - parameterIndex = setDynamicConsentSearchParameters(searchConsentsPreparedStmt, orderedUserIdsMap, - ++parameterIndex); - parameterIndex = parameterIndex - 1; - } - - /* Since we don't know the order of the set condition clauses, have to determine the order of them to set - the actual values to the prepared statement */ - Map orderedParamsMap = ConsentDAOUtils - .determineOrderOfParamsToSet(constructedConditions, applicableConditionsMap, COLUMNS_MAP); - parameterIndex = setDynamicConsentSearchParameters(searchConsentsPreparedStmt, orderedParamsMap, - ++parameterIndex); - parameterIndex = parameterIndex - 1; - - log.debug("Setting parameters to prepared statement to search consents"); - - if (fromTime != null) { - searchConsentsPreparedStmt.setLong(++parameterIndex, fromTime); - } else { - searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); - } - - if (toTime != null) { - searchConsentsPreparedStmt.setLong(++parameterIndex, toTime); - } else { - searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); - } - - if (offset != null && limit != null) { - searchConsentsPreparedStmt.setInt(++parameterIndex, offset); - } - if (limit != null) { - searchConsentsPreparedStmt.setInt(++parameterIndex, limit); - } - - ArrayList detailedConsentResources = new ArrayList<>(); - - try (ResultSet resultSet = searchConsentsPreparedStmt.executeQuery()) { - if (resultSet.isBeforeFirst()) { - int resultSetSize = getResultSetSize(resultSet); - detailedConsentResources = constructDetailedConsentsSearchResult(resultSet, resultSetSize); - } - return detailedConsentResources; - } catch (SQLException e) { - log.error("Error occurred while searching detailed consent resources", e); - throw new OBConsentDataRetrievalException("Error occurred while searching detailed " + - "consent resources", e); - } - } catch (SQLException e) { - log.error(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); - throw new OBConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); - } - } - - ArrayList constructDetailedConsentsSearchResult(ResultSet resultSet, int resultSetSize) - throws SQLException { - - ArrayList detailedConsentResources = new ArrayList<>(); - - while (resultSet.next()) { - - Map consentAttributesMap = new HashMap<>(); - ArrayList consentMappingResources = new ArrayList<>(); - ArrayList authorizationResources = new ArrayList<>(); - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - - setConsentDataToDetailedConsentInSearchResponse(resultSet, detailedConsentResource); - - // Set consent attributes to map if available - if (resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) != null && - StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) - .replaceAll(GROUP_BY_SEPARATOR, ""))) { - // fetch attribute keys and values from group_concat - String[] attKeys = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY).split(GROUP_BY_SEPARATOR); - String[] attValues = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE).split(GROUP_BY_SEPARATOR); - // check if all attribute keys has values - if (attKeys.length == attValues.length) { - for (int index = 0; index < attKeys.length; index++) { - if (!attKeys[index].isEmpty()) { - consentAttributesMap.put(attKeys[index], attValues[index]); - } - } - } - } - // Set authorization data - setAuthorizationDataInResponseForGroupedQuery(authorizationResources, resultSet, - detailedConsentResource.getConsentID()); - // Set consent account mapping data if available - setAccountConsentMappingDataInResponse(consentMappingResources, resultSet); - - detailedConsentResource.setConsentAttributes(consentAttributesMap); - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - detailedConsentResources.add(detailedConsentResource); - - } - return detailedConsentResources; - } - - void setConsentDataToDetailedConsentInSearchResponse(ResultSet resultSet, - DetailedConsentResource detailedConsentResource) - throws SQLException { - - Optional consentId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional clientId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional receipt = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.RECEIPT) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional createdTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_CREATED_TIME) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional consentUpdatedTime = Arrays.stream( - resultSet.getString(ConsentMgtDAOConstants.CONSENT_UPDATED_TIME) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional consentType = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional currentStatus = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional frequency = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_FREQUENCY) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional validityTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.VALIDITY_TIME) - .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); - Optional recurringIndicator = - Optional.of(resultSet.getBoolean(ConsentMgtDAOConstants.RECURRING_INDICATOR)); - - if (consentId.isPresent() && clientId.isPresent()) { - detailedConsentResource.setConsentID(consentId.get()); - detailedConsentResource.setClientID(clientId.get()); - } else { - throw new SQLException("CLIENT_ID and CONSENT_ID could not be null."); - } - receipt.ifPresent(detailedConsentResource::setReceipt); - consentType.ifPresent(detailedConsentResource::setConsentType); - currentStatus.ifPresent(detailedConsentResource::setCurrentStatus); - createdTime.ifPresent(e -> detailedConsentResource.setCreatedTime(Long.parseLong(e))); - consentUpdatedTime.ifPresent(e -> detailedConsentResource.setUpdatedTime(Long.parseLong(e))); - frequency.ifPresent(e -> detailedConsentResource.setConsentFrequency(Integer.parseInt(e))); - validityTime.ifPresent(e -> detailedConsentResource.setValidityPeriod(Long.parseLong(e))); - recurringIndicator.ifPresent(detailedConsentResource::setRecurringIndicator); - } - - protected void setAuthorizationDataInResponseForGroupedQuery(ArrayList - authorizationResources, - ResultSet resultSet, String consentId) - throws SQLException { - - //identify duplicate auth data - Set authIdSet = new HashSet<>(); - - // fetch values from group_concat - String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_ID).split(GROUP_BY_SEPARATOR) : null; - String[] authTypes = resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE).split(GROUP_BY_SEPARATOR) : null; - String[] authStatues = resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS).split(GROUP_BY_SEPARATOR) : null; - String[] updatedTimes = resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME) != null ? - resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME).split(GROUP_BY_SEPARATOR) : null; - String[] userIds = resultSet.getString(ConsentMgtDAOConstants.USER_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.USER_ID).split(GROUP_BY_SEPARATOR) : null; - - for (int index = 0; index < (authIds != null ? authIds.length : 0); index++) { - if (!authIdSet.contains(authIds[index])) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authIdSet.add(authIds[index]); - authorizationResource.setAuthorizationID(authIds[index]); - authorizationResource.setConsentID(consentId); - if (authTypes != null && authTypes.length > index) { - authorizationResource.setAuthorizationType(authTypes[index]); - } - if (authStatues != null && authStatues.length > index) { - authorizationResource.setAuthorizationStatus(authStatues[index]); - } - if (updatedTimes != null && updatedTimes.length > index) { - authorizationResource.setUpdatedTime(Long.parseLong(updatedTimes[index])); - } - if (userIds != null && userIds.length > index) { - authorizationResource.setUserID(userIds[index]); - } - authorizationResources.add(authorizationResource); - } - } - - } - - protected void setAccountConsentMappingDataInResponse(ArrayList consentMappingResources, - ResultSet resultSet) throws SQLException { - - //identify duplicate mappingIds - Set mappingIdSet = new HashSet<>(); - - // fetch values from group_concat - String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; - String[] mappingIds = resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; - String[] accountIds = resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID) != null ? - resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID).split(GROUP_BY_SEPARATOR) : null; - String[] mappingStatues = resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) != null ? - resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS).split(GROUP_BY_SEPARATOR) : null; - String[] permissions = resultSet.getString(ConsentMgtDAOConstants.PERMISSION) != null ? - resultSet.getString(ConsentMgtDAOConstants.PERMISSION).split(GROUP_BY_SEPARATOR) : null; - - for (int index = 0; index < (mappingIds != null ? mappingIds.length : 0); index++) { - if (!mappingIdSet.contains(mappingIds[index])) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - if (authIds != null && authIds.length > index) { - consentMappingResource.setAuthorizationID(authIds[index]); - } - consentMappingResource.setMappingID(mappingIds[index]); - if (accountIds != null && accountIds.length > index) { - consentMappingResource.setAccountID(accountIds[index]); - } - if (mappingStatues != null && mappingStatues.length > index) { - consentMappingResource.setMappingStatus(mappingStatues[index]); - } - if (permissions != null && permissions.length > index) { - consentMappingResource.setPermission(permissions[index]); - } - consentMappingResources.add(consentMappingResource); - mappingIdSet.add(mappingIds[index]); - } - } - - } - - void validateAndSetSearchConditions(Map applicableConditionsMap, ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses) { - - log.debug("Validate applicable search conditions"); - - if (CollectionUtils.isNotEmpty(consentIDs)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_IDS), consentIDs); - } - if (CollectionUtils.isNotEmpty(clientIDs)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CLIENT_IDS), clientIDs); - } - if (CollectionUtils.isNotEmpty(consentTypes)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_TYPES), consentTypes); - } - if (CollectionUtils.isNotEmpty(consentStatuses)) { - applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_STATUSES), consentStatuses); - } - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/AuthorizationResource.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/AuthorizationResource.java deleted file mode 100644 index 2641460f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/AuthorizationResource.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -/** - * Model for the Authorization resource. - */ -public class AuthorizationResource { - - private String authorizationID; - private String consentID; - private String userID; - private String authorizationStatus; - private String authorizationType; - private long updatedTime; - - public AuthorizationResource() { - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public AuthorizationResource(String consentID, String userID, String authorizationStatus, - String authorizationType, long updatedTime) { - this.consentID = consentID; - this.userID = userID; - this.authorizationStatus = authorizationStatus; - this.authorizationType = authorizationType; - this.updatedTime = updatedTime; - - } - public String getAuthorizationID() { - - return authorizationID; - } - - public String getAuthorizationType() { - - return authorizationType; - } - - public void setAuthorizationType(String authorizationType) { - - this.authorizationType = authorizationType; - } - - public void setAuthorizationID(String authorizationID) { - - this.authorizationID = authorizationID; - } - - public String getConsentID() { - - return consentID; - } - - public void setConsentID(String consentID) { - - this.consentID = consentID; - } - - public String getUserID() { - - return userID; - } - - public void setUserID(String userID) { - - this.userID = userID; - } - - public String getAuthorizationStatus() { - - return authorizationStatus; - } - - public void setAuthorizationStatus(String authorizationStatus) { - - this.authorizationStatus = authorizationStatus; - } - - public long getUpdatedTime() { - - return updatedTime; - } - - public void setUpdatedTime(long updatedTime) { - - this.updatedTime = updatedTime; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentAttributes.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentAttributes.java deleted file mode 100644 index 8a1c6783..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentAttributes.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -import java.util.Map; - -/** - * Model for consent attributes. - */ -public class ConsentAttributes { - - private String consentID; - private Map consentAttributes; - - public ConsentAttributes(){ - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public ConsentAttributes(String consentID, Map consentAttributes) { - this.consentID = consentID; - this.consentAttributes = consentAttributes; - } - - public String getConsentID() { - - return consentID; - } - - public void setConsentID(String consentID) { - - this.consentID = consentID; - } - - public Map getConsentAttributes() { - - return consentAttributes; - } - - public void setConsentAttributes(Map consentAttributes) { - - this.consentAttributes = consentAttributes; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentFile.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentFile.java deleted file mode 100644 index 44362f3c..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentFile.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -/** - * Model for the consent file. - */ -public class ConsentFile { - - private String consentID; - private String consentFile; - - public ConsentFile() { - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public ConsentFile(String consentID, String consentFile) { - this.consentID = consentID; - this.consentFile = consentFile; - } - - public String getConsentID() { - - return consentID; - } - - public void setConsentID(String consentID) { - - this.consentID = consentID; - } - - public String getConsentFile() { - - return consentFile; - } - - public void setConsentFile(String consentFile) { - - this.consentFile = consentFile; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentHistoryResource.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentHistoryResource.java deleted file mode 100644 index 8b471d2b..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentHistoryResource.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -import java.util.HashMap; -import java.util.Map; - -/** - * Model for the consent history resource. - */ -public class ConsentHistoryResource { - - private String historyID; - private String consentID; - private long timestamp; - private String reason; - private DetailedConsentResource detailedConsentResource; - private Map changedAttributesJsonDataMap; - - public ConsentHistoryResource() { - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public ConsentHistoryResource(String consentID, String historyID) { - - this.consentID = consentID; - this.historyID = historyID; - this.changedAttributesJsonDataMap = new HashMap<>(); - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - public String getReason() { - return reason; - } - - public void setReason(String reason) { - this.reason = reason; - } - - public DetailedConsentResource getDetailedConsentResource() { - return detailedConsentResource; - } - - public void setDetailedConsentResource(DetailedConsentResource detailedConsentResource) { - this.detailedConsentResource = detailedConsentResource; - } - - public Map getChangedAttributesJsonDataMap() { - return changedAttributesJsonDataMap; - } - - public void setChangedAttributesJsonDataMap(Map changedAttributesJsonDataMap) { - this.changedAttributesJsonDataMap = changedAttributesJsonDataMap; - } - - public String getConsentID() { - return consentID; - } - - public void setConsentID(String consentID) { - this.consentID = consentID; - } - - public String getHistoryID() { - return historyID; - } - - public void setHistoryID(String historyID) { - this.historyID = historyID; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentMappingResource.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentMappingResource.java deleted file mode 100644 index 702435c8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentMappingResource.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -/** - * Model for consent mapping resource. - */ -public class ConsentMappingResource { - - private String mappingID; - private String authorizationID; - private String accountID; - private String permission; - private String mappingStatus; - - public ConsentMappingResource() { - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public ConsentMappingResource(String authorizationID, String accountID, String permission, - String mappingStatus) { - this.authorizationID = authorizationID; - this.accountID = accountID; - this.permission = permission; - this.mappingStatus = mappingStatus; - } - - public String getMappingID() { - - return mappingID; - } - - public void setMappingID(String mappingID) { - - this.mappingID = mappingID; - } - - public String getAuthorizationID() { - - return authorizationID; - } - - public void setAuthorizationID(String authorizationID) { - - this.authorizationID = authorizationID; - } - - public String getAccountID() { - - return accountID; - } - - public void setAccountID(String accountID) { - - this.accountID = accountID; - } - - public String getPermission() { - - return permission; - } - - public void setPermission(String permission) { - - this.permission = permission; - } - - public String getMappingStatus() { - - return mappingStatus; - } - - public void setMappingStatus(String mappingStatus) { - - this.mappingStatus = mappingStatus; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentResource.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentResource.java deleted file mode 100644 index c1bc3309..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentResource.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -import java.util.Map; - -/** - * Model for the consent resource. - */ -public class ConsentResource { - - private String consentID; - private String clientID; - private String receipt; - private String consentType; - private int consentFrequency; - private long validityPeriod; - private boolean recurringIndicator; - private String currentStatus; - private long createdTime; - private long updatedTime; - - public ConsentResource() { - } - - public ConsentResource(String clientID, String receipt, String consentType, String currentStatus) { - this.clientID = clientID; - this.receipt = receipt; - this.consentType = consentType; - this.currentStatus = currentStatus; - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public ConsentResource(String consentID, String clientID, String receipt, String consentType, - int consentFrequency, long validityPeriod, boolean recurringIndicator, - String currentStatus, long createdTime, long updatedTime) { - this.consentID = consentID; - this.clientID = clientID; - this.receipt = receipt; - this.consentType = consentType; - this.consentFrequency = consentFrequency; - this.validityPeriod = validityPeriod; - this.recurringIndicator = recurringIndicator; - this.currentStatus = currentStatus; - this.createdTime = createdTime; - this.updatedTime = updatedTime; - } - - private Map consentAttributes; - - public long getUpdatedTime() { - - return updatedTime; - } - - public void setUpdatedTime(long updatedTime) { - - this.updatedTime = updatedTime; - } - - public Map getConsentAttributes() { - - return consentAttributes; - } - - public void setConsentAttributes(Map consentAttributes) { - - this.consentAttributes = consentAttributes; - } - - public String getConsentID() { - - return consentID; - } - - public void setConsentID(String consentID) { - - this.consentID = consentID; - } - - public String getClientID() { - - return clientID; - } - - public void setClientID(String clientID) { - - this.clientID = clientID; - } - - public String getReceipt() { - - return receipt; - } - - public void setReceipt(String receipt) { - - this.receipt = receipt; - } - - public String getConsentType() { - - return consentType; - } - - public void setConsentType(String consentType) { - - this.consentType = consentType; - } - - public int getConsentFrequency() { - - return consentFrequency; - } - - public void setConsentFrequency(int consentFrequency) { - - this.consentFrequency = consentFrequency; - } - - public long getValidityPeriod() { - - return validityPeriod; - } - - public void setValidityPeriod(long validityPeriod) { - - this.validityPeriod = validityPeriod; - } - - public boolean isRecurringIndicator() { - - return recurringIndicator; - } - - public void setRecurringIndicator(boolean recurringIndicator) { - - this.recurringIndicator = recurringIndicator; - } - - public String getCurrentStatus() { - - return currentStatus; - } - - public void setCurrentStatus(String currentStatus) { - - this.currentStatus = currentStatus; - } - - public long getCreatedTime() { - - return createdTime; - } - - public void setCreatedTime(long createdTime) { - - this.createdTime = createdTime; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentStatusAuditRecord.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentStatusAuditRecord.java deleted file mode 100644 index c1f01240..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/ConsentStatusAuditRecord.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -/** - * Model for consent status audit record resource. - */ -public class ConsentStatusAuditRecord { - - private String statusAuditID; - private String consentID; - private String currentStatus; - private long actionTime; - private String reason; - private String actionBy; - private String previousStatus; - - public ConsentStatusAuditRecord() { - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public ConsentStatusAuditRecord(String consentID, String currentStatus, long actionTime, - String reason, String actionBy, String previousStatus) { - this.consentID = consentID; - this.currentStatus = currentStatus; - this.actionTime = actionTime; - this.reason = reason; - this.actionBy = actionBy; - this.previousStatus = previousStatus; - } - - public String getStatusAuditID() { - - return statusAuditID; - } - - public void setStatusAuditID(String statusAuditID) { - - this.statusAuditID = statusAuditID; - } - - public String getConsentID() { - - return consentID; - } - - public void setConsentID(String consentID) { - - this.consentID = consentID; - } - - public String getCurrentStatus() { - - return currentStatus; - } - - public void setCurrentStatus(String currentStatus) { - - this.currentStatus = currentStatus; - } - - public long getActionTime() { - - return actionTime; - } - - public void setActionTime(long actionTime) { - - this.actionTime = actionTime; - } - - public String getReason() { - - return reason; - } - - public void setReason(String reason) { - - this.reason = reason; - } - - public String getActionBy() { - - return actionBy; - } - - public void setActionBy(String actionBy) { - - this.actionBy = actionBy; - } - - public String getPreviousStatus() { - - return previousStatus; - } - - public void setPreviousStatus(String previousStatus) { - - this.previousStatus = previousStatus; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/DetailedConsentResource.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/DetailedConsentResource.java deleted file mode 100644 index e99239e4..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/models/DetailedConsentResource.java +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.models; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -import java.util.ArrayList; -import java.util.Map; - -/** - * Model for Detailed Consent Resource. - */ -public class DetailedConsentResource { - - private String consentID; - private String clientID; - private String receipt; - private String consentType; - private String currentStatus; - private int consentFrequency; - private long validityPeriod; - private long createdTime; - private long updatedTime; - private boolean recurringIndicator; - private Map consentAttributes; - private ArrayList authorizationResources; - private ArrayList consentMappingResources; - - public DetailedConsentResource() { - - } - - @Generated(message = "Excluding constructor because setter methods are explicitly called") - public DetailedConsentResource(String consentID, String clientID, String receipt, String consentType, - String currentStatus, int consentFrequency, long validityPeriod, long createdTime, - long updatedTime, boolean recurringIndicator, - Map consentAttributes, - ArrayList authorizationResources, - ArrayList consentMappingResources) { - this.consentID = consentID; - this.clientID = clientID; - this.receipt = receipt; - this.consentType = consentType; - this.currentStatus = currentStatus; - this.consentFrequency = consentFrequency; - this.validityPeriod = validityPeriod; - this.createdTime = createdTime; - this.updatedTime = updatedTime; - this.recurringIndicator = recurringIndicator; - this.consentAttributes = consentAttributes; - this.authorizationResources = authorizationResources; - this.consentMappingResources = consentMappingResources; - - } - - public long getUpdatedTime() { - - return updatedTime; - } - - public void setUpdatedTime(long updatedTime) { - - this.updatedTime = updatedTime; - } - - public String getConsentID() { - - return consentID; - } - - public void setConsentID(String consentID) { - - this.consentID = consentID; - } - - public String getClientID() { - - return clientID; - } - - public void setClientID(String clientID) { - - this.clientID = clientID; - } - - public String getReceipt() { - - return receipt; - } - - public void setReceipt(String receipt) { - - this.receipt = receipt; - } - - public String getConsentType() { - - return consentType; - } - - public void setConsentType(String consentType) { - - this.consentType = consentType; - } - - public int getConsentFrequency() { - - return consentFrequency; - } - - public void setConsentFrequency(int consentFrequency) { - - this.consentFrequency = consentFrequency; - } - - public long getValidityPeriod() { - - return validityPeriod; - } - - public void setValidityPeriod(long validityPeriod) { - - this.validityPeriod = validityPeriod; - } - - public boolean isRecurringIndicator() { - - return recurringIndicator; - } - - public void setRecurringIndicator(boolean recurringIndicator) { - - this.recurringIndicator = recurringIndicator; - } - - public String getCurrentStatus() { - - return currentStatus; - } - - public void setCurrentStatus(String currentStatus) { - - this.currentStatus = currentStatus; - } - - public long getCreatedTime() { - - return createdTime; - } - - public void setCreatedTime(long createdTime) { - - this.createdTime = createdTime; - } - - public Map getConsentAttributes() { - - return consentAttributes; - } - - public void setConsentAttributes(Map consentAttributes) { - - this.consentAttributes = consentAttributes; - } - - public ArrayList getAuthorizationResources() { - - return authorizationResources; - } - - public void setAuthorizationResources(ArrayList authorizationResources) { - - this.authorizationResources = authorizationResources; - } - - public ArrayList getConsentMappingResources() { - - return consentMappingResources; - } - - public void setConsentMappingResources(ArrayList consentMappingResources) { - - this.consentMappingResources = consentMappingResources; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/persistence/ConsentStoreInitializer.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/persistence/ConsentStoreInitializer.java deleted file mode 100644 index bff6682c..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/persistence/ConsentStoreInitializer.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.persistence; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.common.persistence.JDBCRetentionDataPersistenceManager; -import com.wso2.openbanking.accelerator.consent.mgt.dao.ConsentCoreDAO; -import com.wso2.openbanking.accelerator.consent.mgt.dao.impl.ConsentCoreDAOImpl; -import com.wso2.openbanking.accelerator.consent.mgt.dao.impl.MssqlConsentCoreDAOImpl; -import com.wso2.openbanking.accelerator.consent.mgt.dao.impl.OracleConsentCoreDAOImpl; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtCommonDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtMssqlDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtOracleDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtPostgresDBQueries; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * This class handles consent DAO layer initiation with the relevant SQL statements per database types. - */ -public class ConsentStoreInitializer { - - private static final String MYSQL = "MySQL"; - private static final String H2 = "H2"; - private static final String MICROSOFT = "Microsoft"; - private static final String MS_SQL = "MSSQL"; - private static final String POSTGRE = "PostgreSQL"; - private static final String ORACLE = "Oracle"; - private static ConsentCoreDAO consentCoreDAO = null; - private static ConsentCoreDAO consentRetentionDAO = null; - - /** - * Return the DAO implementation initialized for the relevant database type. - * - * @return the dao implementation - * @throws ConsentManagementException thrown if an error occurs when getting the database connection - */ - public static synchronized ConsentCoreDAO getInitializedConsentCoreDAOImpl() throws ConsentManagementException { - - if (consentCoreDAO == null) { - consentCoreDAO = getDaoInstance(PersistenceManager.CONSENT_PERSISTENCE_MANAGER); - } - return consentCoreDAO; - } - - /** - * Return the DAO implementation initialized for the relevant database type. - * - * @return the dao implementation - * @throws ConsentManagementException thrown if an error occurs when getting the database connection - */ - public static synchronized ConsentCoreDAO getInitializedConsentRetentionDAOImpl() - throws ConsentManagementException { - - if (consentRetentionDAO == null) { - consentRetentionDAO = getDaoInstance(PersistenceManager.RETENTION_PERSISTENCE_MANAGER); - } - return consentRetentionDAO; - } - - private static ConsentCoreDAO getDaoInstance(PersistenceManager persistenceManager) - throws ConsentManagementException { - - Connection connection; - try { - if (persistenceManager.equals(PersistenceManager.CONSENT_PERSISTENCE_MANAGER)) { - connection = JDBCPersistenceManager.getInstance().getDBConnection(); - } else { - connection = JDBCRetentionDataPersistenceManager.getInstance().getDBConnection(); - } - String driverName = connection.getMetaData().getDriverName(); - - ConsentCoreDAO dao; - if (driverName.contains(MYSQL)) { - dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); - } else if (driverName.contains(H2)) { - dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); - } else if (driverName.contains(MS_SQL) || driverName.contains(MICROSOFT)) { - dao = new MssqlConsentCoreDAOImpl(new ConsentMgtMssqlDBQueries()); - } else if (driverName.contains(POSTGRE)) { - dao = new ConsentCoreDAOImpl(new ConsentMgtPostgresDBQueries()); - } else if (driverName.contains(ORACLE)) { - dao = new OracleConsentCoreDAOImpl(new ConsentMgtOracleDBQueries()); - } else { - throw new ConsentManagementException("Unhandled DB driver: " + driverName + " detected : "); - } - return dao; - } catch (SQLException e) { - throw new ConsentManagementException("Error while getting the database connection : ", e); - } - } - - /** - * PersistenceManager types enum. - */ - public enum PersistenceManager { - CONSENT_PERSISTENCE_MANAGER, - RETENTION_PERSISTENCE_MANAGER - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtCommonDBQueries.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtCommonDBQueries.java deleted file mode 100644 index 48a27b56..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtCommonDBQueries.java +++ /dev/null @@ -1,474 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.queries; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import org.apache.commons.lang.StringUtils; - -/** - * The common database queries used by the consent management DAO layer. - */ -public class ConsentMgtCommonDBQueries { - - public String getStoreConsentPreparedStatement() { - - return "INSERT INTO OB_CONSENT (CONSENT_ID, RECEIPT, CREATED_TIME, UPDATED_TIME, CLIENT_ID, CONSENT_TYPE, " + - "CURRENT_STATUS, CONSENT_FREQUENCY, VALIDITY_TIME, RECURRING_INDICATOR) VALUES (?, ?, ?, ?, ?, ?, ?, " + - "?, ?, ?)"; - } - - public String getStoreAuthorizationPreparedStatement() { - - return "INSERT INTO OB_CONSENT_AUTH_RESOURCE (AUTH_ID, CONSENT_ID, AUTH_TYPE, USER_ID, AUTH_STATUS, " + - "UPDATED_TIME) VALUES (?, ?, ?, ?, ?, ?)"; - } - - public String getStoreConsentMappingPreparedStatement() { - - return "INSERT INTO OB_CONSENT_MAPPING (MAPPING_ID, AUTH_ID, ACCOUNT_ID, PERMISSION, MAPPING_STATUS) VALUES " + - "(?, ?, ?, ?, ?)"; - } - - public String getStoreConsentStatusAuditRecordPreparedStatement() { - - return "INSERT INTO OB_CONSENT_STATUS_AUDIT (STATUS_AUDIT_ID, CONSENT_ID, CURRENT_STATUS, ACTION_TIME, " + - "REASON, ACTION_BY, PREVIOUS_STATUS) VALUES (?, ?, ?, ?, ?, ?, ?)"; - } - - public String getStoreConsentAttributesPreparedStatement() { - - return "INSERT INTO OB_CONSENT_ATTRIBUTE (CONSENT_ID, ATT_KEY, ATT_VALUE) VALUES (?, ?, ?)"; - } - - public String getStoreConsentFilePreparedStatement() { - - return "INSERT INTO OB_CONSENT_FILE (CONSENT_ID, CONSENT_FILE) VALUES (?, ?)"; - } - - public String getUpdateConsentStatusPreparedStatement() { - - return "UPDATE OB_CONSENT SET CURRENT_STATUS = ?, UPDATED_TIME = ? WHERE CONSENT_ID = ?"; - } - - public String getUpdateConsentMappingStatusPreparedStatement() { - - return "UPDATE OB_CONSENT_MAPPING SET MAPPING_STATUS = ? WHERE MAPPING_ID = ?"; - } - - public String getUpdateConsentMappingPermissionPreparedStatement() { - - return "UPDATE OB_CONSENT_MAPPING SET PERMISSION = ? WHERE MAPPING_ID = ?"; - } - - public String getUpdateAuthorizationStatusPreparedStatement() { - - return "UPDATE OB_CONSENT_AUTH_RESOURCE SET AUTH_STATUS = ?, UPDATED_TIME = ? WHERE AUTH_ID = ?"; - } - - public String getUpdateAuthorizationUserPreparedStatement() { - - return "UPDATE OB_CONSENT_AUTH_RESOURCE SET USER_ID = ?, UPDATED_TIME = ? WHERE AUTH_ID = ?"; - } - - public String getGetConsentFileResourcePreparedStatement(boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "SELECT * FROM " + tablePrefix + "OB_CONSENT_FILE WHERE CONSENT_ID = ?"; - } - - public String getGetConsentAttributesPreparedStatement() { - - return "SELECT * FROM OB_CONSENT_ATTRIBUTE WHERE CONSENT_ID = ?"; - } - - public String getGetConsentPreparedStatement() { - - return "SELECT * FROM OB_CONSENT WHERE CONSENT_ID = ?"; - } - - public String getGetDetailedConsentPreparedStatement(boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "SELECT obc.CONSENT_ID," + - "RECEIPT, " + - "CLIENT_ID, " + - "CONSENT_TYPE, " + - "CURRENT_STATUS, " + - "CONSENT_FREQUENCY, " + - "VALIDITY_TIME, " + - "RECURRING_INDICATOR, " + - "CREATED_TIME AS CONSENT_CREATED_TIME, " + - "obc.UPDATED_TIME AS CONSENT_UPDATED_TIME, " + - "ca.ATT_KEY, " + - "ca.ATT_VALUE, " + - "ocar.AUTH_ID, " + - "ocar.AUTH_STATUS, " + - "ocar.AUTH_TYPE, " + - "ocar.UPDATED_TIME AS AUTH_UPDATED_TIME, " + - "ocar.USER_ID, " + - "cm.ACCOUNT_ID, " + - "cm.MAPPING_ID, " + - "cm.MAPPING_STATUS, " + - "cm.PERMISSION " + - "FROM " + - tablePrefix + "OB_CONSENT obc " + - "LEFT JOIN " + - tablePrefix + "OB_CONSENT_ATTRIBUTE ca ON obc.CONSENT_ID=ca.CONSENT_ID " + - "LEFT JOIN " + - tablePrefix + "OB_CONSENT_AUTH_RESOURCE ocar ON obc.CONSENT_ID=ocar.CONSENT_ID " + - "LEFT JOIN " + - tablePrefix + "OB_CONSENT_MAPPING cm ON ocar.AUTH_ID=cm.AUTH_ID " + - "WHERE obc.CONSENT_ID = ?"; - } - - public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, - String userIdFilterClause) { - - String selectClause = "(SELECT * FROM OB_CONSENT " + whereClause + ")"; - String joinType = "LEFT "; - if (StringUtils.isNotEmpty(userIdFilterClause)) { - joinType = "INNER "; - userIdFilterClause = "AND " + userIdFilterClause; - } - - StringBuilder query = new StringBuilder("SELECT OBC.CONSENT_ID, " + - "RECEIPT, " + - "CLIENT_ID, " + - "CONSENT_TYPE, " + - "OBC.CURRENT_STATUS AS CURRENT_STATUS," + - "CONSENT_FREQUENCY," + - "VALIDITY_TIME," + - "RECURRING_INDICATOR," + - "OBC.CREATED_TIME AS CONSENT_CREATED_TIME," + - "OBC.UPDATED_TIME AS CONSENT_UPDATED_TIME," + - "Group_concat(distinct CA.att_key order by CA.att_key SEPARATOR '||' ) AS ATT_KEY, " + - "Group_concat(distinct CA.att_value order by CA.att_key SEPARATOR '||') AS ATT_VALUE, " + - - - "( SELECT Group_concat( OCAR2.auth_id order by OCAR2.auth_id SEPARATOR '||') " + - " FROM OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE OCAR2.consent_id = OBC.consent_id " + - " GROUP BY OCAR2.consent_id ) AS AUTH_ID, " + - - "( SELECT Group_concat(OCAR2.auth_status order by OCAR2.auth_id SEPARATOR '||') " + - " FROM OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE OCAR2.consent_id = OBC.consent_id " + - " GROUP BY OCAR2.consent_id ) AS AUTH_STATUS, " + - - "( SELECT Group_concat(OCAR2.auth_type order by OCAR2.auth_id SEPARATOR '||') " + - " FROM OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE OCAR2.consent_id = OBC.consent_id " + - " GROUP BY OCAR2.consent_id ) AS AUTH_TYPE, " + - - "( SELECT Group_concat(OCAR2.updated_time order by OCAR2.auth_id SEPARATOR '||') " + - " FROM OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE OCAR2.consent_id = OBC.consent_id " + - " GROUP BY OCAR2.consent_id ) AS UPDATED_TIME, " + - - "( SELECT Group_concat(OCAR2.user_id order by OCAR2.auth_id SEPARATOR '||') " + - " FROM OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE OCAR2.consent_id = OBC.consent_id " + - " GROUP BY OCAR2.consent_id ) AS USER_ID," + - - - " ( SELECT Group_concat(OCM2.auth_id order by OCM2.mapping_id SEPARATOR '||') " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE OCAR2.consent_id = OBC.consent_id) AS AUTH_MAPPING_ID , " + - - "( SELECT Group_concat(OCM2.account_id order by OCM2.mapping_id SEPARATOR '||') " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE OCAR2.consent_id = OBC.consent_id) AS ACCOUNT_ID , " + - - "( SELECT Group_concat(OCM2.mapping_id order by OCM2.mapping_id SEPARATOR '||') " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE OCAR2.consent_id = OBC.consent_id) AS MAPPING_ID , " + - - "( SELECT Group_concat(OCM2.mapping_status order by OCM2.mapping_id SEPARATOR '||') " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE OCAR2.consent_id = OBC.consent_id) AS MAPPING_STATUS , " + - - "( SELECT Group_concat(OCM2.permission order by OCM2.mapping_id SEPARATOR '||') " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE OCAR2.consent_id = OBC.consent_id) AS PERMISSION " + - - "FROM " + - selectClause + - "AS OBC " + - "LEFT JOIN OB_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + - joinType + "JOIN OB_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " - + userIdFilterClause + - "LEFT JOIN OB_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID WHERE " + - "(OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + - "AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) " + - "group by OBC.CONSENT_ID ORDER BY OBC.UPDATED_TIME DESC "); - - if (shouldLimit && shouldOffset) { - query.append(" LIMIT ? OFFSET ? "); - } else if (shouldLimit) { - query.append(" LIMIT ? "); - } - - return query.toString(); - } - - public String getGetConsentWithConsentAttributesPreparedStatement() { - - return "SELECT OB_CONSENT.CONSENT_ID, RECEIPT, CREATED_TIME, UPDATED_TIME, CLIENT_ID, CONSENT_TYPE, " + - "CURRENT_STATUS, CONSENT_FREQUENCY, VALIDITY_TIME, RECURRING_INDICATOR, " + - "OB_CONSENT_ATTRIBUTE.ATT_KEY, OB_CONSENT_ATTRIBUTE.ATT_VALUE FROM OB_CONSENT RIGHT JOIN " + - "OB_CONSENT_ATTRIBUTE ON OB_CONSENT.CONSENT_ID = OB_CONSENT_ATTRIBUTE.CONSENT_ID WHERE OB_CONSENT" + - ".CONSENT_ID = ?"; - } - - public String getGetConsentAttributesByNamePreparedStatement() { - - return "SELECT CONSENT_ID, ATT_VALUE FROM OB_CONSENT_ATTRIBUTE WHERE ATT_KEY = ?"; - } - - public String getConsentIdByConsentAttributeNameAndValuePreparedStatement() { - - - return "SELECT CONSENT_ID FROM OB_CONSENT_ATTRIBUTE WHERE ATT_KEY = ? AND ATT_VALUE = ?"; - } - - public String getGetAuthorizationResourcePreparedStatement() { - - return "SELECT * FROM OB_CONSENT_AUTH_RESOURCE WHERE AUTH_ID = ?"; - } - - public String getGetConsentMappingResourcesPreparedStatement() { - - return "SELECT * FROM OB_CONSENT_MAPPING WHERE AUTH_ID = ?"; - } - - public String getGetConsentMappingResourcesForStatusPreparedStatement() { - - return "SELECT * FROM OB_CONSENT_MAPPING WHERE AUTH_ID = ? AND MAPPING_STATUS = ?"; - } - - public String getDeleteConsentAttributePreparedStatement() { - - return "DELETE FROM OB_CONSENT_ATTRIBUTE WHERE CONSENT_ID = ? AND ATT_KEY = ?"; - } - - public String getGetConsentStatusAuditRecordsPreparedStatement(boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "SELECT * FROM " + tablePrefix + "OB_CONSENT_STATUS_AUDIT WHERE CONSENT_ID = COALESCE(?, CONSENT_ID) " + - "AND CURRENT_STATUS = COALESCE(?, CURRENT_STATUS) AND ACTION_BY = COALESCE(?, ACTION_BY) " + - "AND STATUS_AUDIT_ID = COALESCE (?, STATUS_AUDIT_ID) AND ACTION_TIME >= COALESCE(?, ACTION_TIME) " + - "AND ACTION_TIME <= COALESCE(?, ACTION_TIME)"; - } - - public String getSearchAuthorizationResourcesPreparedStatement(String whereClause) { - - return "SELECT * FROM OB_CONSENT_AUTH_RESOURCE" + whereClause; - } - - public String getUpdateConsentReceiptPreparedStatement() { - - return "UPDATE OB_CONSENT SET RECEIPT = ? WHERE CONSENT_ID = ?"; - } - - public String getUpdateConsentValidityTimePreparedStatement() { - - return "UPDATE OB_CONSENT SET VALIDITY_TIME = ?, UPDATED_TIME = ? WHERE CONSENT_ID = ?"; - } - - public String getSearchExpiringConsentPreparedStatement(String statusesEligibleForExpirationCondition) { - - return "SELECT OBC.CONSENT_ID " + - " FROM OB_CONSENT_ATTRIBUTE CA " + - " JOIN OB_CONSENT OBC " + - " ON CA.CONSENT_ID = OBC.CONSENT_ID " + - " WHERE CA.ATT_KEY = ? AND OBC.CURRENT_STATUS IN " + statusesEligibleForExpirationCondition; - } - - public String getInsertConsentHistoryPreparedStatement() { - - return "INSERT INTO OB_CONSENT_HISTORY (TABLE_ID, RECORD_ID, HISTORY_ID, CHANGED_VALUES, " + - "REASON, EFFECTIVE_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)"; - } - - public String getGetConsentHistoryPreparedStatement(String whereClause) { - - return "SELECT * FROM OB_CONSENT_HISTORY " + whereClause + "ORDER BY EFFECTIVE_TIMESTAMP DESC"; - } - - /** - * SQL query for delete consent attributes. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query for delete consent attributes - */ - public String getDeleteConsentAttributeByConsentIdPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "OB_CONSENT_ATTRIBUTE WHERE CONSENT_ID = ?"; - } - - /** - * SQL query for delete consent file. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query for delete consent file - */ - public String getDeleteConsentFileResourcePreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "OB_CONSENT_FILE WHERE CONSENT_ID = ?"; - } - - /** - * SQL query for delete consent mapping by auth id. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query for delete consent mapping by auth id - */ - public String getDeleteConsentMappingByAuthIdPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE OBCM FROM " + tablePrefix + "OB_CONSENT_MAPPING OBCM INNER JOIN " + tablePrefix + - "OB_CONSENT_AUTH_RESOURCE OBAR ON OBCM.AUTH_ID = OBAR.AUTH_ID WHERE OBAR.CONSENT_ID = ?"; - } - - /** - * SQL query for delete auth resource. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query for delete auth resource - */ - public String getDeleteAuthorizationResourcePreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "OB_CONSENT_AUTH_RESOURCE WHERE CONSENT_ID = ?"; - } - - /** - * SQL query for consent status audit record. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query for consent status audit record - */ - public String getDeleteConsentStatusAuditRecordsPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "OB_CONSENT_STATUS_AUDIT WHERE CONSENT_ID = ?"; - } - - /** - * SQL query for delete consent. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query for delete consent - */ - public String getDeleteConsentPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "OB_CONSENT WHERE CONSENT_ID = ?"; - } - - /** - * SQL query for get list of consent_ids. - * @param fetchFromRetentionTables whether to fetch from retention tables - * @return SQL query for get list of consent_ids - */ - public String getListOfConsentIdsPreparedStatement(boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "SELECT CONSENT_ID FROM " + tablePrefix + "OB_CONSENT"; - } - - /** - * SQL query for get consent status audit records by consentIds. - * @param whereClause conditions - * @param shouldLimit whether to consider the Limit parameter - * @param shouldOffset whether to consider the Offset parameter - * @param fetchFromRetentionTables whether to fetch from retention tables - * @return SQL query for get consent status audit records by consentIds - */ - public String getConsentStatusAuditRecordsByConsentIdsPreparedStatement(String whereClause, boolean shouldLimit, - boolean shouldOffset, - boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - StringBuilder query = - new StringBuilder("SELECT * FROM " + tablePrefix + "OB_CONSENT_STATUS_AUDIT " + whereClause); - - if (shouldLimit && shouldOffset) { - query.append(" LIMIT ? OFFSET ? "); - } else if (shouldLimit) { - query.append(" LIMIT ? "); - } - return query.toString(); - } - - /** - * Util method to get the limit offset order for differentiate oracle and mssql pagination. - * @return is limit is before in prepared statement than offset - */ - public boolean isLimitBeforeThanOffset() { - - return true; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtMssqlDBQueries.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtMssqlDBQueries.java deleted file mode 100644 index d9b68208..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtMssqlDBQueries.java +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.queries; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import org.apache.commons.lang.StringUtils; - -/** - * The Microsoft SQL database queries used by the consent management DAO layer. - */ -public class ConsentMgtMssqlDBQueries extends ConsentMgtCommonDBQueries { - - public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, - String userIdFilterClause) { - - String selectClause = "(SELECT * FROM OB_CONSENT)"; - String joinType = " LEFT "; - - if (StringUtils.isNotEmpty(userIdFilterClause)) { - joinType = " INNER "; - userIdFilterClause = "AND " + userIdFilterClause; - } - - if (whereClause.trim().isEmpty()) { - whereClause = " WHERE "; - } else { - whereClause = whereClause + " AND "; - } - - StringBuilder query = new StringBuilder("SELECT OBC.CONSENT_ID, " + - " (SELECT receipt FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS RECEIPT, " + - " (SELECT client_id FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CLIENT_ID, " + - " (SELECT consent_type FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_TYPE, " + - " (SELECT current_status FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CURRENT_STATUS, " + - " (SELECT consent_frequency FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_FREQUENCY, " + - " (SELECT validity_time FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS VALIDITY_TIME, " + - " (SELECT recurring_indicator FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS RECURRING_INDICATOR, " + - " (SELECT created_time FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_CREATED_TIME, " + - " (SELECT updated_time FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_UPDATED_TIME, " + - - "( SELECT String_agg(att_key , '||') within GROUP (ORDER BY att_key) " + - " FROM OB_CONSENT_ATTRIBUTE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS ATT_KEY, " + - - "( SELECT String_agg(att_value , '||') within GROUP (ORDER BY att_key) " + - " FROM OB_CONSENT_ATTRIBUTE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS ATT_VALUE, " + - - "( SELECT String_agg(auth_id , '||') within GROUP (ORDER BY auth_id) " + - " FROM OB_CONSENT_AUTH_RESOURCE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS AUTH_ID, " + - - "( SELECT String_agg(auth_status , '||') within GROUP (ORDER BY auth_id) " + - " FROM OB_CONSENT_AUTH_RESOURCE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS AUTH_STATUS, " + - - "( SELECT String_agg(auth_type , '||') within GROUP (ORDER BY auth_id) " + - " FROM OB_CONSENT_AUTH_RESOURCE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS AUTH_TYPE, " + - - "( SELECT String_agg(updated_time , '||') within GROUP (ORDER BY auth_id) " + - " FROM OB_CONSENT_AUTH_RESOURCE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS UPDATED_TIME, " + - - "( SELECT String_agg(user_id , '||') within GROUP (ORDER BY auth_id) " + - " FROM OB_CONSENT_AUTH_RESOURCE " + - " WHERE consent_id = OBC.consent_id " + - " GROUP BY consent_id ) AS USER_ID," + - - - "( SELECT String_agg(OCM2.AUTH_ID , '||') within GROUP (ORDER BY OCM2.mapping_id) " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS AUTH_MAPPING_ID , " + - - "( SELECT String_agg(OCM2.account_id , '||') within GROUP (ORDER BY OCM2.mapping_id) " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS ACCOUNT_ID , " + - - "( SELECT String_agg(OCM2.mapping_id , '||') within GROUP (ORDER BY OCM2.mapping_id) " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_ID , " + - - "( SELECT String_agg(OCM2.mapping_status , '||') within GROUP (ORDER BY OCM2.mapping_id) " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_STATUS , " + - - "( SELECT String_agg(OCM2.permission , '||') within GROUP (ORDER BY OCM2.mapping_id) " + - " FROM OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS PERMISSION " + - - - "FROM " + selectClause + "AS OBC " + - "LEFT JOIN OB_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + - joinType + "JOIN OB_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " - + userIdFilterClause + - "LEFT JOIN OB_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID " + whereClause + - " (OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + - " AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) GROUP BY obc.consent_id " + - " ORDER BY UPDATED_TIME DESC "); - - if (shouldLimit && shouldOffset) { - query.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); - } else if (shouldLimit) { - query.append("OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY "); - } - - return query.toString(); - } - - /** - * SQL query for delete consent mapping by auth id. - * @param executeOnRetentionTables execute on retention tables - * @return SQL query - */ - public String getDeleteConsentMappingByAuthIdPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE " + tablePrefix + "OB_CONSENT_MAPPING where MAPPING_ID in (SELECT MAPPING_ID FROM " + - tablePrefix + "OB_CONSENT_MAPPING OBCM INNER JOIN " + tablePrefix + "OB_CONSENT_AUTH_RESOURCE OBAR " + - "ON OBCM.AUTH_ID = OBAR.AUTH_ID WHERE OBAR.CONSENT_ID = ?)"; - } - - /** - * SQL query for get consent status audit records by consentIds. - * @param whereClause conditions - * @param shouldLimit limit - * @param shouldOffset offset - * @param fetchFromRetentionTables fetch from retention tables - * @return SQL query - */ - public String getConsentStatusAuditRecordsByConsentIdsPreparedStatement(String whereClause, boolean shouldLimit, - boolean shouldOffset, - boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - StringBuilder query = - new StringBuilder("SELECT * FROM " + tablePrefix + "OB_CONSENT_STATUS_AUDIT " + whereClause); - - if (shouldLimit && shouldOffset) { - query.append("ORDER BY STATUS_AUDIT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); - } else if (shouldLimit) { - query.append("ORDER BY STATUS_AUDIT_ID OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY "); - } - return query.toString(); - } - - /** - * Util method to get the limit offset order for differentiate oracle and mssql pagination. - * @return is limit is before in prepared statement than offset - */ - public boolean isLimitBeforeThanOffset() { - - return false; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtOracleDBQueries.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtOracleDBQueries.java deleted file mode 100644 index d321977c..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtOracleDBQueries.java +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.queries; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import org.apache.commons.lang.StringUtils; - -/** - * The Oracle database queries used by the consent management DAO layer. - */ -public class ConsentMgtOracleDBQueries extends ConsentMgtCommonDBQueries { - - public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, - String userIdFilterClause) { - - String selectClause = "OB_CONSENT "; - String joinType = "LEFT"; - - if (StringUtils.isNotEmpty(userIdFilterClause)) { - joinType = "INNER"; - userIdFilterClause = "AND " + userIdFilterClause; - } - - if (whereClause.trim().isEmpty()) { - whereClause = " WHERE "; - } else { - whereClause = whereClause + " AND "; - } - - StringBuilder query = new StringBuilder("SELECT OBC.CONSENT_ID, " + - " ( SELECT receipt FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH first 1 rows only ) AS RECEIPT, " + - " (SELECT client_id FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS CLIENT_ID, " + - " (SELECT consent_type FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS CONSENT_TYPE, " + - " (SELECT current_status FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS current_status, " + - " (SELECT consent_frequency FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS CONSENT_FREQUENCY, " + - " (SELECT validity_time FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS VALIDITY_TIME, " + - " (SELECT recurring_indicator FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS RECURRING_INDICATOR, " + - " (SELECT created_time FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS consent_created_time, " + - " (SELECT updated_time FROM OB_CONSENT WHERE consent_id = obc.consent_id " + - " FETCH FIRST 1 rows only ) AS consent_updated_time, " + - - " ( SELECT listagg(att_key || '||') within GROUP (ORDER BY att_key) " + - " FROM ob_consent_attribute " + - " WHERE consent_id = obc.consent_id " + - " GROUP BY consent_id ) AS ATT_KEY, " + - - " ( SELECT listagg(att_value || '||') within GROUP (ORDER BY att_key)" + - " FROM ob_consent_attribute" + - " WHERE consent_id = obc.consent_id" + - " GROUP BY consent_id ) AS ATT_VALUE, " + - - " ( SELECT listagg(auth_id || '||') within GROUP (ORDER BY auth_id)" + - " FROM ob_consent_auth_resource" + - " WHERE consent_id = obc.consent_id" + - " GROUP BY consent_id ) AS AUTH_ID, " + - - " ( SELECT listagg(auth_status || '||') within GROUP (ORDER BY auth_id)" + - " FROM ob_consent_auth_resource" + - " WHERE consent_id = obc.consent_id" + - " GROUP BY consent_id ) AS AUTH_STATUS, " + - - " ( SELECT listagg(auth_type || '||') within GROUP (ORDER BY auth_id) " + - " FROM ob_consent_auth_resource " + - " WHERE consent_id = obc.consent_id " + - " GROUP BY consent_id ) AS AUTH_TYPE, " + - - " ( SELECT listagg(updated_time || '||') within GROUP (ORDER BY auth_id) " + - " FROM ob_consent_auth_resource " + - " WHERE consent_id = obc.consent_id " + - " GROUP BY consent_id ) AS UPDATED_TIME, " + - - " ( SELECT listagg(user_id || '||') within GROUP (ORDER BY auth_id) " + - " FROM ob_consent_auth_resource " + - " WHERE consent_id = obc.consent_id " + - " GROUP BY consent_id ) AS USER_ID, " + - - - " ( SELECT listagg(ocm2.auth_id || '||') within GROUP (ORDER BY ocm2.mapping_id) " + - " FROM ob_consent_mapping ocm2 " + - " JOIN ob_consent_auth_resource ocar2 " + - " ON ocar2.auth_id = ocm2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS AUTH_MAPPING_ID , " + - - " ( SELECT listagg(ocm2.account_id || '||') within GROUP (ORDER BY ocm2.mapping_id) " + - " FROM ob_consent_mapping ocm2 " + - " JOIN ob_consent_auth_resource ocar2 " + - " ON ocar2.auth_id = ocm2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS ACCOUNT_ID , " + - - " ( SELECT listagg(ocm2.mapping_id || '||') within GROUP (ORDER BY ocm2.mapping_id) " + - " FROM ob_consent_mapping ocm2 " + - " JOIN ob_consent_auth_resource ocar2 " + - " ON ocar2.auth_id = ocm2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_ID , " + - - " ( SELECT listagg(ocm2.mapping_status || '||') within GROUP (ORDER BY ocm2.mapping_id) " + - " FROM ob_consent_mapping ocm2 " + - " JOIN ob_consent_auth_resource ocar2 " + - " ON ocar2.auth_id = ocm2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_STATUS , " + - - " ( SELECT listagg(ocm2.permission || '||') within GROUP (ORDER BY ocm2.mapping_id) " + - " FROM ob_consent_mapping ocm2 " + - " JOIN ob_consent_auth_resource ocar2 " + - " ON ocar2.auth_id = ocm2.auth_id " + - " WHERE ocar2.consent_id = obc.consent_id) AS PERMISSION " + - - "FROM " + selectClause + " OBC " + - "LEFT JOIN OB_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + - joinType + " JOIN OB_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " - + userIdFilterClause + - "LEFT JOIN OB_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID " + whereClause + - " (OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + - " AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) GROUP BY obc.consent_id " + - "ORDER BY UPDATED_TIME DESC "); - - if (shouldLimit && shouldOffset) { - query.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); - } else if (shouldLimit) { - query.append("FETCH NEXT ? ROWS ONLY"); - } - return query.toString(); - } - - /** - * SQL query for delete consent mapping by auth id. - * @param executeOnRetentionTables whether to execute on retention tables - * @return SQL query to delete consent mapping by auth id - */ - public String getDeleteConsentMappingByAuthIdPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "OB_CONSENT_MAPPING where MAPPING_ID in (SELECT MAPPING_ID FROM " + - tablePrefix + "OB_CONSENT_MAPPING OBCM INNER JOIN " + tablePrefix + "OB_CONSENT_AUTH_RESOURCE OBAR " + - "ON OBCM.AUTH_ID = OBAR.AUTH_ID WHERE OBAR.CONSENT_ID = ?)"; - } - - /** - * SQL query for get consent status audit records by consentIds. - * @param whereClause conditions - * @param shouldLimit whether limit should be applied - * @param shouldOffset whether offset should be applied - * @param fetchFromRetentionTables whether to fetch from retention tables - * @return SQL query to retrieve consent status audit records by consentIds - */ - public String getConsentStatusAuditRecordsByConsentIdsPreparedStatement(String whereClause, boolean shouldLimit, - boolean shouldOffset, - boolean fetchFromRetentionTables) { - - // table prefix is to fetch from the consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (fetchFromRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - StringBuilder query = - new StringBuilder("SELECT * FROM " + tablePrefix + "OB_CONSENT_STATUS_AUDIT " + whereClause); - - if (shouldLimit && shouldOffset) { - query.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); - } else if (shouldLimit) { - query.append("FETCH NEXT ? ROWS ONLY"); - } - return query.toString(); - } - - /** - * Util method to get the limit offset order for differentiate oracle and mssql pagination. - * @return is limit is before in prepared statement than offset - */ - public boolean isLimitBeforeThanOffset() { - - return false; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtPostgresDBQueries.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtPostgresDBQueries.java deleted file mode 100644 index ec5af0d2..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/queries/ConsentMgtPostgresDBQueries.java +++ /dev/null @@ -1,229 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.queries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import org.apache.commons.lang3.StringUtils; - -/** - * The PostgreSQL database queries used by the consent management DAO layer. - */ -public class ConsentMgtPostgresDBQueries extends ConsentMgtCommonDBQueries { - - /** - * This method returns the detailed consent search query. It constructs the query according to the provided - * parameters dynamically. This queries all consent attributes, authorization resources, mapping resources, consent - * data of the provided consent according to the parameters provided. To avoid fetching same rows multiple times, - * the string_agg function is used to concatenate values using a delimiter. The delimited results are later - * processed and set to the result. - * - * @param whereClause the pre-constructed where dynamic where clause - * @param shouldLimit flag that indicates the limit - * @param shouldOffset flag that indicates the offset - * @param userIdFilterClause the pre-constructed user id filter condition - * @return the constructed prepared statement for consent search function - */ - public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, - String userIdFilterClause) { - - String selectClause = "(SELECT * FROM OB_CONSENT " + whereClause + ")"; - String joinType = "LEFT "; - if (StringUtils.isNotEmpty(userIdFilterClause)) { - joinType = "INNER "; - userIdFilterClause = "AND " + userIdFilterClause; - } - - StringBuilder query = new StringBuilder("SELECT " + - " OBC.CONSENT_ID, " + - " RECEIPT, " + - " CLIENT_ID, " + - " CONSENT_TYPE, " + - " OBC.CURRENT_STATUS AS CURRENT_STATUS, " + - " CONSENT_FREQUENCY, " + - " VALIDITY_TIME, " + - " RECURRING_INDICATOR, " + - " OBC.CREATED_TIME AS CONSENT_CREATED_TIME, " + - " OBC.UPDATED_TIME AS CONSENT_UPDATED_TIME, " + - " String_agg(" + - " CA.att_key :: varchar, '||' order by CA.att_key :: varchar" + - " ) AS ATT_KEY," + - " String_agg(" + - " CA.att_value :: varchar, '||' order by CA.att_key :: varchar" + - " ) AS ATT_VALUE," + - " (" + - " SELECT " + - " String_agg(" + - " OCAR2.auth_id:: varchar, '||' order by OCAR2.auth_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id " + - " GROUP BY " + - " OCAR2.consent_id" + - " ) AS AUTH_ID, " + - " (" + - " SELECT " + - " String_agg(" + - " OCAR2.auth_status :: varchar, '||' order by OCAR2.auth_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id " + - " GROUP BY " + - " OCAR2.consent_id" + - " ) AS AUTH_STATUS, " + - " (" + - " select" + - " String_agg(" + - " OCAR2.auth_type :: varchar, '||' order by OCAR2.auth_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id " + - " GROUP BY " + - " OCAR2.consent_id" + - " ) AS AUTH_TYPE, " + - " (" + - " SELECT " + - " String_agg(" + - " OCAR2.updated_time :: varchar, '||' order by OCAR2.auth_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id " + - " GROUP BY " + - " OCAR2.consent_id" + - " ) AS UPDATED_TIME, " + - " (" + - " SELECT " + - " String_agg(" + - " OCAR2.user_id :: varchar, '||' order by OCAR2.auth_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_AUTH_RESOURCE OCAR2 " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id " + - " GROUP BY " + - " OCAR2.consent_id" + - " ) AS USER_ID, " + - " (" + - " SELECT " + - " String_agg(" + - " OCAR2.auth_id:: varchar, '||' order by OCM2.mapping_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id" + - " ) AS AUTH_MAPPING_ID, " + - " (" + - " SELECT " + - " String_agg(" + - " OCM2.account_id :: varchar, '||' order by OCM2.mapping_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id" + - " ) AS ACCOUNT_ID, " + - " (" + - " SELECT " + - " String_agg(" + - " OCM2.mapping_id :: varchar, '||' order by OCM2.mapping_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id" + - " ) AS MAPPING_ID, " + - " (" + - " SELECT " + - " String_agg(" + - " OCM2.mapping_status :: varchar, '||' order by OCM2.mapping_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id" + - " ) AS MAPPING_STATUS, " + - " (" + - " SELECT " + - " String_agg(" + - " OCM2.permission :: varchar, '||' order by OCM2.mapping_id :: varchar" + - " )" + - " FROM " + - " OB_CONSENT_MAPPING OCM2 " + - " JOIN OB_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + - " WHERE " + - " OCAR2.consent_id = OBC.consent_id" + - " ) AS PERMISSION" + - " FROM " + - selectClause + - "AS OBC " + - "LEFT JOIN OB_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + - joinType + "JOIN OB_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " - + userIdFilterClause + - "LEFT JOIN OB_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID WHERE " + - "(OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + - "AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) " + - "group by OBC.CONSENT_ID," + - "OBC.RECEIPT," + - "OBC.CLIENT_ID," + - "OBC.CONSENT_TYPE," + - "CONSENT_FREQUENCY," + - "VALIDITY_TIME," + - "RECURRING_INDICATOR," + - "OBC.CURRENT_STATUS," + - "OBC.CREATED_TIME," + - "OBC.UPDATED_TIME " + - "ORDER BY OBC.UPDATED_TIME DESC"); - - if (shouldLimit && shouldOffset) { - query.append(" LIMIT ? OFFSET ? "); - } else if (shouldLimit) { - query.append(" LIMIT ? "); - } - - return query.toString(); - } - - /** - * SQL query for delete consent mapping by auth id. - * @param executeOnRetentionTables flag to execute on retention tables - * @return SQL query for delete consent mapping by auth id - */ - public String getDeleteConsentMappingByAuthIdPreparedStatement(boolean executeOnRetentionTables) { - - // table prefix is to execute on consent retention data (purged data) tables. (if enabled) - String tablePrefix = ""; - if (executeOnRetentionTables) { - tablePrefix = ConsentMgtDAOConstants.RETENTION_TABLE_NAME_PREFIX; - } - return "DELETE FROM " + tablePrefix + "ob_consent_mapping where MAPPING_ID in (SELECT MAPPING_ID FROM " + - tablePrefix + "ob_consent_mapping OBCM INNER JOIN " + tablePrefix + "ob_consent_auth_resource OBAR " + - "ON OBCM.AUTH_ID = OBAR.AUTH_ID WHERE OBAR.CONSENT_ID = ?)"; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/utils/ConsentDAOUtils.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/utils/ConsentDAOUtils.java deleted file mode 100644 index 5974f4cb..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/dao/utils/ConsentDAOUtils.java +++ /dev/null @@ -1,276 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.utils; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Utils class for consent module. - */ -public class ConsentDAOUtils { - - private static final String SPACE = " "; - private static final String COMMA = ","; - private static final String QUOTE = "\'"; - private static final String PLACEHOLDER = "?"; - private static final String LEFT_PARENTHESIS = "("; - private static final String RIGHT_PARENTHESIS = ")"; - private static final Map DB_OPERATORS_MAP = new HashMap() { - { - put(ConsentMgtDAOConstants.IN, "IN"); - put(ConsentMgtDAOConstants.AND, "AND"); - put(ConsentMgtDAOConstants.OR, "OR"); - put(ConsentMgtDAOConstants.WHERE, "WHERE"); - put(ConsentMgtDAOConstants.PLACEHOLDER, "?,"); - put(ConsentMgtDAOConstants.PLAIN_PLACEHOLDER, "?"); - put(ConsentMgtDAOConstants.EQUALS, "="); - } - }; - - public static String constructConsentSearchPreparedStatement(Map applicableConditions) { - - StringBuilder placeHoldersBuilder = new StringBuilder(); - StringBuilder whereClauseBuilder = new StringBuilder(); - whereClauseBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); - // If all lists are empty or null, return the default term "where" - if (MapUtils.isEmpty(applicableConditions)) { - return ""; - } - for (Map.Entry entry : applicableConditions.entrySet()) { - // Oracle only allows 1000 values to be used in a SQL "IN" clause. Since more than 1000 consent IDs - // are used in some queries, "OR" clause is used - if (entry.getKey().contains("CONSENT_ID")) { - for (int i = 0; i < entry.getValue().size(); i++) { - whereClauseBuilder - .append(SPACE) - .append(entry.getKey()) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLAIN_PLACEHOLDER)) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.OR)); - } - // Delete last OR from the statement - whereClauseBuilder.replace(whereClauseBuilder.length() - 2, - whereClauseBuilder.length(), DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.AND)); - } else { - for (int i = 0; i < entry.getValue().size(); i++) { - placeHoldersBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLACEHOLDER)); - } - String placeHolders = StringUtils.removeEnd(placeHoldersBuilder.toString(), COMMA); - whereClauseBuilder - .append(SPACE) - .append(entry.getKey()) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.IN)) - .append(LEFT_PARENTHESIS) - .append(placeHolders) - .append(RIGHT_PARENTHESIS) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.AND)); - // Delete all content from old string builder except the starting left parenthesis - placeHoldersBuilder.delete(0, placeHoldersBuilder.length()); - } - } - int size = whereClauseBuilder.length(); - //removing the last AND in the statement - whereClauseBuilder.replace(size - 3, size, ""); - return whereClauseBuilder.toString(); - } - - public static String constructUserIdListFilterCondition(Map userIds) { - - StringBuilder placeHoldersBuilder = new StringBuilder(); - StringBuilder userIdFilterBuilder = new StringBuilder(); - - for (Map.Entry entry : userIds.entrySet()) { - for (int i = 0; i < entry.getValue().size(); i++) { - placeHoldersBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLACEHOLDER)); - } - String placeHolders = StringUtils.removeEnd(placeHoldersBuilder.toString(), COMMA); - userIdFilterBuilder - .append(SPACE) - .append(entry.getKey()) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.IN)) - .append(LEFT_PARENTHESIS) - .append(placeHolders) - .append(RIGHT_PARENTHESIS) - .append(SPACE); - // Delete all content from old string builder except the starting left parenthesis - placeHoldersBuilder.delete(0, placeHoldersBuilder.length()); - } - return userIdFilterBuilder.toString(); - } - - public static String constructAuthSearchPreparedStatement(Map applicableConditions) { - - StringBuilder whereClauseBuilder = new StringBuilder(); - - // If all lists are empty or null, return the default term "where" - if (MapUtils.isEmpty(applicableConditions)) { - return whereClauseBuilder.toString(); - } - - whereClauseBuilder.append(SPACE).append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); - - int count = 0; - for (Map.Entry entry : applicableConditions.entrySet()) { - - if (count > 0) { - whereClauseBuilder.append(SPACE).append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.AND)); - } - whereClauseBuilder - .append(SPACE) - .append(entry.getKey()) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) - .append(SPACE) - .append(PLACEHOLDER); - count++; - } - return whereClauseBuilder.toString(); - } - - /** - * Method to construct where clause for consent status audit search condition. - * @param consentIDs List of consent IDs - * @return Filter condition for consent status audit - */ - public static String constructConsentAuditRecordSearchPreparedStatement(ArrayList consentIDs) { - - StringBuilder whereClauseBuilder = new StringBuilder(); - if (!CollectionUtils.isEmpty(consentIDs)) { - whereClauseBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); - for (int count = 0; count < consentIDs.size(); count++) { - whereClauseBuilder - .append(SPACE) - .append(ConsentMgtDAOConstants.CONSENT_ID) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLAIN_PLACEHOLDER)) - .append(SPACE) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.OR)); - } - // Delete last OR from the statement - whereClauseBuilder.replace(whereClauseBuilder.length() - 2, - whereClauseBuilder.length(), StringUtils.SPACE); - } - return whereClauseBuilder.toString(); - } - - public static TreeMap determineOrderOfParamsToSet(String preparedStatement, Map applicableConditionsMap, Map columnsMap) { - - int indexOfConsentIDsList; - int indexOfClientIdsList; - int indexOfConsentTypesList; - int indexOfConsentStatusesList; - int indexOfUserIDsList; - - // Tree map naturally sorts values in ascending order according to the key - TreeMap sortedIndexesMap = new TreeMap<>(); - - /* Check whether the where condition clauses are in the prepared statement and get the index if exists to - determine the order */ - if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CONSENT_IDS))) { - indexOfConsentIDsList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.CONSENT_IDS)); - sortedIndexesMap.put(indexOfConsentIDsList, - applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CONSENT_IDS))); - } - if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CLIENT_IDS))) { - indexOfClientIdsList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.CLIENT_IDS)); - sortedIndexesMap.put(indexOfClientIdsList, - applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CLIENT_IDS))); - } - if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CONSENT_TYPES))) { - indexOfConsentTypesList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.CONSENT_TYPES)); - sortedIndexesMap.put(indexOfConsentTypesList, - applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CONSENT_TYPES))); - } - if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CONSENT_STATUSES))) { - indexOfConsentStatusesList = preparedStatement - .indexOf(columnsMap.get(ConsentMgtDAOConstants.CONSENT_STATUSES)); - sortedIndexesMap.put(indexOfConsentStatusesList, - applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CONSENT_STATUSES))); - } - if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.USER_IDS))) { - indexOfUserIDsList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.USER_IDS)); - sortedIndexesMap.put(indexOfUserIDsList, - applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.USER_IDS))); - } - return sortedIndexesMap; - } - - /** - * Method to construct excluded statuses search condition. - * - * @param statusesEligibleForExpiration List of statuses eligible for expiration - * @return Filter condition for excluded statuses - */ - public static String constructStatusesEligibleForExpirationCondition(List statusesEligibleForExpiration) { - - StringBuilder placeHoldersBuilder = new StringBuilder(); - StringBuilder statusesEligibleForExpirationFilterBuilder = new StringBuilder(); - - for (int i = 0; i < statusesEligibleForExpiration.size(); i++) { - placeHoldersBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLACEHOLDER)); - } - String placeHolders = StringUtils.removeEnd(placeHoldersBuilder.toString(), COMMA); - statusesEligibleForExpirationFilterBuilder - .append(SPACE) - .append(LEFT_PARENTHESIS) - .append(placeHolders) - .append(RIGHT_PARENTHESIS) - .append(SPACE); - // Delete all content from old string builder except the starting left parenthesis - placeHoldersBuilder.delete(0, placeHoldersBuilder.length()); - return statusesEligibleForExpirationFilterBuilder.toString(); - } - - public static String constructConsentHistoryPreparedStatement(int recordIdCount) { - - StringBuilder whereClauseBuilder = new StringBuilder(); - whereClauseBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); - - for (int count = 0; count < recordIdCount; count++) { - whereClauseBuilder.append(SPACE) - .append(LEFT_PARENTHESIS) - .append(ConsentMgtDAOConstants.RECORD_ID) - .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) - .append(PLACEHOLDER) - .append(RIGHT_PARENTHESIS); - if (count < recordIdCount - 1) { - whereClauseBuilder.append(SPACE).append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.OR)); - } - } - return whereClauseBuilder.toString(); - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index a16f7b50..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/OBConsentMgtDAOTests.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/OBConsentMgtDAOTests.java deleted file mode 100644 index d6cdfd1f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/impl/OBConsentMgtDAOTests.java +++ /dev/null @@ -1,2546 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.impl; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.ConsentCoreDAO; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataDeletionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataInsertionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataUpdationException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.queries.ConsentMgtCommonDBQueries; -import com.wso2.openbanking.accelerator.consent.mgt.dao.util.ConsentMgtDAOTestData; -import com.wso2.openbanking.accelerator.consent.mgt.dao.util.DAOUtils; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Open banking consent management DAO tests. - */ -public class OBConsentMgtDAOTests { - - private static final String DB_NAME = "CONSENT_DB"; - - private ConsentCoreDAO consentCoreDAO; - private Connection mockedConnection; - private PreparedStatement mockedPreparedStatement; - private ResultSet mockedResultSet; - - @BeforeClass - public void initTest() throws Exception { - - DAOUtils.initializeDataSource(DB_NAME, DAOUtils.getFilePath("dbScripts/h2.sql")); - consentCoreDAO = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); - mockedConnection = Mockito.mock(Connection.class); - mockedPreparedStatement = Mockito.mock(PreparedStatement.class); - mockedResultSet = Mockito.mock(ResultSet.class); - } - - @DataProvider(name = "storeConsentDataProvider") - public Object[][] storeConsentResourceData() { - - /* - * consentID - * clientID - * receipt - * consentType - * consentFrequency - * validityPeriod - * recurringIndicator - * currentStatus - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_RESOURCE_DATA_HOLDER; - } - - @Test(dataProvider = "storeConsentDataProvider") - public void testStoreConsentResource(String clientID, String receipt, String consentType, - int consentFrequency, long validityPeriod, boolean recurringIndicator, - String currentStatus) throws Exception { - - ConsentResource storedConsentResource; - ConsentResource consentResource = new ConsentResource(); - consentResource.setReceipt(receipt); - consentResource.setClientID(clientID); - consentResource.setConsentType(consentType); - consentResource.setCurrentStatus(currentStatus); - consentResource.setConsentFrequency(consentFrequency); - consentResource.setValidityPeriod(validityPeriod); - consentResource.setConsentID(UUID.randomUUID().toString()); - consentResource.setRecurringIndicator(true); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - } - Assert.assertNotNull(storedConsentResource); - Assert.assertNotNull(storedConsentResource.getConsentID()); - Assert.assertNotNull(storedConsentResource.getClientID()); - Assert.assertNotNull(storedConsentResource.getConsentType()); - Assert.assertEquals(consentFrequency, storedConsentResource.getConsentFrequency()); - Assert.assertNotNull(storedConsentResource.getValidityPeriod()); - Assert.assertTrue(storedConsentResource.isRecurringIndicator()); - Assert.assertNotNull(storedConsentResource.getCreatedTime()); - Assert.assertNotNull(storedConsentResource.getCurrentStatus()); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentResourceInsertionError() throws Exception { - - Mockito.doReturn(Mockito.mock(PreparedStatement.class)).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(Mockito.mock(PreparedStatement.class)).executeUpdate(); - - consentCoreDAO.storeConsentResource(mockedConnection, ConsentMgtDAOTestData.getSampleTestConsentResource()); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentResourceSQLError() throws Exception { - - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentResource(mockedConnection, ConsentMgtDAOTestData.getSampleTestConsentResource()); - } - - @DataProvider(name = "storeAuthorizationDataProvider") - public Object[][] storeAuthorizationResourceData() { - - /* - * authorizationID - * consentID - * authorizationType - * userID - * authorizationStatus - */ - return ConsentMgtDAOTestData.DataProviders.AUTHORIZATION_RESOURCE_DATA_HOLDER; - } - - @Test (dataProvider = "storeAuthorizationDataProvider") - public void testStoreAuthorizationResource(String authorizationType, - String userID, String authorizationStatus) throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(storedConsentResource.getConsentID()); - authorizationResource.setAuthorizationType(authorizationType); - authorizationResource.setUserID(userID); - authorizationResource.setAuthorizationStatus(authorizationStatus); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - authorizationResource); - } - Assert.assertNotNull(storedAuthorizationResource.getConsentID()); - Assert.assertNotNull(storedAuthorizationResource.getAuthorizationType()); - Assert.assertNotNull(storedAuthorizationResource.getUserID()); - Assert.assertNotNull(storedAuthorizationResource.getAuthorizationStatus()); - Assert.assertNotNull(storedAuthorizationResource.getUpdatedTime()); - Assert.assertNotNull(storedAuthorizationResource.getAuthorizationID()); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreAuthorizationResourceInsertionError() throws Exception { - - ConsentResource storedConsentResource = ConsentMgtDAOTestData.getSampleStoredTestConsentResource(); - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - - consentCoreDAO.storeAuthorizationResource(mockedConnection, ConsentMgtDAOTestData. - getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreAuthorizationResourceSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - - consentCoreDAO.storeAuthorizationResource(mockedConnection, ConsentMgtDAOTestData. - getSampleTestAuthorizationResource(Mockito.anyString())); - } - - @DataProvider(name = "storeConsentMappingDataProvider") - public Object[][] storeConsentMappingResourceData() { - - /* - * accountID - * permission - * mappingStatus - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_MAPPING_RESOURCE_DATA_HOLDER; - } - - @Test (dataProvider = "storeConsentMappingDataProvider") - public void testStoreConsentMappingResource(String accountID, String permission, - String mappingStatus) throws Exception { - - ConsentResource consentResource; - AuthorizationResource authorizationResource; - ConsentMappingResource consentMappingResource; - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource storedConsentMappingResource; - - consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - authorizationResource); - - consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(storedAuthorizationResource.getAuthorizationID()); - consentMappingResource.setAccountID(accountID); - consentMappingResource.setPermission(permission); - consentMappingResource.setMappingStatus(mappingStatus); - - storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, - consentMappingResource); - } - Assert.assertNotNull(storedConsentMappingResource.getMappingID()); - Assert.assertNotNull(storedConsentMappingResource.getAuthorizationID()); - Assert.assertNotNull(storedConsentMappingResource.getAccountID()); - Assert.assertNotNull(storedConsentMappingResource.getPermission()); - Assert.assertNotNull(storedConsentMappingResource.getMappingStatus()); - } - - @Test(dataProvider = "storeConsentMappingDataProvider") - public void testStoreConsentMappingResourceWithID(String accountID, String permission, - String mappingStatus) throws Exception { - - ConsentResource consentResource; - AuthorizationResource authorizationResource; - ConsentMappingResource consentMappingResource; - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource storedConsentMappingResource; - - consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - authorizationResource.setAuthorizationID("db0b943d-38e2-47e4-bb78-8a242d279b5a"); - authorizationResource.setUpdatedTime(1669917425); - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - authorizationResource); - - consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(storedAuthorizationResource.getAuthorizationID()); - consentMappingResource.setAccountID(accountID); - consentMappingResource.setMappingID("aa4c943d-38e2-47e5-bb78-8a242d279b5a"); - consentMappingResource.setPermission(permission); - consentMappingResource.setMappingStatus(mappingStatus); - - storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, - consentMappingResource); - } - Assert.assertTrue(storedConsentMappingResource.getMappingID().equals("aa4c943d-38e2-47e5-bb78-8a242d279b5a")); - Assert.assertTrue( - storedConsentMappingResource.getAuthorizationID().equals("db0b943d-38e2-47e4-bb78-8a242d279b5a")); - Assert.assertNotNull(storedConsentMappingResource.getAccountID()); - Assert.assertNotNull(storedConsentMappingResource.getPermission()); - Assert.assertNotNull(storedConsentMappingResource.getMappingStatus()); - } - - @Test(expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentMappingResourceInsertionError() throws Exception { - - ConsentMappingResource sampleConsentMappingResource = - ConsentMgtDAOTestData.getSampleTestConsentMappingResource(ConsentMgtDAOTestData - .getSampleStoredTestAuthorizationResource().getAuthorizationID()); - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - - consentCoreDAO.storeConsentMappingResource(mockedConnection, sampleConsentMappingResource); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentMappingResourceSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentMappingResource(mockedConnection, new ConsentMappingResource()); - } - - @Test(expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreNullConsentMappingResource() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentMappingResource(mockedConnection, null); - } - - @DataProvider(name = "storeConsentStatusAuditRecordDataProvider") - public Object[][] storeConsentStatusAuditRecordData() { - - /* - * currentStatus - * reason - * actionBy - * previousStatus - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_STATUS_AUDIT_RECORD_DATA_HOLDER; - } - - @Test (dataProvider = "storeConsentStatusAuditRecordDataProvider") - public void testStoreConsentStatusAuditRecord(String currentStatus, String reason, - String actionBy, String previousStatus) throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(storedConsentResource.getConsentID()); - consentStatusAuditRecord.setCurrentStatus(currentStatus); - consentStatusAuditRecord.setReason(reason); - consentStatusAuditRecord.setActionBy(actionBy); - consentStatusAuditRecord.setPreviousStatus(previousStatus); - - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - } - Assert.assertNotNull(storedConsentStatusAuditRecord.getConsentID()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getCurrentStatus()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getReason()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getActionBy()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getPreviousStatus()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getActionTime()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getStatusAuditID()); - } - - @Test(dataProvider = "storeConsentStatusAuditRecordDataProvider") - public void testStoreConsentStatusAuditRecordWithConsentId(String currentStatus, String reason, - String actionBy, String previousStatus) - throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - consentResource.setConsentID("234ba17f-c3ac-4493-9049-d71f99c36dc2"); - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(storedConsentResource.getConsentID()); - consentStatusAuditRecord.setCurrentStatus(currentStatus); - consentStatusAuditRecord.setReason(reason); - consentStatusAuditRecord.setActionBy(actionBy); - consentStatusAuditRecord.setPreviousStatus(previousStatus); - consentStatusAuditRecord.setActionTime(1669917425); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - } - Assert.assertTrue( - storedConsentStatusAuditRecord.getConsentID().equals("234ba17f-c3ac-4493-9049-d71f99c36dc2")); - Assert.assertNotNull(storedConsentStatusAuditRecord.getCurrentStatus()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getReason()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getActionBy()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getPreviousStatus()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getActionTime()); - Assert.assertNotNull(storedConsentStatusAuditRecord.getStatusAuditID()); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentStatusAuditRecordInsertionError() throws Exception { - - ConsentStatusAuditRecord sampleConsentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - consentCoreDAO.storeConsentStatusAuditRecord(mockedConnection, sampleConsentStatusAuditRecord); - } - - @Test(expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreNullConsentStatusAuditRecord() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - consentCoreDAO.storeConsentStatusAuditRecord(mockedConnection, null); - } - - @Test(expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentStatusAuditRecordSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentStatusAuditRecord(mockedConnection, new ConsentStatusAuditRecord()); - } - - @DataProvider(name = "storeConsentAttributesDataProvider") - public Object[][] storeConsentAttributesData() { - - /* - * consentAttributesMap - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_ATTRIBUTES_DATA_HOLDER; - } - - @Test (dataProvider = "storeConsentAttributesDataProvider") - public void testStoreConsentAttributes(Map consentAttributes) throws Exception { - - ConsentResource storedConsentResource; - ConsentAttributes consentAttributesResource; - boolean isConsentAttributesStored; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentAttributesResource = new ConsentAttributes(); - consentAttributesResource.setConsentID(storedConsentResource.getConsentID()); - consentAttributesResource.setConsentAttributes(consentAttributes); - - isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - } - Assert.assertTrue(isConsentAttributesStored); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentAttributesSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentAttributes(mockedConnection, ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(ConsentMgtDAOTestData.getSampleStoredTestConsentResource() - .getConsentID())); - } - - @DataProvider(name = "storeConsentFileDataProvider") - public Object[][] storeConsentFileData() { - - /* - * consentFile - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_FILE_DATA_HOLDER; - } - - @Test (dataProvider = "storeConsentFileDataProvider") - public void testStoreConsentFile(String fileContent) throws Exception { - - ConsentResource storedConsentResource; - ConsentFile consentFileResource; - boolean isConsentFileStored; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentFileResource = new ConsentFile(); - consentFileResource.setConsentID(storedConsentResource.getConsentID()); - consentFileResource.setConsentFile(fileContent); - - isConsentFileStored = consentCoreDAO.storeConsentFile(connection, consentFileResource); - } - Assert.assertTrue(isConsentFileStored); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentFileInsertionError() throws Exception { - - ConsentFile sampleConsentFileResource = - ConsentMgtDAOTestData.getSampleConsentFileObject(ConsentMgtDAOTestData.SAMPLE_CONSENT_FILE); - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - consentCoreDAO.storeConsentFile(mockedConnection, sampleConsentFileResource); - } - - @Test (expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentFileSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentFile(mockedConnection, Mockito.anyObject()); - } - - @DataProvider(name = "updateConsentStatusDataProvider") - public Object[][] updateConsentStatusData() { - - /* - * newConsentStatus - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_STATUS_UPDATE_DATA_HOLDER; - } - - @Test (dataProvider = "updateConsentStatusDataProvider") - public void testUpdateConsentStatus(String newConsentStatus) throws Exception { - - ConsentResource storedConsentResource; - ConsentResource updatedConsentResource; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - updatedConsentResource = consentCoreDAO.updateConsentStatus(connection, - storedConsentResource.getConsentID(), newConsentStatus); - } - Assert.assertNotNull(updatedConsentResource.getConsentID()); - Assert.assertNotNull(updatedConsentResource.getCurrentStatus()); - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentStatusSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.updateConsentStatus(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (dataProvider = "updateConsentStatusDataProvider", expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentStatusWithUnmatchedConsentID(String newConsentStatus) throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.updateConsentStatus(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - newConsentStatus); - } - } - - @DataProvider(name = "updateConsentMappingStatusDataProvider") - public Object[][] updateConsentMappingStatusData() { - - /* - * newMappingStatus - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_MAPPING_STATUS_UPDATE_DATA_HOLDER; - } - - @Test (dataProvider = "updateConsentMappingStatusDataProvider") - public void testUpdateConsentMappingStatus(String newMappingStatus) throws Exception { - - boolean isConsentMappingStatusUpdated; - ConsentResource storedConsentResource; - AuthorizationResource authorizationResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource consentMappingResource; - ConsentMappingResource storedConsentMappingResource; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); - - consentMappingResource = - ConsentMgtDAOTestData - .getSampleTestConsentMappingResource(storedAuthorizationResource.getAuthorizationID()); - - storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, - consentMappingResource); - - ArrayList mappingIDs = new ArrayList() { - { - add(storedConsentMappingResource.getMappingID()); - } - }; - - isConsentMappingStatusUpdated = consentCoreDAO.updateConsentMappingStatus(connection, mappingIDs, - newMappingStatus); - } - Assert.assertTrue(isConsentMappingStatusUpdated); - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentMappingStatusSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.updateConsentMappingStatus(mockedConnection, ConsentMgtDAOTestData.UNMATCHED_MAPPING_IDS, - ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); - } - - @DataProvider(name = "updateAuthorizationStatusDataProvider") - public Object[][] updateAuthorizationStatusData() { - - /* - * newAuthorizationStatus - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_AUTHORIZATION_STATUS_UPDATE_DATA_HOLDER; - } - - @Test (dataProvider = "updateAuthorizationStatusDataProvider") - public void testUpdateAuthorizationStatus(String newAuthorizationStatus) throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource authorizationResource; - AuthorizationResource storedAuthorizationResource; - AuthorizationResource updatedAuthorizationResource; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); - - updatedAuthorizationResource = consentCoreDAO.updateAuthorizationStatus(connection, - storedAuthorizationResource.getAuthorizationID(), newAuthorizationStatus); - } - Assert.assertNotNull(updatedAuthorizationResource.getUpdatedTime()); - Assert.assertNotNull(updatedAuthorizationResource.getAuthorizationID()); - Assert.assertNotNull(updatedAuthorizationResource.getAuthorizationStatus()); - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateAuthorizationStatusSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.updateAuthorizationStatus(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, - ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (dataProvider = "updateAuthorizationStatusDataProvider", - expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateAuthorizationStatusWithUnmatchedAuthID(String newAuthorizationStatus) throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.updateAuthorizationStatus(connection, - ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, newAuthorizationStatus); - } - } - - @DataProvider(name = "updateAuthorizationUserDataProvider") - public Object[][] updateAuthorizationUsersData() { - - /* - * newAuthorizationUser - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_AUTHORIZATION_USER_UPDATE_DATA_HOLDER; - } - - @Test (dataProvider = "updateAuthorizationUserDataProvider") - public void testUpdateAuthorizationUser(String newUserID) throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource authorizationResource; - AuthorizationResource storedAuthorizationResource; - AuthorizationResource updatedAuthorizationResource; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); - - updatedAuthorizationResource = consentCoreDAO.updateAuthorizationUser(connection, - storedAuthorizationResource.getAuthorizationID(), newUserID); - } - Assert.assertNotNull(updatedAuthorizationResource.getUserID()); - Assert.assertNotNull(updatedAuthorizationResource.getUpdatedTime()); - Assert.assertNotNull(updatedAuthorizationResource.getAuthorizationID()); - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateAuthorizationUserSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.updateAuthorizationUser(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, - ConsentMgtDAOTestData.SAMPLE_USER_ID); - } - - @Test (dataProvider = "updateAuthorizationUserDataProvider", - expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateAuthorizationUserWithUnmatchedAuthID(String newUserID) throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.updateAuthorizationUser(connection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, - newUserID); - } - } - - @Test - public void testRetrieveConsentResource() throws Exception { - - ConsentResource storedConsentResource; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, - storedConsentResource.getConsentID()); - } - - Assert.assertNotNull(retrievedConsentResource); - Assert.assertEquals(retrievedConsentResource.getConsentID(), storedConsentResource.getConsentID()); - Assert.assertNotNull(retrievedConsentResource.getConsentID()); - Assert.assertNotNull(retrievedConsentResource.getClientID()); - Assert.assertNotNull(retrievedConsentResource.getConsentType()); - Assert.assertEquals(consentResource.getConsentFrequency(), storedConsentResource.getConsentFrequency()); - Assert.assertNotNull(retrievedConsentResource.getValidityPeriod()); - Assert.assertTrue(retrievedConsentResource.isRecurringIndicator()); - Assert.assertNotNull(retrievedConsentResource.getCreatedTime()); - Assert.assertNotNull(retrievedConsentResource.getCurrentStatus()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentResourceResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentResource(mockedConnection, Mockito.anyString()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentResourceSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentResource(mockedConnection, Mockito.anyObject()); - } - - @Test(expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentResourceWithUnmatchedConsentID() throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.getConsentResource(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); - } - } - - @Test - public void testRetrieveDetailedConsentResource() throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource storedConsentMappingResource; - DetailedConsentResource retrievedDetailedConsentResource; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storedConsentResource = consentCoreDAO.storeConsentResource(connection, - ConsentMgtDAOTestData.getSampleTestConsentResource()); - consentCoreDAO.storeConsentAttributes(connection, - ConsentMgtDAOTestData.getSampleTestConsentAttributesObject(storedConsentResource.getConsentID())); - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); - storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, - ConsentMgtDAOTestData.getSampleTestConsentMappingResource(storedAuthorizationResource - .getAuthorizationID())); - retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, - storedConsentResource.getConsentID(), false); - } - - Assert.assertNotNull(retrievedDetailedConsentResource); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); - Assert.assertEquals(retrievedDetailedConsentResource.getClientID(), storedConsentResource.getClientID()); - Assert.assertEquals(retrievedDetailedConsentResource.getReceipt(), storedConsentResource.getReceipt()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentType(), storedConsentResource.getConsentType()); - Assert.assertEquals(retrievedDetailedConsentResource.getCurrentStatus(), - storedConsentResource.getCurrentStatus()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentFrequency(), - storedConsentResource.getConsentFrequency()); - Assert.assertEquals(retrievedDetailedConsentResource.getValidityPeriod(), - storedConsentResource.getValidityPeriod()); - Assert.assertEquals(retrievedDetailedConsentResource.isRecurringIndicator(), - storedConsentResource.isRecurringIndicator()); - Assert.assertNotNull(retrievedDetailedConsentResource.getConsentAttributes()); - Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(0).getAuthorizationID(), - storedAuthorizationResource.getAuthorizationID()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentMappingResources().get(0).getMappingID(), - storedConsentMappingResource.getMappingID()); - } - - @Test - public void testRetrieveDetailedConsentResourceWithoutAttributes() throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource storedConsentMappingResource; - DetailedConsentResource retrievedDetailedConsentResource; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storedConsentResource = consentCoreDAO.storeConsentResource(connection, - ConsentMgtDAOTestData.getSampleTestConsentResource()); - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); - storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, - ConsentMgtDAOTestData.getSampleTestConsentMappingResource(storedAuthorizationResource - .getAuthorizationID())); - retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, - storedConsentResource.getConsentID(), false); - } - - Assert.assertNotNull(retrievedDetailedConsentResource); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); - Assert.assertEquals(retrievedDetailedConsentResource.getClientID(), storedConsentResource.getClientID()); - Assert.assertEquals(retrievedDetailedConsentResource.getReceipt(), storedConsentResource.getReceipt()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentType(), storedConsentResource.getConsentType()); - Assert.assertEquals(retrievedDetailedConsentResource.getCurrentStatus(), - storedConsentResource.getCurrentStatus()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentFrequency(), - storedConsentResource.getConsentFrequency()); - Assert.assertEquals(retrievedDetailedConsentResource.getValidityPeriod(), - storedConsentResource.getValidityPeriod()); - Assert.assertEquals(retrievedDetailedConsentResource.isRecurringIndicator(), - storedConsentResource.isRecurringIndicator()); - Assert.assertNotNull(retrievedDetailedConsentResource.getConsentAttributes()); - Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(0).getAuthorizationID(), - storedAuthorizationResource.getAuthorizationID()); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentMappingResources().get(0).getMappingID(), - storedConsentMappingResource.getMappingID()); - } - - @Test - public void testRetrieveDetailedConsentResourceWithMultipleConsentAttributeKeys() throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResourceOne; - AuthorizationResource storedAuthorizationResourceTwo; - DetailedConsentResource retrievedDetailedConsentResource; - String accountIdOne = "123456"; - String accountIdTwo = "789123"; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storedConsentResource = consentCoreDAO.storeConsentResource(connection, - ConsentMgtDAOTestData.getSampleTestConsentResource()); - consentCoreDAO.storeConsentAttributes(connection, - ConsentMgtDAOTestData.getSampleTestConsentAttributesObject(storedConsentResource.getConsentID())); - // create two auth resources for same consent id - storedAuthorizationResourceOne = consentCoreDAO.storeAuthorizationResource(connection, - ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); - storedAuthorizationResourceTwo = consentCoreDAO.storeAuthorizationResource(connection, - ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); - // create a total of three mapping resources for created auth resources - // mapping resources for first auth resource with two account ids - consentCoreDAO.storeConsentMappingResource(connection, - ConsentMgtDAOTestData - .getSampleTestConsentMappingResourceWithAccountId(storedAuthorizationResourceOne - .getAuthorizationID(), accountIdOne)); - consentCoreDAO.storeConsentMappingResource(connection, - ConsentMgtDAOTestData - .getSampleTestConsentMappingResourceWithAccountId(storedAuthorizationResourceOne - .getAuthorizationID(), accountIdTwo)); - // mapping resource for second auth resource with a single account id - consentCoreDAO.storeConsentMappingResource(connection, - ConsentMgtDAOTestData - .getSampleTestConsentMappingResourceWithAccountId(storedAuthorizationResourceTwo - .getAuthorizationID(), accountIdOne)); - retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, - storedConsentResource.getConsentID(), false); - } - - Assert.assertNotNull(retrievedDetailedConsentResource); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); - Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(0).getAuthorizationID(), - storedAuthorizationResourceOne.getAuthorizationID()); - Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(1).getAuthorizationID(), - storedAuthorizationResourceTwo.getAuthorizationID()); - /* according to the created consent resource, retrieved consent resource should contain two auth resources and - three mapping resources - */ - Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().size(), 2); - Assert.assertEquals(retrievedDetailedConsentResource.getConsentMappingResources().size(), 3); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveDetailedConsentResourceError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getDetailedConsentResource(mockedConnection, Mockito.anyString(), false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveDetailedConsentResourceRetrieveError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).next(); - consentCoreDAO.getDetailedConsentResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveDetailedConsentResourceResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getDetailedConsentResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, false); - } - - @Test - public void testRetrieveConsentWithAttributesResource() throws Exception { - - ConsentAttributes consentAttributesResource; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(consentResource.getConsentID()); - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - retrievedConsentResource = consentCoreDAO.getConsentResourceWithAttributes(connection, - consentResource.getConsentID()); - } - Assert.assertNotNull(retrievedConsentResource); - Assert.assertEquals(retrievedConsentResource.getConsentID(), consentResource.getConsentID()); - Assert.assertNotNull(retrievedConsentResource.getConsentID()); - Assert.assertNotNull(retrievedConsentResource.getClientID()); - Assert.assertNotNull(retrievedConsentResource.getConsentType()); - Assert.assertEquals(consentResource.getConsentFrequency(), retrievedConsentResource.getConsentFrequency()); - Assert.assertNotNull(retrievedConsentResource.getValidityPeriod()); - Assert.assertTrue(retrievedConsentResource.isRecurringIndicator()); - Assert.assertNotNull(retrievedConsentResource.getCreatedTime()); - Assert.assertNotNull(retrievedConsentResource.getCurrentStatus()); - Assert.assertNotNull(retrievedConsentResource.getConsentAttributes()); - - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentWithAttributesResourceResultRetrieveError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).next(); - consentCoreDAO.getConsentResourceWithAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentWithAttributesResourceResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentResourceWithAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentWithAttributesResourceSQLError() throws Exception { - - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString(), - Mockito.anyInt(), Mockito.anyInt()); - consentCoreDAO.getConsentResourceWithAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); - } - - @Test (dataProvider = "storeConsentFileDataProvider") - public void testRetrieveConsentFileResource(String consentFile) throws Exception { - - ConsentFile consentFileResource; - ConsentFile retrievedConsentFileResource; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentFileResource = new ConsentFile(); - consentFileResource.setConsentID(retrievedConsentResource.getConsentID()); - consentFileResource.setConsentFile(consentFile); - - consentCoreDAO.storeConsentFile(connection, consentFileResource); - - retrievedConsentFileResource = consentCoreDAO.getConsentFile(connection, - consentFileResource.getConsentID(), false); - } - Assert.assertNotNull(retrievedConsentFileResource.getConsentID()); - Assert.assertNotNull(retrievedConsentFileResource.getConsentFile()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentFileResourceNoRecordsFoundError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).next(); - consentCoreDAO.getConsentFile(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentFileResourceSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentFile(mockedConnection, Mockito.anyObject(), false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentFileResourceRetrieveError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentFile(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, false); - } - - @Test(expectedExceptions = OBConsentDataRetrievalException.class, dataProvider = "storeConsentFileDataProvider") - public void testRetrieveConsentFileResourceWithUnmatchedConsentID(String consentFile) throws Exception { - - ConsentFile consentFileResource; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentFileResource = new ConsentFile(); - consentFileResource.setConsentID(retrievedConsentResource.getConsentID()); - consentFileResource.setConsentFile(consentFile); - - consentCoreDAO.storeConsentFile(connection, consentFileResource); - consentCoreDAO.getConsentFile(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, false); - } - } - - @DataProvider(name = "getConsentAttributesDataProvider") - public Object[][] getConsentAttributesData() { - - /* - * consentAttributeKeys - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_ATTRIBUTES_GET_DATA_HOLDER; - } - - @Test (dataProvider = "getConsentAttributesDataProvider") - public void testRetrieveConsentAttributes(ArrayList consentAttributeKeys) throws Exception { - - ConsentAttributes consentAttributesResource; - ConsentAttributes retrievedConsentAttributesResource; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - retrievedConsentAttributesResource = consentCoreDAO.getConsentAttributes(connection, - retrievedConsentResource.getConsentID(), consentAttributeKeys); - } - Assert.assertNotNull(retrievedConsentAttributesResource.getConsentID()); - Assert.assertNotNull(retrievedConsentAttributesResource.getConsentAttributes()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesRetrieveError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); - consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyString()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyString()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyObject()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesResultSetErrorOverloadedMethod() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyString(), - ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesSQLErrorOverloadedMethod() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyObject()); - } - - @Test - public void testRetrieveConsentAttributesWithNoKeys() throws Exception { - - ConsentAttributes consentAttributesResource; - ConsentAttributes retrievedConsentAttributesResource; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - retrievedConsentAttributesResource = consentCoreDAO.getConsentAttributes(connection, - retrievedConsentResource.getConsentID()); - } - Assert.assertNotNull(retrievedConsentAttributesResource.getConsentID()); - Assert.assertNotNull(retrievedConsentAttributesResource.getConsentAttributes()); - } - - @Test (dataProvider = "getConsentAttributesDataProvider", - expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesWithUnmatchedConsentID(ArrayList consentAttributeKeys) - throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.getConsentAttributes(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - consentAttributeKeys); - } - } - - @Test - public void testRetrieveConsentAttributesByName() throws Exception { - - ConsentAttributes consentAttributesResource; - Map retrievedValuesMap; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - retrievedValuesMap = consentCoreDAO.getConsentAttributesByName(connection, - "x-request-id"); - - } - Assert.assertTrue(retrievedValuesMap.containsKey(consentAttributesResource.getConsentID())); - Assert.assertTrue(retrievedValuesMap.containsValue(consentAttributesResource.getConsentAttributes().get("x" + - "-request-id"))); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesByNameSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentAttributesByName(mockedConnection, Mockito.anyObject()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAttributesByNameResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentAttributesByName(mockedConnection, Mockito.anyString()); - } - - @Test - public void testRetrieveAuthorizationResource() throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource authorizationResource; - AuthorizationResource storedAuthorizationResource; - AuthorizationResource retrievedAuthorizationResource; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); - - retrievedAuthorizationResource = consentCoreDAO.getAuthorizationResource(connection, - storedAuthorizationResource.getAuthorizationID()); - } - Assert.assertNotNull(retrievedAuthorizationResource.getUpdatedTime()); - Assert.assertNotNull(retrievedAuthorizationResource.getAuthorizationID()); - Assert.assertNotNull(retrievedAuthorizationResource.getAuthorizationStatus()); - Assert.assertNotNull(retrievedAuthorizationResource.getUserID()); - Assert.assertNotNull(retrievedAuthorizationResource.getAuthorizationType()); - Assert.assertEquals(retrievedAuthorizationResource.getConsentID(), storedAuthorizationResource.getConsentID()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveAuthorizationResourceResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getAuthorizationResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveAuthorizationResourceSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getAuthorizationResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveAuthorizationResourceWithUnmatchedAuthID() throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.getAuthorizationResource(connection, - ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - } - } - - @Test - public void testRetrieveConsentStatusAuditRecordsWithConsentID() throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord consentStatusAuditRecord; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - ArrayList retrievedConsentStatusAuditRecords; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), - storedConsentResource.getCurrentStatus()); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - - connection.commit(); - - retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, - storedConsentStatusAuditRecord.getConsentID(), null, - null, null, - null, null , false); - } - Assert.assertNotNull(retrievedConsentStatusAuditRecords); - for (ConsentStatusAuditRecord record: - retrievedConsentStatusAuditRecords) { - Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); - } - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentStatusAuditRecordsResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentStatusAuditRecords(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS, ConsentMgtDAOTestData.SAMPLE_ACTION_BY, - ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, ConsentMgtDAOTestData.SAMPLE_AUDIT_ID, false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentStatusAuditRecordsSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentStatusAuditRecords(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS, ConsentMgtDAOTestData.SAMPLE_ACTION_BY, - ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, ConsentMgtDAOTestData.SAMPLE_AUDIT_ID, false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentStatusAuditRecordByConsentIDWithUnmatchedConsentID() throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.getConsentStatusAuditRecords(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - null, null, null, null, null, false); - } - } - - @Test - public void testRetrieveConsentStatusAuditRecordsByConsentIDAndStatus() throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord consentStatusAuditRecord; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - ArrayList retrievedConsentStatusAuditRecords; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), - storedConsentResource.getCurrentStatus()); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - - retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, - storedConsentStatusAuditRecord.getConsentID(), storedConsentStatusAuditRecord.getCurrentStatus(), - null, null, null, null, false); - } - Assert.assertNotNull(retrievedConsentStatusAuditRecords); - for (ConsentStatusAuditRecord record: - retrievedConsentStatusAuditRecords) { - Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); - Assert.assertEquals(storedConsentStatusAuditRecord.getCurrentStatus(), record.getCurrentStatus()); - } - } - - @Test - public void testRetrieveConsentStatusAuditRecordsByConsentIDStatusAndActionBy() throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord consentStatusAuditRecord; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - ArrayList retrievedConsentStatusAuditRecords; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), - storedConsentResource.getCurrentStatus()); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - - retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, - storedConsentStatusAuditRecord.getConsentID(), storedConsentStatusAuditRecord.getCurrentStatus(), - storedConsentStatusAuditRecord.getActionBy(), null, - null, null, false); - } - Assert.assertNotNull(retrievedConsentStatusAuditRecords); - for (ConsentStatusAuditRecord record: - retrievedConsentStatusAuditRecords) { - Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); - Assert.assertEquals(storedConsentStatusAuditRecord.getCurrentStatus(), record.getCurrentStatus()); - Assert.assertEquals(storedConsentStatusAuditRecord.getActionBy(), record.getActionBy()); - } - } - - @Test - public void testRetrieveConsentAuditRecordByAuditRecordID() throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord consentStatusAuditRecord; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - ArrayList retrievedConsentStatusAuditRecords; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), - storedConsentResource.getCurrentStatus()); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - - retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, - null, null, null, null, null, - storedConsentStatusAuditRecord.getStatusAuditID(), false); - } - Assert.assertNotNull(retrievedConsentStatusAuditRecords); - for (ConsentStatusAuditRecord record: - retrievedConsentStatusAuditRecords) { - Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); - Assert.assertEquals(storedConsentStatusAuditRecord.getStatusAuditID(), record.getStatusAuditID()); - } - } - - @Test - public void testRetrieveConsentAuditRecordForGivenTime() throws Exception { - - long fromTime; - long toTime; - ConsentResource storedConsentResource; - ConsentStatusAuditRecord consentStatusAuditRecord; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - ArrayList retrievedConsentStatusAuditRecords; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), - storedConsentResource.getCurrentStatus()); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - - fromTime = Long.sum(storedConsentStatusAuditRecord.getActionTime(), -60); - toTime = Long.sum(storedConsentStatusAuditRecord.getActionTime(), 60); - - retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, - storedConsentStatusAuditRecord.getConsentID(), null, - null, fromTime, toTime, null, false); - } - Assert.assertNotNull(retrievedConsentStatusAuditRecords); - for (ConsentStatusAuditRecord record: - retrievedConsentStatusAuditRecords) { - Assert.assertEquals(storedConsentResource.getConsentID(), record.getConsentID()); - Assert.assertTrue((record.getActionTime() >= fromTime) && (record.getActionTime() <= toTime)); - } - } - - @Test - public void testRetrieveConsentMappingResource() throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource authorizationResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource consentMappingResource; - ArrayList retrievedConsentMappingResources; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - authorizationResource); - - consentMappingResource = - ConsentMgtDAOTestData - .getSampleTestConsentMappingResource(storedAuthorizationResource.getAuthorizationID()); - - consentCoreDAO.storeConsentMappingResource(connection, - consentMappingResource); - - retrievedConsentMappingResources = consentCoreDAO.getConsentMappingResources(connection, - storedAuthorizationResource.getAuthorizationID()); - } - Assert.assertNotNull(retrievedConsentMappingResources); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentMappingResourceResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentMappingResources(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentMappingResourceSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentMappingResources(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentMappingResourceRetrieveErrorOverloadedMethod() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); - consentCoreDAO.getConsentMappingResources(mockedConnection, Mockito.anyString(), - ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentMappingResourceResultSetErrorOverloadedMethod() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentMappingResources(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, - ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentMappingResourceSQLErrorOverloadedMethod() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentMappingResources(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, - ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentMappingResourceWithUnmatchedAuthID() throws Exception { - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentCoreDAO.getConsentMappingResources(connection, - ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - } - } - - @Test - public void testRetrieveConsentMappingResourceWithMappingStatus() throws Exception { - - ConsentResource storedConsentResource; - AuthorizationResource authorizationResource; - AuthorizationResource storedAuthorizationResource; - ConsentMappingResource storedConsentMappingResource; - ConsentMappingResource consentMappingResource; - ArrayList retrievedConsentMappingResources; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - authorizationResource = ConsentMgtDAOTestData - .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - authorizationResource); - - consentMappingResource = - ConsentMgtDAOTestData - .getSampleTestConsentMappingResource(storedAuthorizationResource.getAuthorizationID()); - - storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, - consentMappingResource); - - retrievedConsentMappingResources = consentCoreDAO.getConsentMappingResources(connection, - storedAuthorizationResource.getAuthorizationID(), storedConsentMappingResource.getMappingStatus()); - } - Assert.assertNotNull(retrievedConsentMappingResources); - } - - @Test - public void testDeleteConsentAttribute() throws Exception { - - ConsentResource storedConsentResource; - ConsentAttributes consentAttributesResource; - boolean isDeleted; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(storedConsentResource.getConsentID()); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - isDeleted = consentCoreDAO.deleteConsentAttributes(connection, storedConsentResource.getConsentID(), - ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - Assert.assertTrue(isDeleted); - } - - @Test - public void testConsentSearchWithConsentIDsList() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, null, - null, null, null, null, null, - 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithConsentIDsListAndTime() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, null, - null, null, null, 1669917425L, 1669917425L, - 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - - } - - @Test - public void testConsentSearchWithClientIDsList() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, null, - ConsentMgtDAOTestData.SAMPLE_CLIENT_IDS_LIST, null, null, null, - null, null, 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithConsentStatusesList() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, - null, ConsentMgtDAOTestData.SAMPLE_CONSENT_STATUSES_LIST, null, null, - null, 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithConsentTypesList() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, - null, ConsentMgtDAOTestData.SAMPLE_CONSENT_STATUSES_LIST, null, null, - null, 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithUserIDsList() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, - null, null, ConsentMgtDAOTestData.SAMPLE_USER_IDS_LIST, null, - null, 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithoutLimitAndOffset() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, null, - null, null, null, null, null, null, - null); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithoutLimitButOffset() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, null, - null, null, null, null, null, null, - 1); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchForNullValues() throws Exception { - - ResultSet mockedResultSetTemp = Mockito.mock(ResultSet.class); - Mockito.doReturn(null).when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_ID); - Mockito.doReturn(null).when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_ID); - ConsentCoreDAOImpl dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); - ArrayList authorizationResources = new ArrayList<>(); - ArrayList consentMappingResources = new ArrayList<>(); - dao.setAuthorizationDataInResponseForGroupedQuery(authorizationResources, - mockedResultSetTemp, ""); - dao.setAccountConsentMappingDataInResponse(consentMappingResources, - mockedResultSetTemp); - Assert.assertTrue(authorizationResources.size() == 0); - Assert.assertTrue(consentMappingResources.size() == 0); - } - - @Test - public void testConsentSearchForNoneNullValues() throws Exception { - - ResultSet mockedResultSetTemp = Mockito.mock(ResultSet.class); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_ID); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_ID); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.ACCOUNT_ID); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_STATUS); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.PERMISSION); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_TYPE); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_STATUS); - Mockito.doReturn("123456").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.UPDATED_TIME); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.USER_ID); - ConsentCoreDAOImpl dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); - ArrayList authorizationResources = new ArrayList<>(); - ArrayList consentMappingResources = new ArrayList<>(); - dao.setAuthorizationDataInResponseForGroupedQuery(authorizationResources, - mockedResultSetTemp, ""); - dao.setAccountConsentMappingDataInResponse(consentMappingResources, - mockedResultSetTemp); - Assert.assertTrue(authorizationResources.size() != 0); - Assert.assertTrue(consentMappingResources.size() != 0); - } - - @Test - public void testConsentSearchForNoneNullValuesNegativeCase() throws Exception { - - ResultSet mockedResultSetTemp = Mockito.mock(ResultSet.class); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_ID); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_ID); - Mockito.doReturn("1,2").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.ACCOUNT_ID); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_STATUS); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.PERMISSION); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_TYPE); - Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_STATUS); - Mockito.doReturn("123456").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.UPDATED_TIME); - Mockito.doReturn("test,test2").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.USER_ID); - ConsentCoreDAOImpl dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); - ArrayList authorizationResources = new ArrayList<>(); - ArrayList consentMappingResources = new ArrayList<>(); - dao.setAuthorizationDataInResponseForGroupedQuery(authorizationResources, - mockedResultSetTemp, ""); - dao.setAccountConsentMappingDataInResponse(consentMappingResources, - mockedResultSetTemp); - Assert.assertTrue(authorizationResources.size() != 0); - Assert.assertTrue(consentMappingResources.size() != 0); - } - - @Test - public void testConsentSearchWithoutOffsetButLimit() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, null, - null, null, null, null, null, 1, - null); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithNoParams() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, - null, null, null, null, - null, 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - } - } - - @Test - public void testConsentSearchWithTimePeriod() throws Exception { - - ArrayList detailedConsentResources; - ArrayList consentIDs = new ArrayList<>(); - long currentTime = System.currentTimeMillis() / 1000; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - storeDataForConsentSearchTest(consentIDs, connection); - detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, - null, null, null, currentTime, - currentTime + 100, 10, 0); - } - - Assert.assertNotNull(detailedConsentResources); - for (DetailedConsentResource resource : detailedConsentResources) { - Assert.assertNotNull(resource.getAuthorizationResources()); - Assert.assertNotNull(resource.getConsentMappingResources()); - Assert.assertNotNull(resource.getConsentAttributes()); - - for (AuthorizationResource authResource : resource.getAuthorizationResources()) { - Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); - } - - Assert.assertTrue((currentTime <= resource.getUpdatedTime()) - && (currentTime + 100 >= resource.getUpdatedTime())); - } - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testSearchConsentsSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString(), - Mockito.anyInt(), Mockito.anyInt()); - consentCoreDAO.searchConsents(mockedConnection, null, null, null, - null, null, null, null, null, null); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testSearchConsentsPreparedResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.searchConsents(mockedConnection, null, null, null, - null, null, null, null, null, null); - } - - @Test - public void testSearchConsentAuthorizations() throws Exception { - - ArrayList authorizationResources; - ConsentResource storedConsentResource; - AuthorizationResource storedAuthorizationResource; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, ConsentMgtDAOTestData - .getSampleTestConsentResource()); - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); - - authorizationResources = consentCoreDAO.searchConsentAuthorizations(connection, - storedConsentResource.getConsentID(), storedAuthorizationResource.getUserID()); - } - - Assert.assertNotNull(authorizationResources); - Assert.assertEquals(storedAuthorizationResource.getAuthorizationID(), - authorizationResources.get(0).getAuthorizationID()); - Assert.assertEquals(storedAuthorizationResource.getConsentID(), - authorizationResources.get(0).getConsentID()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testSearchConsentAuthorizationsSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.searchConsentAuthorizations(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testSearchConsentAuthorizationsResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.searchConsentAuthorizations(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testSearchConsentAuthorizationsNoRecordsFoundError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); - consentCoreDAO.searchConsentAuthorizations(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = OBConsentDataDeletionException.class) - public void testDeleteConsentAttributeSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.deleteConsentAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - - private void storeDataForConsentSearchTest(ArrayList consentIDs, - Connection connection) throws OBConsentDataInsertionException { - - ArrayList authIDs = new ArrayList<>(); - - // Store 3 consent resources - ArrayList consentResources = ConsentMgtDAOTestData.getSampleConsentResourcesList(); - for (ConsentResource resource : consentResources) { - consentIDs.add(consentCoreDAO.storeConsentResource(connection, resource).getConsentID()); - } - - // Store 2 authorization resources for each stored consent - ArrayList authorizationResources = - ConsentMgtDAOTestData.getSampleAuthorizationResourcesList(consentIDs); - for (AuthorizationResource resource : authorizationResources) { - authIDs.add(consentCoreDAO.storeAuthorizationResource(connection, resource).getAuthorizationID()); - } - - // Store 2 consent mapping resources for each authorization resource - ArrayList consentMappingResources = - ConsentMgtDAOTestData.getSampleConsentMappingResourcesList(authIDs); - for (ConsentMappingResource resource : consentMappingResources) { - consentCoreDAO.storeConsentMappingResource(connection, resource); - } - - // Store consent attributes - for (String consentID : consentIDs) { - ConsentAttributes consentAttributesResource = new ConsentAttributes(); - consentAttributesResource.setConsentID(consentID); - consentAttributesResource.setConsentAttributes(ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - } - } - - @Test - public void testUpdateConsentReceipt() throws Exception { - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - String newConsentReceipt = "{\"amendedReceipt\":\"amendedData\"}"; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, - consentResource); - Assert.assertTrue(consentCoreDAO.updateConsentReceipt(connection, storedConsentResource.getConsentID(), - newConsentReceipt)); - } - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentReceiptSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.updateConsentReceipt(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentReceiptUpdateError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - consentCoreDAO.updateConsentReceipt(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); - } - - @Test - public void testUpdateConsentValidityTime() throws Exception { - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - long newConsentValidityTime = 12345; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, - consentResource); - Assert.assertTrue(consentCoreDAO.updateConsentValidityTime(connection, storedConsentResource.getConsentID(), - newConsentValidityTime)); - } - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentValidityTimeSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.updateConsentValidityTime(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - } - - @Test (expectedExceptions = OBConsentDataUpdationException.class) - public void testUpdateConsentValidityTimeUpdateError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - consentCoreDAO.updateConsentValidityTime(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, - ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - } - - @Test - public void testRetrieveConsentIdByConsentAttributeNameAndValue() throws Exception { - - ConsentAttributes consentAttributesResource; - ArrayList consentIdList; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - consentIdList = consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(connection, - "payment-type", "domestic-payments"); - - } - Assert.assertFalse(consentIdList.isEmpty()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentIdByConsentAttributeNameAndValueSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(mockedConnection, "payment-type", - "domestic-payments"); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentIdByConsentAttributeNameAndValueResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(mockedConnection, "payment-type", - "domestic-payments"); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentIdByConsentAttributeNameAndValueNoRecordsFoundError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); - consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(mockedConnection, "payment-type", - "domestic-payments"); - } - - @Test - public void testRetrieveExpiringConsentsWithNoEligibility() throws Exception { - - ConsentAttributes consentAttributesResource; - ArrayList expirationEligibleConsents; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleStoredTestConsentResource(); - consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_EXPIRED_STATUS); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); - consentAttributesResource.getConsentAttributes().put( - ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE, "1632918113"); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - expirationEligibleConsents = consentCoreDAO.getExpiringConsents(connection, - "Authorized,awaitingAuthorisation"); - - } - Assert.assertTrue(expirationEligibleConsents.isEmpty()); - } - - @Test (dependsOnMethods = {"testRetrieveExpiringConsentsWithNoEligibility"}) - public void testRetrieveExpiringConsentsWithEligibility() throws Exception { - - ConsentAttributes consentAttributesResource; - ArrayList expirationEligibleConsents; - ConsentResource retrievedConsentResource; - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); - - consentAttributesResource = ConsentMgtDAOTestData - .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); - consentAttributesResource.getConsentAttributes().put( - ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE, "1632918113"); - - consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); - - expirationEligibleConsents = consentCoreDAO.getExpiringConsents(connection, - "Authorized,awaitingAuthorisation"); - - } - Assert.assertFalse(expirationEligibleConsents.isEmpty()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveExpiringConsentsDataRetrievalError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getExpiringConsents(mockedConnection, "Authorized,awaitingAuthorisation"); - } - - @DataProvider(name = "storeConsentHistoryDataProvider") - public Object[][] storeConsentHistoryData() { - - /* - * historyID - * consentID - * changedAttributes - * consentType - * amendedTimestamp - * amendmentReason - */ - return ConsentMgtDAOTestData.DataProviders.CONSENT_HISTORY_DATA_HOLDER; - } - - @Test (dataProvider = "storeConsentHistoryDataProvider") - public void testStoreConsentAmendmentHistory(String historyID, String recordID, String changedAttributes, - String consentType, long amendedTimestamp, String amendmentReason) throws Exception { - - boolean result; - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - result = consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, - recordID, consentType, changedAttributes, amendmentReason); - } - Assert.assertTrue(result); - } - - @Test (dataProvider = "storeConsentHistoryDataProvider", expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentAmendmentHistoryWithInvalidConsentType(String historyID, String recordID, - String changedAttributes, String consentType, long amendedTimestamp, String amendmentReason) throws Exception { - - boolean result; - consentType = "sampleConsentType"; - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - result = consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, - recordID, consentType, changedAttributes, amendmentReason); - } - Assert.assertTrue(result); - } - - @Test (dataProvider = "storeConsentHistoryDataProvider", expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentAmendmentHistoryInsertionError(String historyID, String recordID, - String changedAttributes, String consentType, long amendedTimestamp, String amendmentReason) - throws Exception { - - Mockito.doReturn(Mockito.mock(PreparedStatement.class)).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(Mockito.mock(PreparedStatement.class)).executeUpdate(); - - consentCoreDAO.storeConsentAmendmentHistory(mockedConnection, historyID, amendedTimestamp, - recordID, consentType, changedAttributes, amendmentReason); - } - - @Test (dataProvider = "storeConsentHistoryDataProvider", expectedExceptions = OBConsentDataInsertionException.class) - public void testStoreConsentAmendmentHistorySQLError(String historyID, String recordID, - String changedAttributes, String consentType, long amendedTimestamp, String amendmentReason) - throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.storeConsentAmendmentHistory(mockedConnection, historyID, amendedTimestamp, - recordID, consentType, changedAttributes, amendmentReason); - } - - @Test(dependsOnMethods = {"testStoreConsentAmendmentHistory"}) - public void testRetrieveConsentAmendmentHistory() throws Exception { - - Map consentHistoryResourcesDataMap; - String expectedConsentDataTypes[] = { ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, - ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, - ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, - ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, - "AmendedReason"}; - - List expectedConsentDataTypesList = Arrays.asList(expectedConsentDataTypes); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - consentHistoryResourcesDataMap = consentCoreDAO.retrieveConsentAmendmentHistory(connection, - ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); - Assert.assertNotNull(consentHistoryResourcesDataMap); - for (Map.Entry consentHistoryDataEntry : - consentHistoryResourcesDataMap.entrySet()) { - Assert.assertEquals(ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, consentHistoryDataEntry.getKey()); - Map consentHistoryData = - consentHistoryDataEntry.getValue().getChangedAttributesJsonDataMap(); - for (Map.Entry consentHistoryDataTypeEntry : - consentHistoryData.entrySet()) { - Assert.assertNotNull(consentHistoryDataTypeEntry.getKey()); - Assert.assertTrue(expectedConsentDataTypesList.contains((consentHistoryDataTypeEntry.getKey()))); - Assert.assertNotNull(consentHistoryDataTypeEntry.getValue()); - } - } - } - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAmendmentHistoryDataRetrievalError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.retrieveConsentAmendmentHistory(mockedConnection, - ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testRetrieveConsentAmendmentHistoryPrepStmtSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.retrieveConsentAmendmentHistory(mockedConnection, - ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); - } - - @Test - public void testRetrieveConsentAmendmentHistoryNoRecordsFound() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); - - Map result = consentCoreDAO.retrieveConsentAmendmentHistory(mockedConnection, - ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); - Assert.assertEquals(result.size(), 0); - } - - @Test - public void testDeleteConsentData() throws Exception { - - boolean isDeleted; - boolean isDeletedOnRetentionTable; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(1).when(mockedPreparedStatement).executeUpdate(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - ConsentResource storeConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - isDeleted = consentCoreDAO.deleteConsentData(mockedConnection, storeConsentResource.getConsentID(), - false); - isDeletedOnRetentionTable = consentCoreDAO.deleteConsentData(mockedConnection, - storeConsentResource.getConsentID(), true); - } - Assert.assertTrue(isDeleted); - Assert.assertTrue(isDeletedOnRetentionTable); - } - - @Test - public void testDeleteConsentData2() throws Exception { - - boolean isDeleted; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - ConsentResource storeConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - isDeleted = consentCoreDAO.deleteConsentData(mockedConnection, storeConsentResource.getConsentID(), - false); - } - Assert.assertTrue(!isDeleted); - } - - @Test (expectedExceptions = OBConsentDataDeletionException.class) - public void testDeleteConsentDataSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.deleteConsentData(mockedConnection, "", false); - } - - @Test - public void testGetConsentStatusAuditRecordsByConsentId() throws Exception { - - ConsentResource storedConsentResource; - ConsentStatusAuditRecord consentStatusAuditRecord; - ConsentStatusAuditRecord storedConsentStatusAuditRecord; - ArrayList retrievedConsentStatusAuditRecords; - ArrayList retrievedConsentStatusAuditRecordsInRetentionTable; - ArrayList retrievedConsentStatusAuditRecordsWithLimit; - ArrayList retrievedConsentStatusAuditRecordsWithLimitAndOffset; - ArrayList retrievedConsentStatusAuditRecordsWithLimitOnly; - ArrayList retrievedConsentStatusAuditRecordsWithOffsetOnly; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - - consentStatusAuditRecord = ConsentMgtDAOTestData - .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), - storedConsentResource.getCurrentStatus()); - - storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, - consentStatusAuditRecord); - - connection.commit(); - ArrayList consentIds = new ArrayList<>(); - consentIds.add(storedConsentStatusAuditRecord.getConsentID()); - retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, - consentIds, null, null, false); - retrievedConsentStatusAuditRecordsInRetentionTable = - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, null, null, true); - retrievedConsentStatusAuditRecordsWithLimit = - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, 10, 0, false); - retrievedConsentStatusAuditRecordsWithLimitAndOffset = - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, 10, 1, false); - retrievedConsentStatusAuditRecordsWithLimitOnly = - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, 10, null, false); - retrievedConsentStatusAuditRecordsWithOffsetOnly = - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, null, 1, false); - } - Assert.assertNotNull(retrievedConsentStatusAuditRecords); - Assert.assertTrue(retrievedConsentStatusAuditRecordsInRetentionTable.isEmpty()); - Assert.assertNotNull(retrievedConsentStatusAuditRecordsWithLimit); - Assert.assertTrue(retrievedConsentStatusAuditRecordsWithLimit.size() > 0); - Assert.assertTrue(retrievedConsentStatusAuditRecordsWithLimitAndOffset.isEmpty()); - Assert.assertTrue(!retrievedConsentStatusAuditRecordsWithLimitOnly.isEmpty()); - Assert.assertTrue(!retrievedConsentStatusAuditRecordsWithOffsetOnly.isEmpty()); - for (ConsentStatusAuditRecord record : - retrievedConsentStatusAuditRecords) { - Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); - } - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testGetConsentStatusAuditRecordsByConsentIdSQLError() throws Exception { - ArrayList consentIds = new ArrayList<>(); - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(mockedConnection, - consentIds, null, null, false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testGetConsentStatusAuditRecordsByConsentIdSQLErrorForResults() throws Exception { - ArrayList consentIds = new ArrayList<>(); - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(mockedConnection, - consentIds, null, null, false); - } - - @Test - public void testGetListOfConsentIds() throws Exception { - - ConsentResource storedConsentResource; - ArrayList listOfConsentIds; - ArrayList listOfConsentIdsInRetentionTable; - - ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); - - try (Connection connection = DAOUtils.getConnection(DB_NAME)) { - - storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); - listOfConsentIds = consentCoreDAO.getListOfConsentIds(connection, false); - listOfConsentIdsInRetentionTable = consentCoreDAO.getListOfConsentIds(connection, true); - } - Assert.assertNotNull(listOfConsentIds); - Assert.assertTrue(listOfConsentIdsInRetentionTable.isEmpty()); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testGetListOfConsentIdsSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - consentCoreDAO.getListOfConsentIds(mockedConnection, false); - } - - @Test (expectedExceptions = OBConsentDataRetrievalException.class) - public void testGetListOfConsentIdsSQLErrorForResults() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - consentCoreDAO.getListOfConsentIds(mockedConnection, false); - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/util/ConsentMgtDAOTestData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/util/ConsentMgtDAOTestData.java deleted file mode 100644 index 91e082f7..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/util/ConsentMgtDAOTestData.java +++ /dev/null @@ -1,558 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.util; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import net.minidev.json.JSONObject; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Consent management DAO test data. - */ -public class ConsentMgtDAOTestData { - - public static final String SAMPLE_CONSENT_RECEIPT = "{\"validUntil\": \"2020-10-20\", \"frequencyPerDay\": 1," + - " \"recurringIndicator\": false, \"combinedServiceIndicator\": true}"; - - public static final String SAMPLE_CONSENT_TYPE = "accounts"; - - public static final int SAMPLE_CONSENT_FREQUENCY = 1; - - public static final Long SAMPLE_CONSENT_VALIDITY_PERIOD = 1638337852L; - - public static final String SAMPLE_CONSENT_ID = "2222"; - - public static final String SAMPLE_AUTHORIZATION_ID = "3333"; - - public static final boolean SAMPLE_RECURRING_INDICATOR = true; - - public static final String SAMPLE_CURRENT_STATUS = "Authorized"; - - public static final String SAMPLE_PREVIOUS_STATUS = "Received"; - - public static final String SAMPLE_AUTHORIZATION_TYPE = "authorizationType"; - - public static final String SAMPLE_USER_ID = "admin@wso2.com"; - - public static final String SAMPLE_AUDIT_ID = "4321234"; - - public static final String SAMPLE_NEW_USER_ID = "ann@gold.com"; - - public static final String SAMPLE_AUTHORIZATION_STATUS = "awaitingAuthorization"; - - public static final String SAMPLE_EXPIRED_STATUS = "Expired"; - - public static final String SAMPLE_ACCOUNT_ID = "123456789"; - - public static final String SAMPLE_MAPPING_ID = "12345"; - - public static final String SAMPLE_MAPPING_ID_2 = "67890"; - - public static final String SAMPLE_MAPPING_STATUS = "active"; - - public static final String SAMPLE_NEW_MAPPING_STATUS = "inactive"; - - public static final String SAMPLE_PERMISSION = "samplePermission"; - - public static final String SAMPLE_REASON = "sample reason"; - - public static final String SAMPLE_ACTION_BY = "admin@wso2.com"; - - public static final String SAMPLE_HISTORY_ID = "1234"; - - public static final Long SAMPLE_UPDATED_TIME = 1638337892L; - - public static final String SAMPLE_AMENDMENT_REASON = "sampleReason"; - - public static final Map SAMPLE_CONSENT_ATTRIBUTES_MAP = new HashMap() { - { - put("x-request-id", UUID.randomUUID().toString()); - put("idenpotency-key", UUID.randomUUID().toString()); - put("payment-type", "domestic-payments"); - put("sessionDataKey", "{\"sessionDataKey\":\"a0c8cd6d-eca0-4c4d-9544-2b39e7e1c180\",\"userId\":\"01Z79\"}"); - } - }; - - public static final ArrayList SAMPLE_CONSENT_ATTRIBUTES_KEYS = new ArrayList() { - { - add("x-request-id"); - add("idenpotency-key"); - } - }; - - public static final ArrayList UNMATCHED_MAPPING_IDS = new ArrayList() { - { - add("4444"); - add("5555"); - } - }; - - private static final ArrayList SAMPLE_CONSENT_RECEIPTS_LIST = new ArrayList() { - { - add("{\"element1\": \"value1\"}"); - add("{\"element2\": \"value2\"}"); - add("{\"element3\": \"value3\"}"); - } - }; - - public static final ArrayList SAMPLE_CONSENT_TYPES_LIST = new ArrayList() { - { - add("accounts"); - add("payments"); - add("cof"); - } - }; - - public static final ArrayList SAMPLE_CONSENT_STATUSES_LIST = new ArrayList() { - { - add("created"); - add("authorized"); - add("awaitingAuthorization"); - - } - }; - - public static final ArrayList SAMPLE_CLIENT_IDS_LIST = new ArrayList() { - { - add("clientID1"); - add("clientID2"); - add("clientID3"); - - } - }; - - public static final ArrayList SAMPLE_USER_IDS_LIST = new ArrayList() { - { - add("userID1"); - add("userID2"); - add("userID3"); - } - }; - - private static final ArrayList SAMPLE_VALIDITY_PERIOD_LIST = new ArrayList() { - { - add(1613454661L); - add(1623654661L); - add(1633654671L); - } - }; - - private static final JSONObject SAMPLE_CONSENT_BASIC_DATA_CHANGED_ATTRIBUTES_JSON = new JSONObject() { - { - put("RECEIPT", SAMPLE_CONSENT_RECEIPT); - put("VALIDITY_TIME", SAMPLE_CONSENT_VALIDITY_PERIOD); - put("UPDATED_TIME", SAMPLE_UPDATED_TIME); - } - }; - - public static final JSONObject SAMPLE_CONSENT_ATTRIBUTES_CHANGED_ATTRIBUTES_JSON = new JSONObject() { - { - put("x-request-id", UUID.randomUUID().toString()); - put("idempotency-key", UUID.randomUUID().toString()); - } - }; - - public static final JSONObject SAMPLE_CONSENT_MAPPINGS_CHANGED_ATTRIBUTES_JSON = new JSONObject() { - { - put("MAPPING_STATUS", SAMPLE_MAPPING_STATUS); - } - }; - - public static final String SAMPLE_CONSENT_FILE = "sample file content"; - - /** - * Data Providers class. - */ - public static final class DataProviders { - - /* - * consentID - * clientID - * receipt - * consentType - * consentFrequency - * validityPeriod - * recurringIndicator - * currentStatus - * createdTime - */ - public static final Object[][] CONSENT_RESOURCE_DATA_HOLDER = new Object[][] { - - { - UUID.randomUUID().toString(), - SAMPLE_CONSENT_RECEIPT, - SAMPLE_CONSENT_TYPE, - SAMPLE_CONSENT_FREQUENCY, - SAMPLE_CONSENT_VALIDITY_PERIOD, - SAMPLE_RECURRING_INDICATOR, - SAMPLE_CURRENT_STATUS, - } - }; - - /* - * authorizationType - * userID - * authorizationStatus - */ - public static final Object[][] AUTHORIZATION_RESOURCE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_AUTHORIZATION_TYPE, - SAMPLE_USER_ID, - SAMPLE_AUTHORIZATION_STATUS - } - }; - - /* - * accountID - * permission - * mappingStatus - */ - public static final Object[][] CONSENT_MAPPING_RESOURCE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_ACCOUNT_ID, - SAMPLE_PERMISSION, - SAMPLE_MAPPING_STATUS - } - }; - - /* - * currentStatus - * reason - * actionBy - * currentStatus - */ - public static final Object[][] CONSENT_STATUS_AUDIT_RECORD_DATA_HOLDER = new Object[][] { - - { - SAMPLE_CURRENT_STATUS, - SAMPLE_REASON, - SAMPLE_ACTION_BY, - SAMPLE_CURRENT_STATUS - } - }; - - /* - * consentAttributesMap - */ - public static final Object[][] CONSENT_ATTRIBUTES_DATA_HOLDER = new Object[][] { - - { - SAMPLE_CONSENT_ATTRIBUTES_MAP - } - }; - - /* - * consentFile - */ - public static final Object[][] CONSENT_FILE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_CONSENT_FILE - } - }; - - /* - * newConsentStatus - */ - public static final Object[][] CONSENT_STATUS_UPDATE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_CURRENT_STATUS - } - }; - - /* - * newMappingStatus - */ - public static final Object[][] CONSENT_MAPPING_STATUS_UPDATE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_NEW_MAPPING_STATUS - } - }; - - /* - * newAuthorizationStatus - */ - public static final Object[][] CONSENT_AUTHORIZATION_STATUS_UPDATE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_CURRENT_STATUS - } - }; - - /* - * newAuthorizationUser - */ - public static final Object[][] CONSENT_AUTHORIZATION_USER_UPDATE_DATA_HOLDER = new Object[][] { - - { - SAMPLE_NEW_USER_ID - } - }; - - /* - * consentAttributeKeys - */ - public static final Object[][] CONSENT_ATTRIBUTES_GET_DATA_HOLDER = new Object[][] { - - { - SAMPLE_CONSENT_ATTRIBUTES_KEYS - } - }; - - /* - * historyID - * consentID - * changedAttributes - * consentType - * amendedTimestamp - */ - public static final Object[][] CONSENT_HISTORY_DATA_HOLDER = new Object[][] { - - { - SAMPLE_HISTORY_ID, - SAMPLE_CONSENT_ID, - SAMPLE_CONSENT_BASIC_DATA_CHANGED_ATTRIBUTES_JSON.toString(), - ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, - SAMPLE_UPDATED_TIME, - SAMPLE_AMENDMENT_REASON - }, - { - SAMPLE_HISTORY_ID, - SAMPLE_CONSENT_ID, - SAMPLE_CONSENT_ATTRIBUTES_CHANGED_ATTRIBUTES_JSON.toString(), - ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, - SAMPLE_UPDATED_TIME, - SAMPLE_AMENDMENT_REASON - }, - { - SAMPLE_HISTORY_ID, - SAMPLE_MAPPING_ID, - SAMPLE_CONSENT_MAPPINGS_CHANGED_ATTRIBUTES_JSON.toString(), - ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, - SAMPLE_UPDATED_TIME, - SAMPLE_AMENDMENT_REASON - }, - { - SAMPLE_HISTORY_ID, - SAMPLE_MAPPING_ID_2, - SAMPLE_CONSENT_MAPPINGS_CHANGED_ATTRIBUTES_JSON.toString(), - ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, - SAMPLE_UPDATED_TIME, - SAMPLE_AMENDMENT_REASON - }, - { - SAMPLE_HISTORY_ID, - SAMPLE_AUTHORIZATION_ID, - "null", - ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, - SAMPLE_UPDATED_TIME, - SAMPLE_AMENDMENT_REASON - } - }; - } - - public static List getRecordIDListOfSampleConsentHistory() { - - List recordIdList = new ArrayList<>(); - recordIdList.add(ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); - recordIdList.add(ConsentMgtDAOTestData.SAMPLE_MAPPING_ID); - recordIdList.add(ConsentMgtDAOTestData.SAMPLE_MAPPING_ID_2); - recordIdList.add(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); - return recordIdList; - } - - public static ConsentResource getSampleTestConsentResource() { - - ConsentResource consentResource = new ConsentResource(); - consentResource.setReceipt(ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); - consentResource.setClientID(UUID.randomUUID().toString()); - consentResource.setConsentType(ConsentMgtDAOTestData.SAMPLE_CONSENT_TYPE); - consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); - consentResource.setConsentFrequency(ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY); - consentResource.setValidityPeriod(ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - consentResource.setRecurringIndicator(ConsentMgtDAOTestData.SAMPLE_RECURRING_INDICATOR); - - return consentResource; - } - - public static ConsentResource getSampleStoredTestConsentResource() { - - ConsentResource consentResource = new ConsentResource(); - consentResource.setConsentID(UUID.randomUUID().toString()); - consentResource.setReceipt(ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); - consentResource.setClientID(UUID.randomUUID().toString()); - consentResource.setConsentType(ConsentMgtDAOTestData.SAMPLE_CONSENT_TYPE); - consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); - consentResource.setConsentFrequency(ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY); - consentResource.setValidityPeriod(ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - consentResource.setRecurringIndicator(ConsentMgtDAOTestData.SAMPLE_RECURRING_INDICATOR); - - return consentResource; - } - - /** - * Generated three sample consent resources for testing purposes. - * - * @return sample consent resources list - */ - public static ArrayList getSampleConsentResourcesList() { - - ArrayList consentResources = new ArrayList<>(); - - for (int i = 0; i < 3; i++) { - ConsentResource consentResource = new ConsentResource(); - consentResource.setReceipt(SAMPLE_CONSENT_RECEIPTS_LIST.get(i)); - consentResource.setClientID(SAMPLE_CLIENT_IDS_LIST.get(i)); - consentResource.setConsentType(SAMPLE_CONSENT_TYPES_LIST.get(i)); - consentResource.setCurrentStatus(SAMPLE_CONSENT_STATUSES_LIST.get(i)); - consentResource.setConsentFrequency(0); - consentResource.setValidityPeriod(SAMPLE_VALIDITY_PERIOD_LIST.get(i)); - consentResource.setRecurringIndicator(false); - consentResources.add(consentResource); - } - return consentResources; - } - - public static ArrayList getSampleAuthorizationResourcesList(ArrayList consentIDs) { - - ArrayList authorizationResources = new ArrayList<>(); - - for (int i = 0; i < consentIDs.size(); i++) { - for (int j = 0; j < 2; j++) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(consentIDs.get(i)); - authorizationResource.setAuthorizationType(SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(SAMPLE_USER_IDS_LIST.get(i)); - authorizationResource.setAuthorizationStatus(SAMPLE_AUTHORIZATION_STATUS); - authorizationResources.add(authorizationResource); - } - } - return authorizationResources; - } - - public static ArrayList getSampleConsentMappingResourcesList(ArrayList authIDs) { - - ArrayList consentMappingResources = new ArrayList<>(); - - for (int i = 0; i < authIDs.size(); i++) { - for (int j = 0; j < 2; j++) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(authIDs.get(i)); - consentMappingResource.setAccountID(SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(SAMPLE_MAPPING_STATUS); - consentMappingResources.add(consentMappingResource); - } - } - return consentMappingResources; - } - - public static AuthorizationResource getSampleTestAuthorizationResource(String consentID) { - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(consentID); - authorizationResource.setAuthorizationType(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(ConsentMgtDAOTestData.SAMPLE_USER_ID); - authorizationResource.setAuthorizationStatus(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); - - return authorizationResource; - } - - public static AuthorizationResource getSampleStoredTestAuthorizationResource() { - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(UUID.randomUUID().toString()); - authorizationResource.setAuthorizationID(UUID.randomUUID().toString()); - authorizationResource.setAuthorizationType(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(ConsentMgtDAOTestData.SAMPLE_USER_ID); - authorizationResource.setAuthorizationStatus(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); - authorizationResource.setUpdatedTime(System.currentTimeMillis() / 1000); - - return authorizationResource; - } - - public static ConsentMappingResource getSampleTestConsentMappingResource(String authorizationID) { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(authorizationID); - consentMappingResource.setAccountID(ConsentMgtDAOTestData.SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(ConsentMgtDAOTestData.SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); - - return consentMappingResource; - } - - public static ConsentMappingResource getSampleTestConsentMappingResourceWithAccountId(String authorizationID, - String accountID) { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(authorizationID); - consentMappingResource.setAccountID(accountID); - consentMappingResource.setPermission(ConsentMgtDAOTestData.SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); - - return consentMappingResource; - } - - public static ConsentStatusAuditRecord getSampleTestConsentStatusAuditRecord(String consentID, - String currentStatus) { - - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(consentID); - consentStatusAuditRecord.setCurrentStatus(currentStatus); - consentStatusAuditRecord.setReason(ConsentMgtDAOTestData.SAMPLE_REASON); - consentStatusAuditRecord.setActionBy(ConsentMgtDAOTestData.SAMPLE_ACTION_BY); - consentStatusAuditRecord.setPreviousStatus(ConsentMgtDAOTestData.SAMPLE_PREVIOUS_STATUS); - - return consentStatusAuditRecord; - } - - public static ConsentAttributes getSampleTestConsentAttributesObject(String consentID) { - - ConsentAttributes consentAttributes = new ConsentAttributes(); - consentAttributes.setConsentID(consentID); - consentAttributes.setConsentAttributes(ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - return consentAttributes; - } - - public static ConsentFile getSampleConsentFileObject(String fileContent) { - - ConsentFile consentFile = new ConsentFile(); - consentFile.setConsentID(UUID.randomUUID().toString()); - consentFile.setConsentFile(fileContent); - - return consentFile; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/util/DAOUtils.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/util/DAOUtils.java deleted file mode 100644 index dd019282..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/dao/util/DAOUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.dao.util; - -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.commons.lang3.StringUtils; - -import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - -/** - * DAO utils. - */ -public class DAOUtils { - - private static Map dataSourceMap = new HashMap<>(); - - public static void initializeDataSource(String databaseName, String scriptPath) throws Exception { - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName("org.h2.Driver"); - dataSource.setUsername("username"); - dataSource.setPassword("password"); - dataSource.setUrl("jdbc:h2:mem:" + databaseName); - - try (Connection connection = dataSource.getConnection()) { - connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'"); - } - dataSourceMap.put(databaseName, dataSource); - } - - public static Connection getConnection(String database) throws SQLException { - if (dataSourceMap.get(database) != null) { - return dataSourceMap.get(database).getConnection(); - } - throw new RuntimeException("Invalid datasource."); - } - - public static String getFilePath(String fileName) { - if (StringUtils.isNotBlank(fileName)) { - return Paths.get(System.getProperty("user.dir"), "src", "test", "resources", fileName) - .toString(); - } - return null; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/resources/dbScripts/h2.sql b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/resources/dbScripts/h2.sql deleted file mode 100644 index b54f6c72..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/resources/dbScripts/h2.sql +++ /dev/null @@ -1,138 +0,0 @@ --- All the data related to time are stored in unix time stamp and therefore, the data types for the time related data --- are represented in BIGINT. --- Since the database systems does not support adding default unix time to the database columns, the default data --- storing is handled within the database queries. - -CREATE TABLE IF NOT EXISTS OB_CONSENT ( - CONSENT_ID VARCHAR(255) NOT NULL, - RECEIPT CLOB NOT NULL, - CREATED_TIME BIGINT NOT NULL, - UPDATED_TIME BIGINT NOT NULL, - CLIENT_ID VARCHAR(255) NOT NULL, - CONSENT_TYPE VARCHAR(64) NOT NULL, - CURRENT_STATUS VARCHAR(64) NOT NULL, - CONSENT_FREQUENCY INT, - VALIDITY_TIME BIGINT, - RECURRING_INDICATOR BOOLEAN, - PRIMARY KEY (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_AUTH_RESOURCE ( - AUTH_ID VARCHAR(255) NOT NULL, - CONSENT_ID VARCHAR(255) NOT NULL, - AUTH_TYPE VARCHAR(255) NOT NULL, - USER_ID VARCHAR(255), - AUTH_STATUS VARCHAR(255) NOT NULL, - UPDATED_TIME BIGINT NOT NULL, - PRIMARY KEY(AUTH_ID), - CONSTRAINT FK_ID_OB_CONSENT_AUTH_RESOURCE FOREIGN KEY (CONSENT_ID) REFERENCES OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_MAPPING ( - MAPPING_ID VARCHAR(255) NOT NULL, - AUTH_ID VARCHAR(255) NOT NULL, - ACCOUNT_ID VARCHAR(255) NOT NULL, - PERMISSION VARCHAR(255) NOT NULL, - MAPPING_STATUS VARCHAR(255) NOT NULL, - PRIMARY KEY(MAPPING_ID), - CONSTRAINT FK_OB_CONSENT_MAPPING FOREIGN KEY (AUTH_ID) REFERENCES OB_CONSENT_AUTH_RESOURCE (AUTH_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_STATUS_AUDIT ( - STATUS_AUDIT_ID VARCHAR(255) NOT NULL, - CONSENT_ID VARCHAR(255) NOT NULL, - CURRENT_STATUS VARCHAR(255) NOT NULL, - ACTION_TIME BIGINT NOT NULL, - REASON VARCHAR(255), - ACTION_BY VARCHAR(255), - PREVIOUS_STATUS VARCHAR(255), - PRIMARY KEY(STATUS_AUDIT_ID), - CONSTRAINT FK_OB_CONSENT_STATUS_AUDIT FOREIGN KEY (CONSENT_ID) REFERENCES OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_FILE ( - CONSENT_ID VARCHAR(255) NOT NULL, - CONSENT_FILE CLOB, - PRIMARY KEY(CONSENT_ID), - CONSTRAINT FK_OB_CONSENT_FILE FOREIGN KEY (CONSENT_ID) REFERENCES OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_ATTRIBUTE ( - CONSENT_ID VARCHAR(255) NOT NULL, - ATT_KEY VARCHAR(255) NOT NULL, - ATT_VALUE VARCHAR(1023) NOT NULL, - PRIMARY KEY(CONSENT_ID, ATT_KEY), - CONSTRAINT FK_OB_CONSENT_ATTRIBUTE FOREIGN KEY (CONSENT_ID) REFERENCES OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_HISTORY ( - TABLE_ID VARCHAR(10) NOT NULL, - RECORD_ID VARCHAR(255) NOT NULL, - HISTORY_ID VARCHAR(255) NOT NULL, - CHANGED_VALUES CLOB NOT NULL, - REASON VARCHAR(255) NOT NULL, - EFFECTIVE_TIMESTAMP BIGINT NOT NULL, - PRIMARY KEY (TABLE_ID,RECORD_ID,HISTORY_ID) -); - -CREATE TABLE IF NOT EXISTS RET_OB_CONSENT ( - CONSENT_ID VARCHAR(255) NOT NULL, - RECEIPT CLOB NOT NULL, - CREATED_TIME BIGINT NOT NULL, - UPDATED_TIME BIGINT NOT NULL, - CLIENT_ID VARCHAR(255) NOT NULL, - CONSENT_TYPE VARCHAR(64) NOT NULL, - CURRENT_STATUS VARCHAR(64) NOT NULL, - CONSENT_FREQUENCY INT, - VALIDITY_TIME BIGINT, - RECURRING_INDICATOR BOOLEAN, - PRIMARY KEY (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS RET_OB_CONSENT_AUTH_RESOURCE ( - AUTH_ID VARCHAR(255) NOT NULL, - CONSENT_ID VARCHAR(255) NOT NULL, - AUTH_TYPE VARCHAR(255) NOT NULL, - USER_ID VARCHAR(255), - AUTH_STATUS VARCHAR(255) NOT NULL, - UPDATED_TIME BIGINT NOT NULL, - PRIMARY KEY(AUTH_ID), - CONSTRAINT FK_ID_RET_OB_CONSENT_AUTH_RESOURCE FOREIGN KEY (CONSENT_ID) REFERENCES RET_OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS RET_OB_CONSENT_MAPPING ( - MAPPING_ID VARCHAR(255) NOT NULL, - AUTH_ID VARCHAR(255) NOT NULL, - ACCOUNT_ID VARCHAR(255) NOT NULL, - PERMISSION VARCHAR(255) NOT NULL, - MAPPING_STATUS VARCHAR(255) NOT NULL, - PRIMARY KEY(MAPPING_ID), - CONSTRAINT FK_RET_OB_CONSENT_MAPPING FOREIGN KEY (AUTH_ID) REFERENCES RET_OB_CONSENT_AUTH_RESOURCE (AUTH_ID) -); - -CREATE TABLE IF NOT EXISTS RET_OB_CONSENT_STATUS_AUDIT ( - STATUS_AUDIT_ID VARCHAR(255) NOT NULL, - CONSENT_ID VARCHAR(255) NOT NULL, - CURRENT_STATUS VARCHAR(255) NOT NULL, - ACTION_TIME BIGINT NOT NULL, - REASON VARCHAR(255), - ACTION_BY VARCHAR(255), - PREVIOUS_STATUS VARCHAR(255), - PRIMARY KEY(STATUS_AUDIT_ID), - CONSTRAINT FK_RET_OB_CONSENT_STATUS_AUDIT FOREIGN KEY (CONSENT_ID) REFERENCES RET_OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS RET_OB_CONSENT_FILE ( - CONSENT_ID VARCHAR(255) NOT NULL, - CONSENT_FILE CLOB, - PRIMARY KEY(CONSENT_ID), - CONSTRAINT FK_RET_OB_CONSENT_FILE FOREIGN KEY (CONSENT_ID) REFERENCES RET_OB_CONSENT (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS OB_CONSENT_ATTRIBUTE ( - CONSENT_ID VARCHAR(255) NOT NULL, - ATT_KEY VARCHAR(255) NOT NULL, - ATT_VALUE VARCHAR(255) NOT NULL, - PRIMARY KEY(CONSENT_ID, ATT_KEY), - CONSTRAINT FK_RET_OB_CONSENT_ATTRIBUTE FOREIGN KEY (CONSENT_ID) REFERENCES RET_OB_CONSENT (CONSENT_ID) -); diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/resources/testng.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/resources/testng.xml deleted file mode 100644 index 7a3f38de..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.dao/src/test/resources/testng.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/pom.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/pom.xml deleted file mode 100644 index e6aaeb14..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/pom.xml +++ /dev/null @@ -1,238 +0,0 @@ - - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.consent.service - WSO2 Open Banking - Consent Service - WSO2 Open Banking - Consent Service Module - bundle - - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.authentication.framework - provided - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.dao - provided - - - commons-dbcp - commons-dbcp - - - commons-logging - commons-logging - - - org.testng - testng - test - - - com.h2database - h2 - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - org.mockito - mockito-all - test - - - org.powermock - powermock-api-mockito - test - - - org.powermock - powermock-module-testng - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - target/jacoco.exec - - true - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - **/*Constants.class - **/*Component.class - **/*DataHolder.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - COMPLEXITY - COVEREDRATIO - 0.76 - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.consent.mgt.service.internal - - - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - org.wso2.carbon.identity.oauth2.*;version="${identity.inbound.auth.oauth.version.range}", - com.wso2.openbanking.accelerator.common.*;version="${project.version}", - org.apache.commons.lang3;version="${commons-lang.version}" - - - !com.wso2.openbanking.accelerator.consent.mgt.service.internal, - com.wso2.openbanking.accelerator.consent.mgt.service.*;version="${project.version}", - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/ConsentCoreService.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/ConsentCoreService.java deleted file mode 100644 index 067c2b70..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/ConsentCoreService.java +++ /dev/null @@ -1,732 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; - -import java.util.ArrayList; -import java.util.Map; - -/** - * Consent core service interface. - */ -public interface ConsentCoreService { - - /** - * This method is used to create a consent. The following functionality contains in this method. - * - * 1. Creates a consent resource - * 2. If available, stores consent attributes - * 3. Create an audit record for consent creation - * 4. If isImplicitAuth parameter is true, creates an authorization resource - * - * @param consentResource consent resource - * @param userID user ID is optional and used to create the audit record - * @param authStatus authorization status - * @param authType authorization type (eg. authorization, cancellation) - * @param isImplicitAuth flag to determine whether authorization is implicit or not - * @return returns DetailedConsentResource - * @throws ConsentManagementException thrown if any error occur in the process - */ - DetailedConsentResource createAuthorizableConsent(ConsentResource consentResource, String userID, - String authStatus, String authType, - boolean isImplicitAuth) - throws ConsentManagementException; - - /** - * This method is used to create an exclusive consent. The following functionality contains in this method. - * - * 1. Update existing consent statuses as necessary and deactivate their account mappings - * 2. Create audit records for necessary consent updates - * 3. Create a new authorizable consent - * - * @param consentResource consent resource - * @param userID user ID - * @param authStatus authorization status - * @param authType authorization type - * @param applicableExistingConsentsStatus applicable status for existing consents to be updated - * @param newExistingConsentStatus new status that the updated consents should be - * @param isImplicitAuth flag to determine whether authorization is implicit or not - * @return returns DetailedConsentResource - * @throws ConsentManagementException thrown if any error occur in the process - */ - DetailedConsentResource createExclusiveConsent(ConsentResource consentResource, String userID, String authStatus, - String authType, String applicableExistingConsentsStatus, - String newExistingConsentStatus, boolean isImplicitAuth) - throws ConsentManagementException; - - /** - * This method is used to create a consent file. The following functionality contains in this method. - * - * 1. Get the existing consent to validate the status according to the attribute "applicableStatusToFileUpload" - * 2. Create the consent file - * 3. Update the consent status - * 4. Create an audit record for consent update - * - * @param consentFileResource consent file resource - * @param newConsentStatus new consent status - * @param userID user ID (optional) - * @param applicableStatusToFileUpload status that the consent should have to upload a file - * @return true if transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean createConsentFile(ConsentFile consentFileResource, String newConsentStatus, String userID, - String applicableStatusToFileUpload) - throws ConsentManagementException; - - /** - * This method is used to revoke a consent. The following functionality contains in this method. - * - * 1. Get existing consent for status validation - * 2. Update existing consent status - * 3. Create an audit record for consent update - * 4. Update account mapping status as inactive - * - * @param consentID ID of the consent - * @param revokedConsentStatus the status of the consent after revoked - * @return true is the transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean revokeConsent(String consentID, String revokedConsentStatus) - throws ConsentManagementException; - - /** - * This method is used to revoke a consent by adding a revoke reason. - * The following functionality contains in this method. - * - * 1. Get existing consent for status validation - * 2. Update existing consent status - * 3. Create an audit record for consent update - * 4. Update account mapping status as inactive - * - * @param consentID ID of the consent - * @param revokedConsentStatus the status of the consent after revoked - * @param revokedReason the reason for consent revocation - * @return true is the transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String revokedReason) - throws ConsentManagementException; - - /** - * This method is used to revoke a consent. The following functionality contains in this method. - * - * 1. Get existing consent for status validation - * 2. Update existing consent status - * 3. Create an audit record for consent update - * 4. Update account mapping status as inactive - * - * @param consentID ID of the consent - * @param revokedConsentStatus the status of the consent after revoked - * @param userID user ID - * @return true is the transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean revokeConsent(String consentID, String revokedConsentStatus, String userID) - throws ConsentManagementException; - - /** - * This method is used to revoke a consent by adding a revoke reason. - * The following functionality contains in this method. - * - * 1. Get existing consent for status validation - * 2. Update existing consent status - * 3. Create an audit record for consent update - * 4. Update account mapping status as inactive - * - * @param consentID ID of the consent - * @param revokedConsentStatus the status of the consent after revoked - * @param userID user ID - * @param revokedReason the reason for consent revocation - * @return true is the transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, String revokedReason) - throws ConsentManagementException; - - /** - * This method is used to revoke a consent. The following functionality contains in this method. - * - * 1. Get existing consent for status validation - * 2. Update existing consent status - * 3. Create an audit record for consent update - * 4. Update account mapping status as inactive - * 5. Revoke tokens related to the consent if the flag 'shouldRevokeTokens' is true - * - * @param consentID ID of the consent - * @param revokedConsentStatus the status of the consent after revoked - * @param userID user ID - * @param shouldRevokeTokens the check to revoke tokens or not when revoking consent - * @return true is the transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean revokeConsent(String consentID, String revokedConsentStatus, String userID, boolean shouldRevokeTokens) - throws ConsentManagementException; - - /** - * This method is used to revoke a consent. The following functionality contains in this method. - * - * 1. Get existing consent for status validation - * 2. Update existing consent status - * 3. Create an audit record for consent update - * 4. Update account mapping status as inactive - * 5. Revoke tokens related to the consent if the flag 'shouldRevokeTokens' is true - * - * @param consentID ID of the consent - * @param revokedConsentStatus the status of the consent after revoked - * @param userID user ID - * @param shouldRevokeTokens the check to revoke tokens or not when revoking consent - * @param revokedReason the reason for consent revocation - * @return true is the transaction is a success, throws an exception otherwise - * @throws ConsentManagementException thrown if any error occur in the process - */ - boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, - boolean shouldRevokeTokens, String revokedReason) - throws ConsentManagementException; - - /** - * This method is used to revoke existing consents for the given clientID, userID, consent type and status - * combination. Also revokes the tokens related to the consents which are revoked if the flag - * 'shouldRevokeTokens' is true. - * - * @param clientID ID of the client - * @param userID ID of the user - * @param consentType consent type - * @param applicableStatusToRevoke the status that a consent should have for revoking - * @param revokedConsentStatus the status should be updated the consent with after revoking - * @param shouldRevokeTokens the check to revoke tokens or not when revoking consent - * @return returns true if successful - * @throws ConsentManagementException thrown if an error occurs in the process - */ - boolean revokeExistingApplicableConsents(String clientID, String userID, String consentType, - String applicableStatusToRevoke, String revokedConsentStatus, - boolean shouldRevokeTokens) - throws ConsentManagementException; - - /** - * This method is used to get a consent with or without consent attributes. The following functionality contains in - * this method. - * - * 1. Get existing consent for status validation - * 2. Optionally gets consent attributes according to the value of withConsentAttributes flag - * 3. Check whether the retrieved consent involves a file - * - * @param consentID ID of the consent - * @param withConsentAttributes flag to determine the consent should be retrieved with attributes or not - * @return returns ConsentResource - * @throws ConsentManagementException thrown if any error occur in the process - */ - ConsentResource getConsent(String consentID, boolean withConsentAttributes) - throws ConsentManagementException; - - /** - * This method is used to store consent attributes related to a particular consent. - * - * @param consentID consent ID - * @param consentAttributes consent attribute key and values map - * @return a consent attributes resource - * @throws ConsentManagementException thrown if an error occurs in the process - */ - boolean storeConsentAttributes(String consentID, Map consentAttributes) - throws ConsentManagementException; - - /** - * This method is used to get consent attributes for a provided attribute keys list related to a particular consent. - * - * @param consentID consent ID - * @param consentAttributeKeys consent attribute keys list - * @return a consent attributes resource - * @throws ConsentManagementException thrown if an error occurs in the process - */ - ConsentAttributes getConsentAttributes(String consentID, ArrayList consentAttributeKeys) - throws ConsentManagementException; - - /** - * This method is used to get consent attributes related to a particular consent. - * - * @param consentID consent ID - * @return a consent attributes resource - * @throws ConsentManagementException thrown if an error occurs in the process - */ - ConsentAttributes getConsentAttributes(String consentID) throws ConsentManagementException; - - /** - * This method is used to get consent attributes for a provided attribute name. - * - * @param attributeName attribute name - * @return a map with related consent ID and the attribute values - * @throws ConsentManagementException thrown if an error occurs in the process - */ - Map getConsentAttributesByName(String attributeName) throws ConsentManagementException; - - - /** - * This method is used to get consent attributes for a provided attribute name and attribute value. - * - * @param attributeName attribute name - * @param attributeValue attribute value - * @return Consent ID related to the given attribute key and value - * @throws ConsentManagementException thrown if an error occurs in the process - */ - ArrayList getConsentIdByConsentAttributeNameAndValue(String attributeName, String attributeValue) - throws ConsentManagementException; - - /** - * This method is used to delete the provided consent attributes for a particular consent. - * - * @param consentID consen ID - * @param attributeKeysList attributes to delete - * @return true if deletion is successfull - * @throws ConsentManagementException thrown if an error occurs in the process - */ - boolean deleteConsentAttributes(String consentID, ArrayList attributeKeysList) - throws ConsentManagementException; - - /** - * This method is used to retrieve the consent file using the related consent ID. - * - * @param consentID consent ID - * @return the consent file resource - * @throws ConsentManagementException thrown if an error occurs - */ - ConsentFile getConsentFile(String consentID) throws ConsentManagementException; - - /** - * This method is to retrieve an authorization resource using a given authorization ID. - * - * @param authorizationID authorization ID - * @return an authorization resource - * @throws ConsentManagementException thrown if an error occurs in the process - */ - AuthorizationResource getAuthorizationResource(String authorizationID) throws ConsentManagementException; - - /** - * This method is used to search audit records. Useful for auditing purposes. All the input parameters are - * optional. If all parameters are null, all the audit records will be returned. - * - * @param consentID consent ID - * @param status status of the audit records needed - * @param actionBy user who performed the status change - * @param fromTime from time - * @param toTime to time - * @param statusAuditID ID of a specific audit record that need to be searched - * @return a list of consent status audit records - * @throws ConsentManagementException thrown if an error occurs - */ - ArrayList searchConsentStatusAuditRecords(String consentID, String status, - String actionBy, Long fromTime, Long toTime, - String statusAuditID) - throws ConsentManagementException; - - /** - * This method is used in consent re authorization scenarios to update the account mappings according to the - * additional/removed accounts from the new authorization. Also, the consent status is updated with a provided - * status. Also can be used to amend accounts. - * - * @param consentID consent ID - * @param authID authorization ID - * @param userID user ID for creating the audit record - * @param accountIDsMapWithPermissions accounts IDs with relative permissions - * @param currentConsentStatus current status of the consent for creating audit record - * @param newConsentStatus new consent status after re authorization - * @return true if all operations are successful - * @throws ConsentManagementException thrown if any error occurs in the process - */ - boolean reAuthorizeExistingAuthResource(String consentID, String authID, String userID, Map> accountIDsMapWithPermissions, String currentConsentStatus, String newConsentStatus) - throws ConsentManagementException; - - /** - * This method is used in consent re authorization scenarios to update the account mappings according to the - * additional/removed accounts from the new authorization. A new authorization resource will be created when - * re authorizing using this method. Existing authorizations will be updated with a provided status. Also, the - * consent status is updated with a provided status. Also can be used to amend accounts. - * - * @param consentID consent ID - * @param userID user ID - * @param accountIDsMapWithPermissions account IDs with relative permissions - * @param currentConsentStatus current status of the consent for creating audit record - * @param newConsentStatus new consent status after re authorization - * @param newExistingAuthStatus new status of the existing authorizations - * @param newAuthStatus new status of the new authorization - * @param newAuthType new authorization type - * @return true if all operations are successful - * @throws ConsentManagementException thrown if any error occurs in the process - */ - boolean reAuthorizeConsentWithNewAuthResource(String consentID, String userID, Map> accountIDsMapWithPermissions, String currentConsentStatus, String newConsentStatus, - String newExistingAuthStatus, String newAuthStatus, - String newAuthType) - throws ConsentManagementException; - - /** - * This method is used to get a detailed consent for the provided consent ID. The detailed consent includes - * following data if exist in addition to consent resource specific data. - * - * 1. Relative consent authorization data - * 2. Relative consent account mapping data - * 3. Relative consent attributes - * - * @param consentID ID of the consent - * @return a detailed consent resource - * @throws ConsentManagementException thrown if any error occur in the process - */ - DetailedConsentResource getDetailedConsent(String consentID) throws ConsentManagementException; - - /** - * This method is used to create an authorization for a consent. - * - * @param authorizationResource authorization resource - * @return returns AuthorizationResource - * @throws ConsentManagementException thrown if any error occurs in the process - */ - AuthorizationResource createConsentAuthorization(AuthorizationResource authorizationResource) - throws ConsentManagementException; - - /** - * This method is used to create account ID and permission mappings for the relevant authorized user. A map is - * used to represent permissions related to each accountID. - * - * @param authID authorization ID - * @param accountIDsMapWithPermissions account IDs with relative permissions - * @return returns the list of created consent mapping resources - * @throws ConsentManagementException thrown if any error occurs - */ - ArrayList createConsentAccountMappings(String authID, - Map> - accountIDsMapWithPermissions) - throws ConsentManagementException; - - /** - * This method is used to deactivate account bindings of provided account mapping IDs. - * - * @param accountMappingIDs list of account mapping IDs to be deactivated - * @return true is deactivation is a success, false otherwise - * @throws ConsentManagementException thrown if any error occurs - */ - boolean deactivateAccountMappings(ArrayList accountMappingIDs) throws ConsentManagementException; - - /** - * This method is used to update the status of account bindings of provided account mapping IDs. - * - * @param accountMappingIDs list of account mapping IDs to be updated - * @param newMappingStatus new mapping status - * @return true is update is successful, false otherwise - * @throws ConsentManagementException thrown if any error occurs - */ - boolean updateAccountMappingStatus(ArrayList accountMappingIDs, String newMappingStatus) throws - ConsentManagementException; - - /** - * This method is used to update the permissions of the provided account mappings. - * - * @param mappingIDPermissionMap - A map of mapping IDs against new permissions - * @return - true if update is successful - * @throws ConsentManagementException - Thrown if a DAO level error occurs - */ - boolean updateAccountMappingPermission(Map mappingIDPermissionMap) throws - ConsentManagementException; - - /** - * This method is used to search detailed consents for the given lists of parameters. Following optional lists - * can be passed to retrieve detailed consents. The search will be performed according to the provided input. Any - * list can contain any number of elements. The conjunctive result will be returned. If all lists are passed as - * null, all the consents related to other search parameters will be returned. - * - * 1. A list of consent IDs - * 2. A list of client IDs - * 3. A list of consent types - * 4. A list of consent statuses - * 5. A list of user IDs - * - * (All above lists are optional) - * - * @param consentIDs consent IDs optional list - * @param clientIDs client IDs optional list - * @param consentTypes consent types optional list - * @param consentStatuses consent statuses optional list - * @param userIDs user IDs optional list - * @param fromTime from time - * @param toTime to time - * @param limit limit - * @param offset offset - * @return a list of detailed consent resources according to the provided parameters - * @throws ConsentManagementException thrown if any error occur - * @deprecated use {@link #searchDetailedConsents(ArrayList, ArrayList, ArrayList, ArrayList, ArrayList, Long, - * Long, Integer, Integer, boolean)} instead. - */ - @Deprecated - ArrayList searchDetailedConsents(ArrayList consentIDs, ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, Long toTime, - Integer limit, Integer offset) - throws ConsentManagementException; - - - /** - * This method is used to search detailed consents for the given lists of parameters. Following optional lists - * can be passed to retrieve detailed consents. The search will be performed according to the provided input. Any - * list can contain any number of elements. The conjunctive result will be returned. If all lists are passed as - * null, all the consents related to other search parameters will be returned. - * - * 1. A list of consent IDs - * 2. A list of client IDs - * 3. A list of consent types - * 4. A list of consent statuses - * 5. A list of user IDs - * - * (All above lists are optional) - * - * @param consentIDs consent IDs optional list - * @param clientIDs client IDs optional list - * @param consentTypes consent types optional list - * @param consentStatuses consent statuses optional list - * @param userIDs user IDs optional list - * @param fromTime from time - * @param toTime to time - * @param limit limit - * @param offset offset - * @param fetchFromRetentionDatabase flag to enable fetch data from retention database. - * @return a list of detailed consent resources according to the provided parameters - * @throws ConsentManagementException thrown if any error occur - */ - ArrayList searchDetailedConsents(ArrayList consentIDs, ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, Long toTime, - Integer limit, Integer offset, - boolean fetchFromRetentionDatabase) - throws ConsentManagementException; - - /** - * This method is used to bind user and accounts to the consent. - * - * @param consentResource consent resource - * @param userID user ID - * @param authID ID of the authorization resource - * @param accountIDsMapWithPermissions account IDs list with relevant permissions - * @param newAuthStatus new authorization status - * @param newCurrentConsentStatus the new status of the current consent - * @return true if all operations are successful - * @throws ConsentManagementException thrown if an error occurs in the process - */ - boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, String authID, - Map> accountIDsMapWithPermissions, String newAuthStatus, - String newCurrentConsentStatus) throws ConsentManagementException; - - /** - * This method is used to bind user and accounts to the consent where permissions for each account is not relevant. - * - * @param consentResource consent resource - * @param userID user ID - * @param authID ID of the authorization resource - * @param accountIDs account IDs list - * @param newAuthStatus new authorization status - * @param newCurrentConsentStatus the new status of the current consent - * @return true if all operations are successful - * @throws ConsentManagementException thrown if an error occurs in the process - */ - public boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, - String authID, ArrayList accountIDs, - String newAuthStatus, - String newCurrentConsentStatus) - throws ConsentManagementException; - - /** - * This method is used to search authorization resources for a given input parameter. Both consent ID and - * user ID are optional. If both are null, all authorization resources will be returned. - * - * @param consentID consent ID - * @param userID user ID - * @return a list of authorization resources - * @throws ConsentManagementException thrown if any error occurs in the process - */ - ArrayList searchAuthorizations(String consentID, String userID) - throws ConsentManagementException; - - /** - * This method is used to search authorization resources for a given consent ID. - * - * @param consentID consent ID - * @return a list of authorization resources - * @throws ConsentManagementException thrown if any error occurs in the process - */ - ArrayList searchAuthorizations(String consentID) - throws ConsentManagementException; - - /** - * This method is used to search authorization resources for a userId. - * - * @param userID user ID - * @return a list of authorization resources - * @throws ConsentManagementException thrown if any error occurs in the process - */ - ArrayList searchAuthorizationsForUser(String userID) - throws ConsentManagementException; - - /** - * This method is used to amend consent receipt or validity period. The consent ID is mandatory. One of consent - * receipt of validity period must be provided. An audit record is created to indicate that the consent is - * amended. But the consent status won't be changed (since when an authorized consent is amended, the status - * remains the same) - * - * @param consentID consent ID - * @param consentReceipt new consent receipt - * @param consentValidityTime new consent validity time - * @param userID user ID to create audit record - * @return the updated consent resource - * @throws ConsentManagementException thrown if any error occurs in the process - */ - ConsentResource amendConsentData(String consentID, String consentReceipt, Long consentValidityTime, String userID) - throws ConsentManagementException; - - /** - * This method is used to update status of the consent for a given consentId and userId. - * @param consentId consent ID - * @param newConsentStatus new consent status - * @return updated consent resource - * @throws ConsentManagementException thrown if any error occurs in the process - */ - ConsentResource updateConsentStatus(String consentId, String newConsentStatus) - throws ConsentManagementException; - - /** - * This method is used to fetch consents which has a expiring time as a consent attribute - * (eligible for expiration). - * @param statusesEligibleForExpiration statuses eligible for expiration - * @return list of consents eligible for expiration - * @throws ConsentManagementException thrown if any error occurs in the process - */ - ArrayList getConsentsEligibleForExpiration(String statusesEligibleForExpiration) - throws ConsentManagementException; - - /** - * This method is used to update the status of an authorization resource by providing the authorization Id and - * the new authorization status. - * - * @param authorizationId the authorization Id of the authorization resource need to be updated - * @param newAuthorizationStatus the new authorization resource - * @return the updated authorization resource - * @throws ConsentManagementException thrown if any error occur while updating - */ - AuthorizationResource updateAuthorizationStatus(String authorizationId, String newAuthorizationStatus) - throws ConsentManagementException; - - /** - * This method is used to update the user of an authorization resource by providing the authorization ID and - * the user ID. - * - * @param authorizationID the authorization ID of the authorization resource that needs to be updated - * @param userID the user of the authorization resource - * @throws ConsentManagementException thrown if any error occurs while updating - */ - void updateAuthorizationUser(String authorizationID, String userID) - throws ConsentManagementException; - - /** - * This method is used to amend the selected properties of the entire detailed consent. The consent ID is mandatory. - * One of consent receipt or validity period must be provided. - * An audit record is created to indicate that the consent is - * amended. But the consent status won't be changed (since when an authorized consent is amended, the status - * remains the same) - * - * @param consentID consent ID - * @param consentReceipt new consent receipt - * @param consentValidityTime new consent validity time - * @param authID authorization ID - * @param accountIDsMapWithPermissions accounts IDs with relative permissions - * @param newConsentStatus new consent status - * @param consentAttributes new consent attributes key and values map - * @param userID user ID to create audit record - * @param additionalAmendmentData A Data Map to pass any additional data that needs to be amended in the consent - * @return the updated detailed consent resource - * @throws ConsentManagementException thrown if any error occurs in the process - */ - DetailedConsentResource amendDetailedConsent(String consentID, String consentReceipt, Long consentValidityTime, - String authID, Map> accountIDsMapWithPermissions, - String newConsentStatus, Map consentAttributes, String userID, - Map additionalAmendmentData) - throws ConsentManagementException; - - /** - * This method is used to store the details of the previous consent when an consent amendment happens. - * The consent ID is mandatory. The detailed consent resource for the previous consent and the amendedTimestamp - * is mandatory to be set in the ConsentHistoryResource. - * - * @param consentID consent ID - * @param consentHistoryResource detailed consent resource and other history parameters of the previous consent - * @param currentConsentResource detailed consent resource of the current (new) consent - * @return true if all operations are successful - * @throws ConsentManagementException thrown if any error occurs in the process - */ - boolean storeConsentAmendmentHistory(String consentID, ConsentHistoryResource consentHistoryResource, - DetailedConsentResource currentConsentResource) throws ConsentManagementException; - - /** - * This method is used to retrieve consent amendment history for a given consentId. Consent ID is mandatory. - * - * @param consentID consent ID - * @return a map of consent history resources - * @throws ConsentManagementException thrown if any error occurs in the process - */ - Map getConsentAmendmentHistoryData(String consentID) - throws ConsentManagementException; - - /** - * This method is used to sync the retention database with purged consents from consent database. - * @return true if the sync is successful - * @throws ConsentManagementException thrown if any error occurs in the process - */ - boolean syncRetentionDatabaseWithPurgedConsent() throws ConsentManagementException; - - /** - * This method is used to retrieve a list of consent status audit records by consent_id. - * - * @param consentIDs list of consentIDs (optional) - * @param limit limit - * @param offset offset - * @param fetchFromRetentionDatabase boolean value to fetch from retention tables (temporary purged data) - * @return returns a list of consent status audit records. - * @throws ConsentManagementException thrown if a database error occurs - */ - ArrayList getConsentStatusAuditRecords(ArrayList consentIDs, - Integer limit, Integer offset, - boolean fetchFromRetentionDatabase) - throws ConsentManagementException; - - /** - * This method is used to retrieve consent file data by consent_id. - * - * @param consentId consentID - * @param fetchFromRetentionDatabase boolean value to fetch from retention tables (temporary purged data) - * @return returns consent file data by consent_id. - * @throws ConsentManagementException thrown if a database error occurs - */ - ConsentFile getConsentFile(String consentId, boolean fetchFromRetentionDatabase) throws ConsentManagementException; - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/constants/ConsentCoreServiceConstants.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/constants/ConsentCoreServiceConstants.java deleted file mode 100644 index 2ab2b14a..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/constants/ConsentCoreServiceConstants.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.constants; - -/** - * Consent Core Service Constants. - */ -public class ConsentCoreServiceConstants { - - public static final String CONSENT_ATTRIBUTES_DELETE_ERROR_MSG = "Error occurred while deleting consent " + - "attributes in the database"; - public static final String DATA_INSERTION_ROLLBACK_ERROR_MSG = "Error occurred while inserting data. Rolling back" + - " the transaction"; - public static final String DATA_RETRIEVE_ERROR_MSG = "Error occurred while retrieving data"; - public static final String DATA_UPDATE_ROLLBACK_ERROR_MSG = "Error occurred while updating consent data. Rolling " + - "back the transaction"; - public static final String DATA_DELETE_ERROR_MSG = "Error occurred while deleting data"; - public static final String DATA_DELETE_ROLLBACK_ERROR_MSG = "Error occurred while deleting consent data. Rolling " + - "back the transaction"; - public static final String NEW_CONSENT_STATUS_OR_APPLICABLE_STATUS_MISSING_ERROR = "New consent status or " + - "applicable status for file upload is missing. Cannot proceed"; - public static final String CREATE_EXCLUSIVE_CONSENT_MANDATORY_PARAMETER_MISSING_ERROR = "One or more of following" + - " data are missing (Client ID, receipt, consent type, consent status, auth status, auth type, applicable " + - "existing consent status, new existing consent status, new current consent status), cannot proceed"; - - public static final String TRANSACTION_COMMITTED_LOG_MSG = "Transaction committed"; - public static final String DATABASE_CONNECTION_CLOSE_LOG_MSG = "Closing database connection"; - - public static final String CONSENT_REVOKE_FROM_DASHBOARD_REASON = "Revoke the consent from dashboard"; - public static final String CONSENT_REVOKE_REASON = "Revoke the consent"; - public static final String CONSENT_FILE_UPLOAD_REASON = "Upload consent file"; - public static final String CREATE_CONSENT_REASON = "Create consent"; - public static final String CREATE_EXCLUSIVE_AUTHORIZATION_CONSENT_REASON = "Create exclusive authorization consent"; - public static final String USER_ACCOUNTS_BINDING_REASON = "Bind user accounts to consent"; - public static final String CONSENT_REAUTHORIZE_REASON = "Reauthorize consent"; - public static final String CONSENT_AMEND_REASON = "Amend consent"; - public static final String SUBMISSION_RECEIVED_REASON = "Receive submission request for the consent"; - - public static final String ACTIVE_MAPPING_STATUS = "active"; - public static final String INACTIVE_MAPPING_STATUS = "inactive"; - public static final String CONSENT_AMENDED_STATUS = "amended"; - - public static final String CONSENT_RESOURCE = "ConsentResource"; - public static final String DETAILED_CONSENT_RESOURCE = "DetailedConsentResource"; - public static final String CONSENT_AMENDMENT_HISTORY_RESOURCE = "ConsentAmendmentHistory"; - - public static final String ADDITIONAL_AUTHORIZATION_RESOURCES = "AdditionalAuthorizationResources"; - public static final String ADDITIONAL_MAPPING_RESOURCES = "AdditionalMappingResources"; - - public static final String CONSENT_AMENDMENT_TIME = "ConsentAmendmentTime"; - public static final String AMENDMENT_REASON_CONSENT_AMENDMENT_FLOW = "ConsentAmendmentFlow"; - public static final String AMENDMENT_REASON_CONSENT_REVOCATION = "ConsentRevocation"; - public static final String AMENDMENT_REASON_CONSENT_EXPIRATION = "ConsentExpiration"; - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/ConsentCoreServiceImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/ConsentCoreServiceImpl.java deleted file mode 100644 index 0a8f0504..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/ConsentCoreServiceImpl.java +++ /dev/null @@ -1,2848 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.impl; - -import com.google.gson.Gson; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.mgt.dao.ConsentCoreDAO; -import com.wso2.openbanking.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataDeletionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataInsertionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataUpdationException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.persistence.ConsentStoreInitializer; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import com.wso2.openbanking.accelerator.consent.mgt.service.internal.ConsentManagementDataHolder; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.oltu.oauth2.common.message.types.GrantType; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO; -import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; -import org.wso2.carbon.user.core.util.UserCoreUtil; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Savepoint; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -/** - * Consent core service implementation. - */ -public class ConsentCoreServiceImpl implements ConsentCoreService { - - private static final Log log = LogFactory.getLog(ConsentCoreServiceImpl.class); - - @Override - public DetailedConsentResource createAuthorizableConsent(ConsentResource consentResource, String userID, - String authStatus, String authType, - boolean isImplicitAuth) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentResource.getClientID()) || StringUtils.isBlank(consentResource.getReceipt()) || - StringUtils.isBlank(consentResource.getConsentType()) || - StringUtils.isBlank(consentResource.getCurrentStatus())) { - - log.error("Client ID, receipt, consent type or consent status is missing, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since client ID, receipt, consent type or consent " + - "status is missing."); - } - - if (isImplicitAuth) { - if (StringUtils.isBlank(authStatus) || StringUtils.isBlank(authType)) { - log.error("Authorization status and authorization type is not found for implicit " + - "authorization creation"); - throw new ConsentManagementException("Cannot proceed with implicit authorization creation " + - "without Authorization Status and Authorization Type provided"); - } - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - DetailedConsentResource detailedConsentResource = createAuthorizableConesntWithAuditRecord(connection, - consentCoreDAO, consentResource, userID, authStatus, authType, isImplicitAuth); - DatabaseUtil.commitTransaction(connection); - return detailedConsentResource; - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public DetailedConsentResource createExclusiveConsent(ConsentResource consentResource, String userID, - String authStatus, String authType, - String applicableExistingConsentsStatus, - String newExistingConsentStatus, - boolean isImplicitAuth) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentResource.getClientID()) || StringUtils.isBlank(consentResource.getReceipt()) || - StringUtils.isBlank(consentResource.getConsentType()) || - StringUtils.isBlank(consentResource.getCurrentStatus()) || StringUtils.isBlank(userID) - || StringUtils.isBlank(applicableExistingConsentsStatus) - || StringUtils.isBlank(newExistingConsentStatus)) { - - log.error(ConsentCoreServiceConstants.CREATE_EXCLUSIVE_CONSENT_MANDATORY_PARAMETER_MISSING_ERROR); - throw new ConsentManagementException(ConsentCoreServiceConstants - .CREATE_EXCLUSIVE_CONSENT_MANDATORY_PARAMETER_MISSING_ERROR); - } - - if (isImplicitAuth) { - if (StringUtils.isBlank(authStatus) || StringUtils.isBlank(authType)) { - log.error("Authorization status and authorization type is not found for implicit " + - "authorization creation"); - throw new ConsentManagementException("Cannot proceed with implicit authorization creation " + - "without Authorization Status and Authorization Type provided"); - } - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - - // Update existing consent statuses and revoke their account mappings - updateExistingConsentStatusesAndRevokeAccountMappings(connection, consentCoreDAO, consentResource, - userID, applicableExistingConsentsStatus, newExistingConsentStatus); - - // Create a new consent, audit record and authorization resource if allowed - DetailedConsentResource storedDetailedConsentResource = - createAuthorizableConesntWithAuditRecord(connection, consentCoreDAO, consentResource, userID, - authStatus, authType, isImplicitAuth); - - // Commit the transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return storedDetailedConsentResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean createConsentFile(ConsentFile consentFileResource, String newConsentStatus, String userID, - String applicableStatusToFileUpload) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentFileResource.getConsentID()) || - StringUtils.isBlank(consentFileResource.getConsentFile())) { - - log.error("Consent ID or Consent File content is missing. Cannot proceed."); - throw new ConsentManagementException("Cannot proceed without consent ID and file content."); - } - - String consentID = consentFileResource.getConsentID(); - - if (StringUtils.isBlank(newConsentStatus) || StringUtils.isBlank(applicableStatusToFileUpload)) { - log.error(ConsentCoreServiceConstants.NEW_CONSENT_STATUS_OR_APPLICABLE_STATUS_MISSING_ERROR); - throw new ConsentManagementException(ConsentCoreServiceConstants - .NEW_CONSENT_STATUS_OR_APPLICABLE_STATUS_MISSING_ERROR); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Get the existing consent to validate status - if (log.isDebugEnabled()) { - log.debug("Retrieving the consent for ID:" + consentID.replaceAll("[\r\n]", "") + - " to validate status"); - } - ConsentResource existingConsentResource = consentCoreDAO.getConsentResource(connection, consentID); - - String existingConsentStatus = existingConsentResource.getCurrentStatus(); - - // Validate status of the consent - if (!applicableStatusToFileUpload.equalsIgnoreCase(existingConsentResource.getCurrentStatus())) { - log.error("The consent is not in required state to proceed"); - throw new ConsentManagementException("The consent should be in the required state in order to " + - "proceed"); - } - - // Store the consent file - if (log.isDebugEnabled()) { - log.debug("Creating the consent file for the consent of ID:" + - consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.storeConsentFile(connection, consentFileResource); - - // Update consent status with new status - if (log.isDebugEnabled()) { - log.debug("Updating the status of the consent for ID:" + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); - - // Create audit record and execute state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_RESOURCE, existingConsentResource); - postStateChange(connection, consentCoreDAO, consentID, userID, newConsentStatus, - existingConsentStatus, ConsentCoreServiceConstants.CONSENT_FILE_UPLOAD_REASON, - existingConsentResource.getClientID(), consentDataMap); - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean revokeConsent(String consentID, String revokedConsentStatus) - throws ConsentManagementException { - return revokeConsentWithReason(consentID, revokedConsentStatus, null, true, - ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - } - - @Override - public boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String revokedReason) - throws ConsentManagementException { - return revokeConsentWithReason(consentID, revokedConsentStatus, null, true, revokedReason); - } - - @Override - public boolean revokeConsent(String consentID, String revokedConsentStatus, String userID) - throws ConsentManagementException { - return revokeConsentWithReason(consentID, revokedConsentStatus, userID, true, - ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - } - - @Override - public boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, - String revokedReason) - throws ConsentManagementException { - return revokeConsentWithReason(consentID, revokedConsentStatus, userID, true, revokedReason); - } - - @Override - public boolean revokeConsent(String consentID, String revokedConsentStatus, String userID, - boolean shouldRevokeTokens) - throws ConsentManagementException { - return revokeConsentWithReason(consentID, revokedConsentStatus, userID, shouldRevokeTokens, - ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - } - - - @Override - public boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, - boolean shouldRevokeTokens, String revokedReason) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || StringUtils.isBlank(revokedConsentStatus)) { - log.error("Consent ID or new consent status is missing, cannot proceed"); - throw new ConsentManagementException("Consent ID or new consent status is missing, cannot " + - "proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Get existing detailed consent - if (log.isDebugEnabled()) { - log.debug("Retrieving existing consent of ID: " + consentID.replaceAll("[\r\n]", "") + - " for status validation"); - } - DetailedConsentResource retrievedDetailedConsentResource = consentCoreDAO - .getDetailedConsentResource(connection, consentID, false); - String previousConsentStatus = retrievedDetailedConsentResource.getCurrentStatus(); - - // Update consent status as revoked - if (log.isDebugEnabled()) { - log.debug("Updating the status of the consent of ID: " + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateConsentStatus(connection, consentID, revokedConsentStatus); - - if (shouldRevokeTokens) { - // Extract userId from authorizationResources - ArrayList authorizationResources = retrievedDetailedConsentResource - .getAuthorizationResources(); - - // Get all users of the consent - Set consentUserIDSet = new HashSet<>(); - if (authorizationResources != null && !authorizationResources.isEmpty()) { - for (AuthorizationResource authorizationResource : authorizationResources) { - consentUserIDSet.add(authorizationResource.getUserID()); - } - } - - if (consentUserIDSet.isEmpty()) { - log.error("User ID is required for token revocation, cannot proceed"); - throw new ConsentManagementException("User ID is required for token revocation, cannot " + - "proceed"); - } - - if (!isValidUserID(userID, consentUserIDSet)) { - final String errorMsg = "Requested UserID and Consent UserID do not match, cannot proceed."; - log.error(errorMsg + ", request UserID: " + userID.replaceAll("[\r\n]", "") + - " is not a member of the consent user list"); - throw new ConsentManagementException(errorMsg); - } - revokeTokens(retrievedDetailedConsentResource, userID); - } - - ArrayList consentMappingResources = retrievedDetailedConsentResource - .getConsentMappingResources(); - ArrayList mappingIDs = new ArrayList<>(); - - if (!consentMappingResources.isEmpty()) { - for (ConsentMappingResource resource : consentMappingResources) { - mappingIDs.add(resource.getMappingID()); - } - - // Update account mapping status as inactive - if (log.isDebugEnabled()) { - log.debug("Updating the account mappings of consent ID: " + - consentID.replaceAll("[\r\n]", "") + " as inactive"); - } - consentCoreDAO.updateConsentMappingStatus(connection, mappingIDs, - ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); - } - - HashMap consentDataMap = new HashMap<>(); - // Get detailed consent status after the updates - DetailedConsentResource newDetailedConsentResource = - consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, - newDetailedConsentResource); - - // Pass the previous status consent to persist as consent history - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, - retrievedDetailedConsentResource); - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_TIME, System.currentTimeMillis()); - - // Create an audit record execute state change listener - postStateChange(connection, consentCoreDAO, consentID, userID, revokedConsentStatus, - previousConsentStatus, revokedReason, - retrievedDetailedConsentResource.getClientID(), consentDataMap); - - //Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } catch (IdentityOAuth2Exception e) { - log.error("Error while revoking tokens for the consent ID: " - + consentID.replaceAll("[\r\n]", ""), e); - throw new ConsentManagementException("Error occurred while revoking tokens for the consent ID: " - + consentID); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return true; - } - - @Override - public boolean revokeExistingApplicableConsents(String clientID, String userID, String consentType, - String applicableStatusToRevoke, - String revokedConsentStatus, boolean shouldRevokeTokens) - throws ConsentManagementException { - - if (StringUtils.isBlank(clientID) || StringUtils.isBlank(revokedConsentStatus) || StringUtils.isBlank(userID) - || StringUtils.isBlank(applicableStatusToRevoke) || StringUtils.isBlank(consentType)) { - log.error("Client ID, new consent status, consent type, user ID or applicable consent status to revoke is" + - " missing, cannot proceed"); - throw new ConsentManagementException("Client ID, new consent status, consent type, user ID or applicable " + - "consent status to revoke is missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - - ArrayList accountMappingIDsList = new ArrayList<>(); - ArrayList clientIDsList = new ArrayList<>(); - clientIDsList.add(clientID); - ArrayList userIDsList = new ArrayList<>(); - userIDsList.add(userID); - ArrayList consentTypesList = new ArrayList<>(); - consentTypesList.add(consentType); - ArrayList consentStatusesList = new ArrayList<>(); - consentStatusesList.add(applicableStatusToRevoke); - - // Get existing consents - log.debug("Retrieving existing consents"); - - // Only parameters needed for the search are provided, others are made null - ArrayList retrievedDetailedConsentResources = consentCoreDAO - .searchConsents(connection, null, clientIDsList, consentTypesList, - consentStatusesList, userIDsList, null, null, null, null); - - // Revoke existing consents and create audit records - for (DetailedConsentResource resource : retrievedDetailedConsentResources) { - String previousConsentStatus = resource.getCurrentStatus(); - - // Update consent status - if (log.isDebugEnabled()) { - log.debug("Updating consent status for consent ID: " + - resource.getConsentID().replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateConsentStatus(connection, resource.getConsentID(), revokedConsentStatus); - - if (shouldRevokeTokens) { - revokeTokens(resource, userID); - } - - // Create an audit record for consent update - if (log.isDebugEnabled()) { - log.debug("Creating audit record for the status change of consent ID: " - + resource.getConsentID().replaceAll("[\r\n]", "")); - } - // Create an audit record execute state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, resource); - postStateChange(connection, consentCoreDAO, resource.getConsentID(), userID, - revokedConsentStatus, previousConsentStatus, - ConsentCoreServiceConstants.CONSENT_REVOKE_REASON, resource.getClientID(), consentDataMap); - - // Extract account mapping IDs for retrieved applicable consents - if (log.isDebugEnabled()) { - log.debug("Extracting account mapping IDs from consent ID: " + - resource.getConsentID().replaceAll("[\r\n]", "")); - } - for (ConsentMappingResource mappingResource : resource.getConsentMappingResources()) { - accountMappingIDsList.add(mappingResource.getMappingID()); - } - } - - // Update account mappings as inactive - log.debug("Deactivating account mappings"); - if (accountMappingIDsList.size() > 0) { - consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDsList, - ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); - } - //Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } catch (IdentityOAuth2Exception e) { - log.error("Error while revoking tokens for existing consents", e); - throw new ConsentManagementException("Error occurred while revoking tokens for existing consents"); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ConsentResource getConsent(String consentID, boolean withAttributes) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID)) { - log.error("Consent ID is missing, cannot proceed"); - throw new ConsentManagementException("Consent ID is missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - ConsentResource retrievedConsentResource; - - // Get consent attributes if needed - if (!withAttributes) { - if (log.isDebugEnabled()) { - log.debug("Retrieving consent for consent ID: " + consentID.replaceAll("[\r\n]", "")); - } - retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentID); - } else { - if (log.isDebugEnabled()) { - log.debug("Retrieving consent with consent attributes for consent ID: " + - consentID.replaceAll("[\r\n]", "")); - } - retrievedConsentResource = consentCoreDAO.getConsentResourceWithAttributes(connection, consentID); - } - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedConsentResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean storeConsentAttributes(String consentID, Map consentAttributes) - throws ConsentManagementException { - - boolean isConsentAttributesStored; - - if (StringUtils.isBlank(consentID) || consentAttributes == null || consentAttributes.isEmpty()) { - - log.error("consentID or consentAttributes is missing, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since consentID or consentAttributes is missing."); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - ConsentAttributes consentAttributesObject = new ConsentAttributes(); - consentAttributesObject.setConsentID(consentID); - consentAttributesObject.setConsentAttributes(consentAttributes); - - if (log.isDebugEnabled()) { - log.debug("Storing consent attributes for the consent of ID: " + - consentID.replaceAll("[\r\n]", "")); - } - isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributesObject); - DatabaseUtil.commitTransaction(connection); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return isConsentAttributesStored; - - } - - @Override - public ConsentAttributes getConsentAttributes(String consentID, ArrayList consentAttributeKeys) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || CollectionUtils.isEmpty(consentAttributeKeys)) { - log.error("Consent ID or consent attributes keys are missing, cannot proceed"); - throw new ConsentManagementException("Consent ID or consent attribute keys are missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - ConsentAttributes retrievedConsentAttributes; - if (log.isDebugEnabled()) { - log.debug("Retrieving consent attributes for given keys for consent ID: " + - consentID.replaceAll("[\r\n]", "")); - } - retrievedConsentAttributes = consentCoreDAO.getConsentAttributes(connection, consentID, - consentAttributeKeys); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedConsentAttributes; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ConsentAttributes getConsentAttributes(String consentID) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID)) { - log.error("Consent ID is missing, cannot proceed"); - throw new ConsentManagementException("Consent ID is missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - ConsentAttributes retrievedConsentAttributes; - if (log.isDebugEnabled()) { - log.debug("Retrieving consent attributes for consent ID: " + - consentID.replaceAll("[\r\n]", "")); - } - retrievedConsentAttributes = consentCoreDAO.getConsentAttributes(connection, consentID); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedConsentAttributes; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public Map getConsentAttributesByName(String attributeName) throws ConsentManagementException { - - if (StringUtils.isBlank(attributeName)) { - log.error("Attribute name is not provided, cannot proceed"); - throw new ConsentManagementException("Attribute name is not provided, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - Map retrievedAttributeValuesMap; - if (log.isDebugEnabled()) { - log.debug("Retrieving attribute values for the provided attribute key: " + - attributeName.replaceAll("[\r\n]", "")); - } - retrievedAttributeValuesMap = consentCoreDAO.getConsentAttributesByName(connection, attributeName); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedAttributeValuesMap; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ArrayList getConsentIdByConsentAttributeNameAndValue(String attributeName, String attributeValue) - throws ConsentManagementException { - - if (StringUtils.isBlank(attributeName) || StringUtils.isBlank(attributeValue)) { - log.error("Attribute name or value is not provided, cannot proceed"); - throw new ConsentManagementException("Attribute name or value is not provided, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - ArrayList retrievedConsentIdList; - if (log.isDebugEnabled()) { - log.debug("Retrieving consent Id for the provided attribute key : " + - attributeName.replaceAll("[\r\n]", "") + " and " + - "attribute value : " + attributeValue.replaceAll("[\r\n]", "")); - } - retrievedConsentIdList = consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(connection, - attributeName, attributeValue); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedConsentIdList; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean deleteConsentAttributes(String consentID, ArrayList attributeKeysList) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || CollectionUtils.isEmpty(attributeKeysList)) { - log.error("Consent ID or attributes list is not provided, cannot proceed"); - throw new ConsentManagementException("Consent ID or attributes list is not provided, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - if (log.isDebugEnabled()) { - log.debug("Deleting attributes for the consent ID: " + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.deleteConsentAttributes(connection, consentID, attributeKeysList); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataDeletionException e) { - log.error(ConsentCoreServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ConsentFile getConsentFile(String consentID) throws ConsentManagementException { - - if (StringUtils.isBlank(consentID)) { - log.error("Consent ID is missing, cannot proceed"); - throw new ConsentManagementException("Consent ID is missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - ConsentFile retrievedConsentFileResource; - - // Get consent file - if (log.isDebugEnabled()) { - log.debug("Retrieving consent file resource for consent ID: " + - consentID.replaceAll("[\r\n]", "")); - } - retrievedConsentFileResource = consentCoreDAO.getConsentFile(connection, consentID, false); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedConsentFileResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public AuthorizationResource getAuthorizationResource(String authorizationID) throws ConsentManagementException { - - if (StringUtils.isBlank(authorizationID)) { - log.error("Authorization ID is missing, cannot proceed"); - throw new ConsentManagementException("Authorization ID is missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - AuthorizationResource retrievedAuthorizationResource; - - // Get consent file - if (log.isDebugEnabled()) { - log.debug("Retrieving authorization resource for authorization ID: " + - authorizationID.replaceAll("[\r\n]", "")); - } - retrievedAuthorizationResource = consentCoreDAO.getAuthorizationResource(connection, authorizationID); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedAuthorizationResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ArrayList searchConsentStatusAuditRecords(String consentID, String status, - String actionBy, Long fromTime, - Long toTime, String statusAuditID) - throws ConsentManagementException { - - ArrayList auditRecords; - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - - log.debug("Searching audit records"); - auditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, consentID, status, actionBy, - fromTime, toTime, statusAuditID, false); - - } catch (OBConsentDataRetrievalException e) { - log.error("Error occurred while searching audit records"); - throw new ConsentManagementException("Error occurred while searching audit records", e); - } - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return auditRecords; - } - - @Override - public boolean reAuthorizeExistingAuthResource(String consentID, String authID, String userID, - Map> accountIDsMapWithPermissions, - String currentConsentStatus, String newConsentStatus) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || StringUtils.isBlank(authID) || StringUtils.isBlank(userID) - || MapUtils.isEmpty(accountIDsMapWithPermissions) || StringUtils.isBlank(newConsentStatus) - || StringUtils.isBlank(currentConsentStatus)) { - log.error("Consent ID, auth ID, user ID, account permissions map, applicable consent status, new consent " + - "status or current consent status is not present, cannot proceed"); - throw new ConsentManagementException("Consent ID, auth ID, user ID, account permissions map, applicable " + - "consent status, new consent status or current consent status is not present, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - - // Get detailed consent to retrieve account mappings - DetailedConsentResource detailedConsentResource = - consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - - // Update accounts if required - updateAccounts(connection, consentCoreDAO, authID, accountIDsMapWithPermissions, - detailedConsentResource, false); - - // Update consent status - consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); - - // Create an audit record execute state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, detailedConsentResource); - postStateChange(connection, consentCoreDAO, consentID, userID, newConsentStatus, - currentConsentStatus, ConsentCoreServiceConstants.CONSENT_REAUTHORIZE_REASON, - detailedConsentResource.getClientID(), consentDataMap); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean reAuthorizeConsentWithNewAuthResource(String consentID, String userID, Map> accountIDsMapWithPermissions, String currentConsentStatus, String newConsentStatus, - String newExistingAuthStatus, String newAuthStatus, - String newAuthType) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || StringUtils.isBlank(userID) - || MapUtils.isEmpty(accountIDsMapWithPermissions) || StringUtils.isBlank(newConsentStatus) - || StringUtils.isBlank(currentConsentStatus) || StringUtils.isBlank(newExistingAuthStatus) - || StringUtils.isBlank(newAuthStatus) || StringUtils.isBlank(newAuthType)) { - log.error("Consent ID, user ID, account permissions map, current consent status, new consent " + - "status, new existing auth status, new auth status or new auth type is not present, cannot " + - "proceed"); - throw new ConsentManagementException("Consent ID, user ID, account permissions map, current consent " + - "status, new consent status, new existing auth status, new auth status or new auth type is not " + - "present, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - - // Get authorizations related to current consent to revoke - ArrayList authorizationResources = - consentCoreDAO.searchConsentAuthorizations(connection, consentID, userID); - - ArrayList mappingResourcesToDeactivate - = new ArrayList(); - for (AuthorizationResource resource : authorizationResources) { - // Update existing authorizations - consentCoreDAO.updateAuthorizationStatus(connection, resource.getAuthorizationID(), - newExistingAuthStatus); - mappingResourcesToDeactivate.addAll(consentCoreDAO.getConsentMappingResources(connection, - resource.getAuthorizationID())); - } - - // Deactivate account mappings of old auth resource. - ArrayList mappingIdsToDeactivate = new ArrayList<>(); - for (ConsentMappingResource resource : mappingResourcesToDeactivate) { - mappingIdsToDeactivate.add(resource.getMappingID()); - } - consentCoreDAO.updateConsentMappingStatus(connection, mappingIdsToDeactivate, - ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); - - // Create a new authorization resource for the consent - AuthorizationResource newAuthorizationResource = new AuthorizationResource(); - newAuthorizationResource.setConsentID(consentID); - newAuthorizationResource.setAuthorizationType(newAuthType); - newAuthorizationResource.setAuthorizationStatus(newAuthStatus); - newAuthorizationResource.setUserID(userID); - consentCoreDAO.storeAuthorizationResource(connection, newAuthorizationResource); - - // Retrieve the detailed consent for obtaining relative account mappings - DetailedConsentResource detailedConsentResource = - consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - - // Update accounts if required - updateAccounts(connection, consentCoreDAO, newAuthorizationResource.getAuthorizationID(), - accountIDsMapWithPermissions, detailedConsentResource, true); - - // Update consent status - consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); - - // Create an audit record execute state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, detailedConsentResource); - postStateChange(connection, consentCoreDAO, consentID, userID, newConsentStatus, - currentConsentStatus, ConsentCoreServiceConstants.CONSENT_REAUTHORIZE_REASON, - detailedConsentResource.getClientID(), consentDataMap); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public DetailedConsentResource getDetailedConsent(String consentID) throws ConsentManagementException { - - if (StringUtils.isBlank(consentID)) { - log.error("Consent ID is missing, cannot proceed"); - throw new ConsentManagementException("Consent ID is missing, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - DetailedConsentResource retrievedDetailedConsentResource; - - // Retrieve the detailed consent resource - if (log.isDebugEnabled()) { - log.debug("Retrieving detailed consent for consent ID: " + consentID.replaceAll("[\r\n]", "")); - } - retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, consentID, - false); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return retrievedDetailedConsentResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public AuthorizationResource createConsentAuthorization(AuthorizationResource authorizationResource) - throws ConsentManagementException { - - if (StringUtils.isBlank(authorizationResource.getConsentID()) || - StringUtils.isBlank(authorizationResource.getAuthorizationType()) || - StringUtils.isBlank(authorizationResource.getAuthorizationStatus())) { - - log.error("Consent ID, authorization type, user ID or authorization status is missing, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since consent ID, authorization type, user ID or " + - "authorization status is missing"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Create authorization resource - if (log.isDebugEnabled()) { - log.debug("Creating authorization resource for the consent of ID: " + authorizationResource - .getConsentID().replaceAll("[\r\n]", "")); - } - AuthorizationResource storedAuthorizationResource = - consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); - - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return storedAuthorizationResource; - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ArrayList createConsentAccountMappings(String authID, Map> accountIDsMapWithPermissions) throws ConsentManagementException { - - if (StringUtils.isBlank(authID) || MapUtils.isEmpty(accountIDsMapWithPermissions)) { - log.error("Authorization ID, accountID/permission map is not found, cannot " + - "proceed"); - throw new ConsentManagementException("Authorization ID, accountID/permission map " + - "is not found, cannot proceed"); - } - - ArrayList storedConsentMappingResources = new ArrayList<>(); - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Create account mapping resources - if (log.isDebugEnabled()) { - log.debug("Creating consent account mapping resources for authorization ID: " + - authID.replaceAll("[\r\n]", "")); - } - for (Map.Entry> entry : accountIDsMapWithPermissions.entrySet()) { - String accountID = entry.getKey(); - for (String value : entry.getValue()) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAccountID(accountID); - consentMappingResource.setPermission(value); - consentMappingResource.setAuthorizationID(authID); - consentMappingResource.setMappingStatus(ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); - storedConsentMappingResources.add(consentCoreDAO.storeConsentMappingResource(connection, - consentMappingResource)); - } - } - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return storedConsentMappingResources; - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean deactivateAccountMappings(ArrayList accountMappingIDs) throws ConsentManagementException { - - if (accountMappingIDs.isEmpty()) { - log.error("Account mapping IDs are not provided, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since account mapping IDs are not provided"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Deactivate account mapping resources - log.debug("Deactivating consent account mapping resources for given mapping IDs"); - - consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDs, - ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - @Override - public boolean updateAccountMappingStatus(ArrayList accountMappingIDs, String newMappingStatus) throws - ConsentManagementException { - - if (accountMappingIDs.isEmpty()) { - log.error("Account mapping IDs are not provided, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since account mapping IDs are not provided"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // update account mapping resources - log.debug("Deactivating consent account mapping resources for given mapping IDs"); - - consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDs, - newMappingStatus); - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean updateAccountMappingPermission(Map mappingIDPermissionMap) throws - ConsentManagementException { - - if (mappingIDPermissionMap.isEmpty()) { - log.error("Account mapping IDs are not provided, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since account mapping IDs are not provided"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - log.debug("Updating consent account mapping permissions for given mapping IDs"); - consentCoreDAO.updateConsentMappingPermission(connection, mappingIDPermissionMap); - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ArrayList searchDetailedConsents(ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, - Long toTime, - Integer limit, Integer offset) - throws ConsentManagementException { - - // Input parameters except limit and offset are not validated since they are validated in the DAO method - ArrayList detailedConsentResources; - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - - log.debug("Searching detailed consents"); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, clientIDs, - consentTypes, consentStatuses, userIDs, fromTime, toTime, limit, offset); - - } catch (OBConsentDataRetrievalException e) { - log.error("Error occurred while searching detailed consents", e); - throw new ConsentManagementException("Error occurred while searching detailed consents", e); - } - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return detailedConsentResources; - } - - @Override - public ArrayList searchDetailedConsents(ArrayList consentIDs, - ArrayList clientIDs, - ArrayList consentTypes, - ArrayList consentStatuses, - ArrayList userIDs, Long fromTime, - Long toTime, Integer limit, Integer offset, - boolean fetchFromRetentionDatabase) - throws ConsentManagementException { - - // Input parameters except limit and offset are not validated since they are validated in the DAO method - ArrayList detailedConsentResources; - - Connection connection; - if (fetchFromRetentionDatabase) { - connection = DatabaseUtil.getRetentionDBConnection(); - } else { - connection = DatabaseUtil.getDBConnection(); - } - - try { - try { - ConsentCoreDAO consentCoreDAO; - if (fetchFromRetentionDatabase) { - consentCoreDAO = ConsentStoreInitializer.getInitializedConsentRetentionDAOImpl(); - } else { - consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - } - - log.debug("Searching detailed consents"); - detailedConsentResources = consentCoreDAO.searchConsents(connection, consentIDs, clientIDs, - consentTypes, consentStatuses, userIDs, fromTime, toTime, limit, offset); - - } catch (OBConsentDataRetrievalException e) { - log.error("Error occurred while searching detailed consents", e); - throw new ConsentManagementException("Error occurred while searching detailed consents", e); - } - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return detailedConsentResources; - } - - @Override - public boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, - String authID, ArrayList accountIDs, - String newAuthStatus, - String newCurrentConsentStatus) - throws ConsentManagementException { - - Map> accountIDsMapWithPermissions = new HashMap<>(); - ArrayList permissionsDefault = new ArrayList<>(); - permissionsDefault.add("n/a"); - - for (String accountId : accountIDs) { - accountIDsMapWithPermissions.put(accountId, permissionsDefault); - } - - return bindUserAccountsToConsent(consentResource, userID, authID, accountIDsMapWithPermissions, newAuthStatus, - newCurrentConsentStatus); - } - - @Override - public boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, - String authID, Map> accountIDsMapWithPermissions, - String newAuthStatus, - String newCurrentConsentStatus) - throws ConsentManagementException { - - String consentID = consentResource.getConsentID(); - String clientID = consentResource.getClientID(); - String consentType = consentResource.getConsentType(); - - if (StringUtils.isBlank(consentID) || StringUtils.isBlank(clientID) || StringUtils.isBlank(consentType) - || StringUtils.isBlank(userID) || StringUtils.isBlank(authID) || StringUtils.isBlank(newAuthStatus) - || StringUtils.isBlank(newCurrentConsentStatus)) { - log.error("Consent ID, client ID, consent type, user ID, authorization ID, new authorization status or " + - "new consent status is " + - "missing, cannot proceed."); - throw new ConsentManagementException("Consent ID, client ID, consent type, user ID, authorization ID, new" + - " authorization status or new consent status is missing, " + - "cannot proceed"); - } - - if (MapUtils.isEmpty(accountIDsMapWithPermissions)) { - log.error("Account IDs and relative permissions are not present, cannot proceed"); - throw new ConsentManagementException("Account IDs and relative permissions are not present, cannot " + - "proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - - // Update authorization resource of current consent - if (log.isDebugEnabled()) { - log.debug("Update authorization status and authorization user for current consent ID: " - + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateAuthorizationUser(connection, authID, userID); - consentCoreDAO.updateAuthorizationStatus(connection, authID, newAuthStatus); - - // Create account mappings for current consent - if (log.isDebugEnabled()) { - log.debug("Creating account mappings for current consent ID: " + - consentID.replaceAll("[\r\n]", "")); - } - for (Map.Entry> entry : accountIDsMapWithPermissions.entrySet()) { - String accountID = entry.getKey(); - for (String value : entry.getValue()) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAccountID(accountID); - consentMappingResource.setPermission(value); - consentMappingResource.setAuthorizationID(authID); - consentMappingResource.setMappingStatus(ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); - consentCoreDAO.storeConsentMappingResource(connection, consentMappingResource); - } - } - - // Update current consent status - if (log.isDebugEnabled()) { - log.debug("Update the status of the current consent ID: " + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateConsentStatus(connection, consentID, newCurrentConsentStatus); - - // Create audit record for the consent status update and execute the state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_RESOURCE, consentResource); - postStateChange(connection, consentCoreDAO, consentID, userID, newCurrentConsentStatus, - consentResource.getCurrentStatus(), ConsentCoreServiceConstants.USER_ACCOUNTS_BINDING_REASON, - clientID, consentDataMap); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ArrayList searchAuthorizations(String consentID) - throws ConsentManagementException { - return searchAuthorizations(consentID, null); - } - - @Override - public ArrayList searchAuthorizationsForUser(String userID) - throws ConsentManagementException { - return searchAuthorizations(null, userID); - } - - @Override - public ArrayList searchAuthorizations(String consentID, String userID) - throws ConsentManagementException { - - ArrayList authorizationResources; - Connection connection = DatabaseUtil.getDBConnection(); - - try { - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - - log.debug("Searching authorization resources"); - authorizationResources = consentCoreDAO.searchConsentAuthorizations(connection, consentID, userID); - - } catch (OBConsentDataRetrievalException e) { - log.error("Error occurred while searching authorization resources", e); - throw new ConsentManagementException("Error occurred while searching authorization resources", e); - } - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return authorizationResources; - } - - private void createAuditRecord(Connection connection, ConsentCoreDAO consentCoreDAO, String consentID, - String userID, String newConsentStatus, String previousConsentStatus, String reason) - throws OBConsentDataInsertionException { - - // Create an audit record - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(consentID); - consentStatusAuditRecord.setCurrentStatus(newConsentStatus); - consentStatusAuditRecord.setReason(reason); - if (StringUtils.isNotEmpty(userID)) { - consentStatusAuditRecord.setActionBy(userID); - } else { - consentStatusAuditRecord.setActionBy(null); - } - consentStatusAuditRecord.setPreviousStatus(previousConsentStatus); - - if (log.isDebugEnabled()) { - log.debug(("Storing audit record for consent of ID: " + - consentStatusAuditRecord.getConsentID()).replaceAll("[\r\n]", "")); - } - consentCoreDAO.storeConsentStatusAuditRecord(connection, consentStatusAuditRecord); - } - - private DetailedConsentResource createAuthorizableConesntWithAuditRecord(Connection connection, - ConsentCoreDAO consentCoreDAO, - ConsentResource consentResource, - String userID, String authStatus, - String authType, - boolean isImplicitAuthorization) - throws OBConsentDataInsertionException, ConsentManagementException { - - boolean isConsentAttributesStored = false; - AuthorizationResource storedAuthorizationResource = null; - - // Create consent - if (log.isDebugEnabled()) { - log.debug(("Creating the consent for ID:" + consentResource.getConsentID()).replaceAll("[\r\n]", "")); - } - ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, - consentResource); - String consentID = storedConsentResource.getConsentID(); - - // Store consent attributes if available - if (MapUtils.isNotEmpty(consentResource.getConsentAttributes())) { - ConsentAttributes consentAttributes = new ConsentAttributes(); - consentAttributes.setConsentID(consentID); - consentAttributes.setConsentAttributes(consentResource.getConsentAttributes()); - - if (log.isDebugEnabled()) { - log.debug("Storing consent attributes for the consent of ID: " + consentAttributes - .getConsentID().replaceAll("[\r\n]", "")); - } - isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributes); - } - - /* Create audit record, setting previous consent status as null since this is the first time the - consent is created and execute state change listener */ - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_RESOURCE, consentResource); - postStateChange(connection, consentCoreDAO, consentID, userID, consentResource.getCurrentStatus(), - null, ConsentCoreServiceConstants.CREATE_CONSENT_REASON, - consentResource.getClientID(), consentDataMap); - - // Create an authorization resource if isImplicitAuth parameter is true - if (isImplicitAuthorization) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(consentID); - authorizationResource.setAuthorizationStatus(authStatus); - authorizationResource.setAuthorizationType(authType); - if (StringUtils.isNotBlank(userID)) { - authorizationResource.setUserID(userID); - } else { - /* Setting userID as null since at this point, there is no userID in this flow. User ID can be - updated in authorization flow */ - authorizationResource.setUserID(null); - } - - if (log.isDebugEnabled()) { - log.debug(("Storing authorization resource for consent of ID: " + authorizationResource - .getConsentID()).replaceAll("[\r\n]", "")); - } - - storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, - authorizationResource); - } - - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - detailedConsentResource.setConsentID(consentID); - detailedConsentResource.setClientID(storedConsentResource.getClientID()); - detailedConsentResource.setReceipt(storedConsentResource.getReceipt()); - detailedConsentResource.setConsentType(storedConsentResource.getConsentType()); - detailedConsentResource.setCurrentStatus(storedConsentResource.getCurrentStatus()); - detailedConsentResource.setConsentFrequency(storedConsentResource.getConsentFrequency()); - detailedConsentResource.setValidityPeriod(storedConsentResource.getValidityPeriod()); - detailedConsentResource.setCreatedTime(storedConsentResource.getCreatedTime()); - detailedConsentResource.setRecurringIndicator(storedConsentResource.isRecurringIndicator()); - detailedConsentResource.setUpdatedTime(storedConsentResource.getUpdatedTime()); - - if (isConsentAttributesStored) { - detailedConsentResource.setConsentAttributes(consentResource.getConsentAttributes()); - } - if (isImplicitAuthorization) { - ArrayList authorizationResources = new ArrayList<>(); - authorizationResources.add(storedAuthorizationResource); - detailedConsentResource.setAuthorizationResources(authorizationResources); - } - return detailedConsentResource; - } - - private void updateExistingConsentStatusesAndRevokeAccountMappings(Connection connection, - ConsentCoreDAO consentCoreDAO, - ConsentResource consentResource, String userID, - String applicableExistingConsentsStatus, - String newExistingConsentStatus) - throws OBConsentDataRetrievalException, OBConsentDataUpdationException, OBConsentDataInsertionException, - ConsentManagementException { - - ArrayList accountMappingIDsList = new ArrayList<>(); - ArrayList clientIDsList = new ArrayList<>(); - clientIDsList.add(consentResource.getClientID()); - ArrayList userIDsList = new ArrayList<>(); - userIDsList.add(userID); - ArrayList consentTypesList = new ArrayList<>(); - consentTypesList.add(consentResource.getConsentType()); - ArrayList consentStatusesList = new ArrayList<>(); - consentStatusesList.add(applicableExistingConsentsStatus); - - // Get existing applicable consents - log.debug("Retrieving existing authorized consents"); - ArrayList retrievedExistingAuthorizedConsentsList = - consentCoreDAO.searchConsents(connection, null, clientIDsList, consentTypesList, - consentStatusesList, userIDsList, null, null, null, - null); - - for (DetailedConsentResource resource : retrievedExistingAuthorizedConsentsList) { - - String previousConsentStatus = resource.getCurrentStatus(); - - // Update existing consents as necessary - if (log.isDebugEnabled()) { - log.debug(("Updating existing consent statuses with the new status provided for consent ID: " - + resource.getConsentID()).replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateConsentStatus(connection, resource.getConsentID(), - newExistingConsentStatus); - - // Create audit record for each consent update - if (log.isDebugEnabled()) { - log.debug(("Creating audit record for the consent update of consent ID: " - + resource.getConsentID()).replaceAll("[\r\n]", "")); - } - // Create an audit record execute state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, resource); - postStateChange(connection, consentCoreDAO, resource.getConsentID(), userID, - newExistingConsentStatus, previousConsentStatus, - ConsentCoreServiceConstants.CREATE_EXCLUSIVE_AUTHORIZATION_CONSENT_REASON, resource.getClientID(), - consentDataMap); - - // Extract account mapping IDs for retrieved applicable consents - if (log.isDebugEnabled()) { - log.debug(("Extracting account mapping IDs from consent ID: " + - resource.getConsentID()).replaceAll("[\r\n]", "")); - } - for (ConsentMappingResource mappingResource : resource.getConsentMappingResources()) { - accountMappingIDsList.add(mappingResource.getMappingID()); - } - } - - // Update account mappings as inactive - log.debug("Deactivating account mappings"); - consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDsList, - ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); - } - - private void updateAccounts(Connection connection, - ConsentCoreDAO consentCoreDAO, String authID, - Map> accountIDsMapWithPermissions, - DetailedConsentResource detailedConsentResource, boolean isNewAuthResource) - throws OBConsentDataInsertionException, OBConsentDataUpdationException { - - // Get existing consent account mappings - log.debug("Retrieve existing active account mappings"); - ArrayList existingAccountMappings = - detailedConsentResource.getConsentMappingResources(); - - // Determine unique account IDs - HashSet existingAccountIDs = new HashSet<>(); - for (ConsentMappingResource resource : existingAccountMappings) { - existingAccountIDs.add(resource.getAccountID()); - } - - ArrayList existingAccountIDsList = new ArrayList<>(existingAccountIDs); - - ArrayList reAuthorizedAccounts = new ArrayList<>(); - for (Map.Entry> entry : accountIDsMapWithPermissions.entrySet()) { - String accountID = entry.getKey(); - reAuthorizedAccounts.add(accountID); - } - - // Determine whether the account should be removed or added - ArrayList accountsToRevoke = new ArrayList<>(existingAccountIDsList); - accountsToRevoke.removeAll(reAuthorizedAccounts); - - ArrayList accountsToAdd = new ArrayList<>(reAuthorizedAccounts); - - if (isNewAuthResource) { - ArrayList commonAccountsFromReAuth = new ArrayList<>(existingAccountIDs); - commonAccountsFromReAuth.retainAll(accountsToAdd); - accountsToAdd.removeAll(existingAccountIDs); - accountsToAdd.addAll(commonAccountsFromReAuth); - } else { - accountsToAdd.removeAll(existingAccountIDs); - } - - if (!accountsToAdd.isEmpty()) { - // Store accounts as consent account mappings - log.debug("Add extra accounts as account mappings"); - for (String accountID : accountsToAdd) { - ArrayList permissions = accountIDsMapWithPermissions.get(accountID); - for (String permission : permissions) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(authID); - consentMappingResource.setAccountID(accountID); - consentMappingResource.setPermission(permission); - consentMappingResource.setMappingStatus(ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); - consentCoreDAO.storeConsentMappingResource(connection, consentMappingResource); - } - } - } - if (!accountsToRevoke.isEmpty()) { - // Update mapping statuses of revoking accounts to inactive - log.debug("Deactivate unwanted account mappings"); - ArrayList mappingIDsToUpdate = new ArrayList<>(); - for (String accountID : accountsToRevoke) { - for (ConsentMappingResource resource : existingAccountMappings) { - if (accountID.equalsIgnoreCase(resource.getAccountID())) { - mappingIDsToUpdate.add(resource.getMappingID()); - } - } - } - consentCoreDAO.updateConsentMappingStatus(connection, mappingIDsToUpdate, - ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); - } - } - - @Override - public ConsentResource amendConsentData(String consentID, String consentReceipt, Long consentValidityTime, - String userID) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || - (StringUtils.isBlank(consentReceipt) && (consentValidityTime == null))) { - log.error("Consent ID or both consent receipt and consent validity period are not provided, cannot " + - "proceed"); - throw new ConsentManagementException("Consent ID or both consent receipt and consent validity period are " + - "not provided, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Update receipt and validity time accordingly - if (StringUtils.isNotBlank(consentReceipt) && (consentValidityTime != null)) { - // update receipt - consentCoreDAO.updateConsentReceipt(connection, consentID, consentReceipt); - // update validity period - consentCoreDAO.updateConsentValidityTime(connection, consentID, consentValidityTime); - } else { - if (StringUtils.isBlank(consentReceipt) && (consentValidityTime != null)) { - // update receipt - consentCoreDAO.updateConsentValidityTime(connection, consentID, consentValidityTime); - } else { - // update receipt - consentCoreDAO.updateConsentReceipt(connection, consentID, consentReceipt); - } - } - - // Get consent after update - ConsentResource consentResource = consentCoreDAO.getConsentResource(connection, consentID); - - /* Even if the consent is amended, the status remains same as Authorized. For tracking purposes, an - audit record is created as the consent status of "amended". But still the real consent status will - remain as it is */ - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_RESOURCE, consentResource); - postStateChange(connection, consentCoreDAO, consentID, userID, - ConsentCoreServiceConstants.CONSENT_AMENDED_STATUS, consentResource.getCurrentStatus(), - ConsentCoreServiceConstants.CONSENT_AMEND_REASON, consentResource.getClientID(), - consentDataMap); - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return consentResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - public DetailedConsentResource amendDetailedConsent(String consentID, String consentReceipt, - Long consentValidityTime, String authID, - Map> accountIDsMapWithPermissions, - String newConsentStatus, Map consentAttributes, String userID, - Map additionalAmendmentData) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || - (StringUtils.isBlank(consentReceipt) && (consentValidityTime == null))) { - log.error("Consent ID or both consent receipt and consent validity period are not provided, cannot " + - "proceed"); - throw new ConsentManagementException("Consent ID or both consent receipt and consent validity period are " + - "not provided, cannot proceed"); - } - - if (StringUtils.isBlank(authID) || StringUtils.isBlank(userID) - || MapUtils.isEmpty(accountIDsMapWithPermissions) || StringUtils.isBlank(newConsentStatus) - || consentAttributes == null) { - log.error("Auth ID, user ID, account permissions map, new consent status or new consent attributes " + - "is not present, cannot proceed"); - throw new ConsentManagementException("Auth ID, user ID, account permissions map, new consent status or " + - "new consent attributes is not present, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - // Retrieve the current detailed consent before the amendment for the consent amendment history persistence - DetailedConsentResource detailedConsentResource = - consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - - // Update receipt and validity time - if (StringUtils.isNotBlank(consentReceipt)) { - consentCoreDAO.updateConsentReceipt(connection, consentID, consentReceipt); - } - if (consentValidityTime != null) { - consentCoreDAO.updateConsentValidityTime(connection, consentID, consentValidityTime); - } - - // Update consent status and record the updated time - consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); - - // Update accounts if required - updateAccounts(connection, consentCoreDAO, authID, accountIDsMapWithPermissions, - detailedConsentResource, false); - - // Update consent attributes - updateConsentAttributes(connection, consentCoreDAO, consentID, consentAttributes); - - // Update consent accordingly if additional amendment data passed - if (!additionalAmendmentData.isEmpty()) { - processAdditionalConsentAmendmentData(connection, consentCoreDAO, additionalAmendmentData); - } - - // Get detailed consent status after update - DetailedConsentResource newDetailedConsentResource = - consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - - /* Even if the consent is amended, the status remains same as Authorized. For tracking purposes, an - audit record is created as the consent status of "amended". But still the real consent status will - remain as it is */ - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, newDetailedConsentResource); - - // Pass the previous consent to persist as consent amendment history - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, detailedConsentResource); - consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_TIME, System.currentTimeMillis()); - - postStateChange(connection, consentCoreDAO, consentID, userID, - ConsentCoreServiceConstants.CONSENT_AMENDED_STATUS, detailedConsentResource.getCurrentStatus(), - ConsentCoreServiceConstants.CONSENT_AMEND_REASON, detailedConsentResource.getClientID(), - consentDataMap); - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return newDetailedConsentResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataDeletionException e) { - log.error(ConsentCoreServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - private void updateConsentAttributes(Connection connection, ConsentCoreDAO consentCoreDAO, - String consentID, Map consentAttributes) - throws OBConsentDataDeletionException, OBConsentDataInsertionException { - - // delete existing consent attributes - if (log.isDebugEnabled()) { - log.debug("Deleting attributes for the consent ID: " + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.deleteConsentAttributes(connection, consentID, - new ArrayList<>(consentAttributes.keySet())); - - // store new set of consent attributes - ConsentAttributes consentAttributesObject = new ConsentAttributes(); - consentAttributesObject.setConsentID(consentID); - consentAttributesObject.setConsentAttributes(consentAttributes); - if (log.isDebugEnabled()) { - log.debug("Storing consent attributes for the consent of ID: " + consentID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.storeConsentAttributes(connection, consentAttributesObject); - } - - private void processAdditionalConsentAmendmentData(Connection connection, ConsentCoreDAO consentCoreDAO, - Map additionalAmendmentData) - throws ConsentManagementException, OBConsentDataInsertionException { - - Map newAuthResources; - Map> newMappingResources; - - if (additionalAmendmentData.containsKey(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES) && - additionalAmendmentData.containsKey(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES)) { - - newAuthResources = (Map) additionalAmendmentData - .get(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES); - newMappingResources = (Map>) additionalAmendmentData - .get(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES); - - for (Map.Entry authResourceEntry : newAuthResources.entrySet()) { - String userId = authResourceEntry.getKey(); - AuthorizationResource authResource = authResourceEntry.getValue(); - - if (StringUtils.isBlank(authResource.getConsentID()) || - StringUtils.isBlank(authResource.getAuthorizationType()) || - StringUtils.isBlank(authResource.getAuthorizationStatus())) { - log.error("Consent ID, authorization type or authorization status is missing, cannot proceed"); - throw new ConsentManagementException("Cannot proceed since consent ID, authorization type or " + - "authorization status is missing"); - } - // create authorization resource - AuthorizationResource authorizationResource = - consentCoreDAO.storeAuthorizationResource(connection, authResource); - ArrayList mappingResources = newMappingResources.get(userId); - - for (ConsentMappingResource mappingResource : mappingResources) { - - if (StringUtils.isBlank(mappingResource.getAccountID()) || - StringUtils.isBlank(mappingResource.getMappingStatus())) { - log.error("Account ID or Mapping Status is not found, cannot proceed"); - throw new ConsentManagementException("Account ID or Mapping Status is not found, " + - "cannot proceed"); - } - mappingResource.setAuthorizationID(authorizationResource.getAuthorizationID()); - // create mapping resource - consentCoreDAO.storeConsentMappingResource(connection, mappingResource); - } - } - } - } - - @Override - public boolean storeConsentAmendmentHistory(String consentID, ConsentHistoryResource consentHistoryResource, - DetailedConsentResource detailedCurrentConsent) throws ConsentManagementException { - - if (StringUtils.isBlank(consentID) || consentHistoryResource == null || - StringUtils.isBlank(consentHistoryResource.getReason()) || consentHistoryResource.getTimestamp() == 0) { - log.error("Consent ID or detailed consent resource or amendment reason or amended timestamp " + - "in consent history resource is empty/zero"); - throw new ConsentManagementException("Consent ID or detailed consent resource or amendment reason or " + - "amended timestamp in consent resource history is empty/zero, cannot proceed"); - } - - String historyID = consentHistoryResource.getHistoryID(); - if (StringUtils.isBlank(historyID)) { - historyID = String.valueOf(UUID.randomUUID()); - } - long amendedTimestamp = consentHistoryResource.getTimestamp(); - String amendmentReason = consentHistoryResource.getReason(); - - Connection connection = DatabaseUtil.getDBConnection(); - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - if (detailedCurrentConsent == null) { - detailedCurrentConsent = consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - } - - DetailedConsentResource detailedHistoryConsent = consentHistoryResource.getDetailedConsentResource(); - // store only the changes in basic consent data to CA history - JSONObject changedConsentDataJson = getChangedBasicConsentDataJSON(detailedCurrentConsent, - detailedHistoryConsent); - if (!changedConsentDataJson.isEmpty()) { - consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, consentID, - ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, String.valueOf(changedConsentDataJson), - amendmentReason); - } - - // store only the changes in consent attributes to CA history - JSONObject changedConsentAttributesJson = getChangedConsentAttributesDataJSON( - detailedCurrentConsent.getConsentAttributes(), detailedHistoryConsent.getConsentAttributes()); - if (!changedConsentAttributesJson.isEmpty()) { - consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, - consentID, ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, - String.valueOf(changedConsentAttributesJson), amendmentReason); - } - - // store only the changes in consent mappings to CA history - Map changedConsentMappingsJsonDataMap = - getChangedConsentMappingDataJSONMap(detailedCurrentConsent.getConsentMappingResources(), - detailedHistoryConsent.getConsentMappingResources()); - for (Map.Entry changedConsentMapping : changedConsentMappingsJsonDataMap.entrySet()) { - consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, - changedConsentMapping.getKey(), ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, - String.valueOf(changedConsentMapping.getValue()), amendmentReason); - } - - // store only the changes in consent Auth Resources to CA history - Map changedConsentAuthResourcesJsonDataMap = - getChangedConsentAuthResourcesDataJSONMap(detailedCurrentConsent.getAuthorizationResources(), - detailedHistoryConsent.getAuthorizationResources()); - for (Map.Entry changedConsentAuthResource : - changedConsentAuthResourcesJsonDataMap.entrySet()) { - consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, - changedConsentAuthResource.getKey(), ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, - String.valueOf(changedConsentAuthResource.getValue()), amendmentReason); - } - - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return true; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - private JSONObject getChangedBasicConsentDataJSON(DetailedConsentResource newConsentResource, - DetailedConsentResource oldConsentResource) { - - JSONObject changedConsentDataJson = new JSONObject(); - if (!newConsentResource.getReceipt().equalsIgnoreCase(oldConsentResource.getReceipt())) { - changedConsentDataJson.put(ConsentMgtDAOConstants.RECEIPT, oldConsentResource.getReceipt()); - } - if (newConsentResource.getValidityPeriod() != oldConsentResource.getValidityPeriod()) { - changedConsentDataJson.put(ConsentMgtDAOConstants.VALIDITY_TIME, - String.valueOf(oldConsentResource.getValidityPeriod())); - } - if (newConsentResource.getUpdatedTime() != oldConsentResource.getUpdatedTime()) { - changedConsentDataJson.put(ConsentMgtDAOConstants.UPDATED_TIME, - String.valueOf(oldConsentResource.getUpdatedTime())); - } - if (!newConsentResource.getCurrentStatus().equalsIgnoreCase(oldConsentResource.getCurrentStatus())) { - changedConsentDataJson.put(ConsentMgtDAOConstants.CURRENT_STATUS, - String.valueOf(oldConsentResource.getCurrentStatus())); - } - return changedConsentDataJson; - } - - private JSONObject getChangedConsentAttributesDataJSON(Map newConsentAttributes, - Map oldConsentAttributes) { - - JSONObject changedConsentAttributesJson = new JSONObject(); - for (Map.Entry consentAttribute : oldConsentAttributes.entrySet()) { - String attributeKey = consentAttribute.getKey(); - if (!newConsentAttributes.containsKey(attributeKey) - || !newConsentAttributes.get(attributeKey).equalsIgnoreCase(consentAttribute.getValue())) { - //store only the consent attributes with a changed value to the consent amendment history - changedConsentAttributesJson.put(attributeKey, consentAttribute.getValue()); - } - } - for (Map.Entry newConsentAttribute : newConsentAttributes.entrySet()) { - String attributeKey = newConsentAttribute.getKey(); - if (!oldConsentAttributes.containsKey(newConsentAttribute.getKey())) { - //store any new consent attribute in current consent to the changedConsentAttributesJson of - //the immediate past consent amendment history with a null value - changedConsentAttributesJson.put(attributeKey, null); - } - } - return changedConsentAttributesJson; - } - - private Map getChangedConsentMappingDataJSONMap(ArrayList - newConsentMappings, ArrayList oldConsentMappings) { - - Map changedConsentMappingsJsonDataMap = new HashMap<>(); - ArrayList existingConsentMappingIds = new ArrayList<>(); - for (ConsentMappingResource newMapping : newConsentMappings) { - JSONObject changedConsentMappingJson = new JSONObject(); - for (ConsentMappingResource oldMapping : oldConsentMappings) { - if (newMapping.getMappingID().equalsIgnoreCase(oldMapping.getMappingID())) { - existingConsentMappingIds.add(newMapping.getMappingID()); - if (!newMapping.getMappingStatus().equalsIgnoreCase(oldMapping.getMappingStatus())) { - //store only the mapping-ids with a changed Mapping Status to the consent amendment history - changedConsentMappingJson.put(ConsentMgtDAOConstants.MAPPING_STATUS, - oldMapping.getMappingStatus()); - } - break; - } - } - if (!changedConsentMappingJson.isEmpty()) { - changedConsentMappingsJsonDataMap.put(newMapping.getMappingID(), changedConsentMappingJson); - } - // store any new mapping-ids in current consent to the immediate past consent amendment history with - // 'null' value - if (!existingConsentMappingIds.contains(newMapping.getMappingID())) { - changedConsentMappingsJsonDataMap.put(newMapping.getMappingID(), null); - } - } - return changedConsentMappingsJsonDataMap; - } - - private Map getChangedConsentAuthResourcesDataJSONMap(ArrayList - newConsentAuthResources, ArrayList oldConsentAuthResources) { - - Map changedConsentAuthResourcesJsonDataMap = new HashMap<>(); - - ArrayList existingConsentAuthResourceIds = new ArrayList<>(); - for (AuthorizationResource newAuthResource : newConsentAuthResources) { - for (AuthorizationResource oldAuthResource : oldConsentAuthResources) { - if (newAuthResource.getAuthorizationID().equalsIgnoreCase(oldAuthResource.getAuthorizationID())) { - existingConsentAuthResourceIds.add(newAuthResource.getAuthorizationID()); - break; - } - } - // store any new authorization-ids in current consent (an Auth Resource not available in previous consent, - // but newly added in current consent) to the immediate past consent amendment history with 'null' value - if (!existingConsentAuthResourceIds.contains(newAuthResource.getAuthorizationID())) { - changedConsentAuthResourcesJsonDataMap.put(newAuthResource.getAuthorizationID(), null); - } - } - return changedConsentAuthResourcesJsonDataMap; - } - - @Override - public Map getConsentAmendmentHistoryData(String consentID) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentID)) { - log.error("Consent ID is empty"); - throw new ConsentManagementException("Consent ID is empty, cannot proceed"); - } - - Connection connection = DatabaseUtil.getDBConnection(); - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - //Retrieve the current detailed consent to build the detailed consent amendment history resources - DetailedConsentResource currentConsentResource = - consentCoreDAO.getDetailedConsentResource(connection, consentID, false); - - Map consentAmendmentHistoryRetrievalResult = - consentCoreDAO.retrieveConsentAmendmentHistory(connection, - getRecordIdListForConsentHistoryRetrieval(currentConsentResource)); - - Map consentAmendmentHistory = new LinkedHashMap<>(); - if (!consentAmendmentHistoryRetrievalResult.isEmpty()) { - consentAmendmentHistory = processConsentAmendmentHistoryData( - consentAmendmentHistoryRetrievalResult, currentConsentResource); - } - DatabaseUtil.commitTransaction(connection); - return consentAmendmentHistory; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean syncRetentionDatabaseWithPurgedConsent() throws ConsentManagementException { - - if (!OpenBankingConfigParser.getInstance().isConsentDataRetentionEnabled()) { - log.error("Consent data retention is not enabled, Hence data sync is not possible at the moment"); - throw new ConsentManagementException("Consent data retention is not enabled, " + - "Hence data sync is not possible at the moment"); - } - - Connection consentDBConnection = DatabaseUtil.getDBConnection(); - Connection retentionDBConnection = DatabaseUtil.getRetentionDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - ConsentCoreDAO consentRetentionDAO = ConsentStoreInitializer.getInitializedConsentRetentionDAOImpl(); - - // Fetch list of consent_id's to sync from temporary retention tables in consent DB. - ArrayList listOfConsentIds = consentCoreDAO.getListOfConsentIds(consentDBConnection, true); - - // Fetch consent data from temporary retention tables in consent DB. - log.debug("Fetching consent data from temporary retention tables in consent DB"); - for (String consentId : listOfConsentIds) { - Savepoint retentionDBSavepoint = retentionDBConnection.setSavepoint(); - Savepoint consentDBSavepoint = consentDBConnection.setSavepoint(); - try { - // Fetching detailed consent. - DetailedConsentResource detailedConsent = - consentCoreDAO.getDetailedConsentResource(consentDBConnection, consentId, true); - ConsentResource consentResource = new ConsentResource(detailedConsent.getConsentID(), - detailedConsent.getClientID(), detailedConsent.getReceipt(), - detailedConsent.getConsentType(), detailedConsent.getConsentFrequency(), - detailedConsent.getValidityPeriod(), detailedConsent.isRecurringIndicator(), - detailedConsent.getCurrentStatus(), detailedConsent.getCreatedTime(), - detailedConsent.getUpdatedTime()); - - ConsentFile consentFile = null; - ArrayList consentStatusAuditRecords = null; - try { - // Fetching consent file. - consentFile = consentCoreDAO.getConsentFile(consentDBConnection, consentId, true); - } catch (OBConsentDataRetrievalException e) { - log.error(String.format("Error occurred fetching consent file for consent_id : %s , " + - "Ignoring this as null consent file for given consent_id", - consentId.replaceAll("[\r\n]", ""))); - } - try { - // Fetching consent audit records. - ArrayList consentIds = new ArrayList<>(); - consentIds.add(consentId); - consentStatusAuditRecords = - consentCoreDAO.getConsentStatusAuditRecordsByConsentId(consentDBConnection, consentIds, - null, null, true); - } catch (OBConsentDataRetrievalException e) { - log.error(String.format("Error occurred fetching consent audit records for consent_id : %s , " + - "Ignoring this as null consent audit records for given consent_id", - consentId.replaceAll("[\r\n]", ""))); - } - - // Inserting to retention datasource - ConsentResource insertedConsentResources = - consentRetentionDAO.storeConsentResource(retentionDBConnection, consentResource); - if (insertedConsentResources == null) { - throw new OBConsentDataInsertionException(ConsentCoreServiceConstants. - DATA_INSERTION_ROLLBACK_ERROR_MSG + " for consent resource"); - } - for (AuthorizationResource authResource : detailedConsent.getAuthorizationResources()) { - if (authResource.getAuthorizationID() != null) { - AuthorizationResource storeAuthorizationResource = - consentRetentionDAO.storeAuthorizationResource(retentionDBConnection, authResource); - if (storeAuthorizationResource == null) { - throw new OBConsentDataInsertionException(ConsentCoreServiceConstants. - DATA_INSERTION_ROLLBACK_ERROR_MSG + " for authorization resources"); - } - } - } - for (ConsentMappingResource mappingResource : detailedConsent.getConsentMappingResources()) { - ConsentMappingResource storeConsentMappingResource = - consentRetentionDAO.storeConsentMappingResource(retentionDBConnection, mappingResource); - if (storeConsentMappingResource == null) { - throw new OBConsentDataInsertionException(ConsentCoreServiceConstants. - DATA_INSERTION_ROLLBACK_ERROR_MSG + " for mapping resources"); - } - } - if (!detailedConsent.getConsentAttributes().isEmpty()) { - ConsentAttributes consentAttributes = new ConsentAttributes(consentId, - detailedConsent.getConsentAttributes()); - if (!consentRetentionDAO.storeConsentAttributes(retentionDBConnection, consentAttributes)) { - throw new OBConsentDataInsertionException(ConsentCoreServiceConstants. - DATA_INSERTION_ROLLBACK_ERROR_MSG + " for consent attributes"); - } - } - if (consentFile != null) { - if (!consentRetentionDAO.storeConsentFile(retentionDBConnection, consentFile)) { - throw new OBConsentDataInsertionException(ConsentCoreServiceConstants. - DATA_INSERTION_ROLLBACK_ERROR_MSG + " for consent file"); - } - } - if (consentStatusAuditRecords != null) { - for (ConsentStatusAuditRecord auditRecords : consentStatusAuditRecords) { - ConsentStatusAuditRecord storeConsentStatusAuditRecord = consentRetentionDAO - .storeConsentStatusAuditRecord(retentionDBConnection, auditRecords); - if (storeConsentStatusAuditRecord == null) { - throw new OBConsentDataInsertionException(ConsentCoreServiceConstants. - DATA_INSERTION_ROLLBACK_ERROR_MSG + " for consent audit records"); - } - } - } - - // Removing consent data from temporary retention table in consent database - boolean consentDeleted = consentCoreDAO.deleteConsentData(consentDBConnection, consentId, true); - if (!consentDeleted) { - throw new OBConsentDataDeletionException(ConsentCoreServiceConstants. - DATA_DELETE_ROLLBACK_ERROR_MSG + " for consent data deletion"); - } - // Commit transactions - DatabaseUtil.commitTransaction(retentionDBConnection); - DatabaseUtil.commitTransaction(consentDBConnection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - } catch (OBConsentDataRetrievalException | OBConsentDataInsertionException | - OBConsentDataDeletionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - consentDBConnection.rollback(consentDBSavepoint); - retentionDBConnection.rollback(retentionDBSavepoint); - } - } - return true; - } catch (OBConsentDataRetrievalException | SQLException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException("Error occurred while syncing the retention data in consent " + - "database to retention database", e); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(consentDBConnection); - DatabaseUtil.closeConnection(retentionDBConnection); - } - } - - @Override - public ArrayList getConsentStatusAuditRecords(ArrayList consentIDs, - Integer limit, Integer offset, - boolean fetchFromRetentionDatabase) - throws ConsentManagementException { - - if (!OpenBankingConfigParser.getInstance().isConsentDataRetentionEnabled() && fetchFromRetentionDatabase) { - log.error("Consent data retention is not enabled."); - throw new ConsentManagementException("Consent data retention is not enabled."); - } - - Connection connection; - if (fetchFromRetentionDatabase) { - connection = DatabaseUtil.getRetentionDBConnection(); - } else { - connection = DatabaseUtil.getDBConnection(); - } - - ConsentCoreDAO consentCoreDAO; - if (fetchFromRetentionDatabase) { - consentCoreDAO = ConsentStoreInitializer.getInitializedConsentRetentionDAOImpl(); - log.debug("Fetching consent status audit records from retention datasource"); - } else { - consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - } - - try { - //Retrieve consent status audit records. - return consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIDs, limit, offset, - false); - - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ConsentFile getConsentFile(String consentId, boolean fetchFromRetentionDatabase) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentId)) { - log.error("Consent ID is empty"); - throw new ConsentManagementException("Consent ID is empty, cannot proceed"); - } - - if (!OpenBankingConfigParser.getInstance().isConsentDataRetentionEnabled() && fetchFromRetentionDatabase) { - log.error("Consent data retention is not enabled."); - throw new ConsentManagementException("Consent data retention is not enabled."); - } - - Connection connection; - if (fetchFromRetentionDatabase) { - connection = DatabaseUtil.getRetentionDBConnection(); - } else { - connection = DatabaseUtil.getDBConnection(); - } - - ConsentCoreDAO consentCoreDAO; - if (fetchFromRetentionDatabase) { - consentCoreDAO = ConsentStoreInitializer.getInitializedConsentRetentionDAOImpl(); - log.debug("Fetching consent file from retention datasource"); - } else { - consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - } - - try { - //Retrieve consent status audit records. - return consentCoreDAO.getConsentFile(connection, consentId, false); - - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - private List getRecordIdListForConsentHistoryRetrieval(DetailedConsentResource detailedConsentResource) { - - List recordIdsList = new ArrayList<>(); - recordIdsList.add(detailedConsentResource.getConsentID()); - - for (ConsentMappingResource mappingResource : detailedConsentResource.getConsentMappingResources()) { - recordIdsList.add(mappingResource.getMappingID()); - } - for (AuthorizationResource authResource : detailedConsentResource.getAuthorizationResources()) { - recordIdsList.add(authResource.getAuthorizationID()); - } - return recordIdsList; - } - - private Map processConsentAmendmentHistoryData( - Map consentAmendmentHistoryRetrievalResult, - DetailedConsentResource currentConsentResource) throws ConsentManagementException { - - Gson gson = new Gson(); - Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); - DetailedConsentResource detailedConsentHistoryResource = gson.fromJson(gson.toJson(currentConsentResource), - DetailedConsentResource.class); - - for (Map.Entry consentHistoryDataEntry : - consentAmendmentHistoryRetrievalResult.entrySet()) { - String historyId = consentHistoryDataEntry.getKey(); - ConsentHistoryResource consentHistoryResource = consentHistoryDataEntry.getValue(); - - for (Map.Entry consentHistoryDataTypeEntry : - consentHistoryResource.getChangedAttributesJsonDataMap().entrySet()) { - String consentDataType = consentHistoryDataTypeEntry.getKey(); - Object changedAttributes = consentHistoryDataTypeEntry.getValue(); - - if (ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA.equalsIgnoreCase(consentDataType)) { - JSONObject changedValuesJSON = parseChangedAttributeJsonString(changedAttributes.toString()); - if (changedValuesJSON.containsKey(ConsentMgtDAOConstants.RECEIPT)) { - detailedConsentHistoryResource.setReceipt( - (String) changedValuesJSON.get(ConsentMgtDAOConstants.RECEIPT)); - } - if (changedValuesJSON.containsKey(ConsentMgtDAOConstants.VALIDITY_TIME)) { - detailedConsentHistoryResource.setValidityPeriod(Long.parseLong((String) - changedValuesJSON.get(ConsentMgtDAOConstants.VALIDITY_TIME))); - } - if (changedValuesJSON.containsKey(ConsentMgtDAOConstants.UPDATED_TIME)) { - detailedConsentHistoryResource.setUpdatedTime(Long.parseLong((String) - changedValuesJSON.get(ConsentMgtDAOConstants.UPDATED_TIME))); - } - if (changedValuesJSON.containsKey(ConsentMgtDAOConstants.CURRENT_STATUS)) { - detailedConsentHistoryResource.setCurrentStatus((String) - changedValuesJSON.get(ConsentMgtDAOConstants.CURRENT_STATUS)); - } - - } else if (ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA.equalsIgnoreCase(consentDataType)) { - JSONObject changedValuesJSON = parseChangedAttributeJsonString(changedAttributes.toString()); - for (Map.Entry attribute : changedValuesJSON.entrySet()) { - Object attributeValue = attribute.getValue(); - if (attributeValue == null) { - //Ignore the consent attribute from the consent history if it's value is stored as null - detailedConsentHistoryResource.getConsentAttributes().remove(attribute.getKey()); - } else { - detailedConsentHistoryResource.getConsentAttributes().put(attribute.getKey(), - attributeValue.toString()); - } - } - - } else if (ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA.equalsIgnoreCase(consentDataType)) { - Map changedConsentMappingsDataMap = (Map) changedAttributes; - ArrayList consentMappings = - detailedConsentHistoryResource.getConsentMappingResources(); - ArrayList consentMappingsHistory = new ArrayList<>(); - for (ConsentMappingResource mapping : consentMappings) { - String mappingID = mapping.getMappingID(); - if (changedConsentMappingsDataMap.containsKey(mappingID)) { - JSONObject changedValuesJSON = parseChangedAttributeJsonString( - changedConsentMappingsDataMap.get(mappingID).toString()); - if (changedValuesJSON.isEmpty()) { - //Skip setting the mapping to consent history if the value is null - continue; - } - //set the value available in the history as the mapping status - mapping.setMappingStatus( - changedValuesJSON.get(ConsentMgtDAOConstants.MAPPING_STATUS).toString()); - } - consentMappingsHistory.add(gson.fromJson(gson.toJson(mapping), ConsentMappingResource.class)); - } - detailedConsentHistoryResource.setConsentMappingResources(consentMappingsHistory); - - } else if (ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA.equalsIgnoreCase(consentDataType)) { - Map changedConsentAuthResourceDataMap = (Map) changedAttributes; - ArrayList consentAuthResources = detailedConsentHistoryResource - .getAuthorizationResources(); - ArrayList consentAuthResourceHistory = new ArrayList<>(); - for (AuthorizationResource authResource : consentAuthResources) { - String authID = authResource.getAuthorizationID(); - if (changedConsentAuthResourceDataMap.containsKey(authID)) { - JSONObject changedValuesJSON = parseChangedAttributeJsonString( - changedConsentAuthResourceDataMap.get(authID).toString()); - if (changedValuesJSON.isEmpty()) { - //Skip setting the auth resource to consent history if the value is null - continue; - } - } - consentAuthResourceHistory.add(gson.fromJson(gson.toJson(authResource), - AuthorizationResource.class)); - } - detailedConsentHistoryResource.setAuthorizationResources(consentAuthResourceHistory); - } - } - consentHistoryResource.setDetailedConsentResource(gson.fromJson(gson.toJson(detailedConsentHistoryResource), - DetailedConsentResource.class)); - consentAmendmentHistoryDataMap.put(historyId, consentHistoryResource); - } - return consentAmendmentHistoryDataMap; - } - - private JSONObject parseChangedAttributeJsonString(String changedAttributes) throws ConsentManagementException { - - Object changedValues; - try { - changedValues = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(changedAttributes); - } catch (ParseException e) { - throw new ConsentManagementException("Changed Values is not a valid JSON object", e); - } - if (changedValues == null) { - return new JSONObject(); - } - return (JSONObject) changedValues; - - } - - public void revokeTokens(DetailedConsentResource detailedConsentResource, String userID) - throws IdentityOAuth2Exception { - - OAuth2Service oAuth2Service = getOAuth2Service(); - String clientId = detailedConsentResource.getClientID(); - String consentId = detailedConsentResource.getConsentID(); - AuthenticatedUser authenticatedUser = getAuthenticatedUser(userID); - Set accessTokenDOSet = getAccessTokenDOSet(detailedConsentResource, authenticatedUser); - - String consentIdClaim = OpenBankingConfigParser.getInstance().getConfiguration() - .get(OpenBankingConstants.CONSENT_ID_CLAIM_NAME).toString(); - - if (!accessTokenDOSet.isEmpty()) { - Set activeTokens = new HashSet<>(); - // Get tokens to revoke to an array - for (AccessTokenDO accessTokenDO : accessTokenDOSet) { - // Filter tokens by consent ID claim - if (Arrays.asList(accessTokenDO.getScope()).contains(consentIdClaim + - detailedConsentResource.getConsentID())) { - activeTokens.add(accessTokenDO.getAccessToken()); - } - } - - if (!activeTokens.isEmpty()) { - // set authorization context details for the given user - OAuthClientAuthnContext oAuthClientAuthnContext = new OAuthClientAuthnContext(); - oAuthClientAuthnContext.setAuthenticated(true); - oAuthClientAuthnContext.setClientId(clientId); - oAuthClientAuthnContext.addParameter(OpenBankingConstants.IS_CONSENT_REVOCATION_FLOW, true); - - // set common properties of token revocation request - OAuthRevocationRequestDTO revokeRequestDTO = new OAuthRevocationRequestDTO(); - revokeRequestDTO.setOauthClientAuthnContext(oAuthClientAuthnContext); - revokeRequestDTO.setConsumerKey(clientId); - revokeRequestDTO.setTokenType(GrantType.REFRESH_TOKEN.toString()); - - for (String activeToken : activeTokens) { - // set access token to be revoked - revokeRequestDTO.setToken(activeToken); - OAuthRevocationResponseDTO oAuthRevocationResponseDTO = - revokeTokenByClient(oAuth2Service, revokeRequestDTO); - - if (oAuthRevocationResponseDTO.isError()) { - log.error("Error while revoking access token for consent ID: " - + consentId.replaceAll("[\r\n]", "")); - throw new IdentityOAuth2Exception( - String.format("Error while revoking access token for consent ID: %s. Caused by, %s", - consentId, oAuthRevocationResponseDTO.getErrorMsg())); - } - } - } - } - } - - private boolean isValidUserID(String requestUserID, Set consentUserIDSet) { - if (StringUtils.isEmpty(requestUserID)) { - // userId not present in request query parameters, can use consentUserID to revoke tokens - return true; - } - return consentUserIDSet.contains(requestUserID); - } - - @Generated(message = "Excluded from code coverage since used for testing purposes") - OAuth2Service getOAuth2Service() { - - return ConsentManagementDataHolder.getInstance().getOAuth2Service(); - } - - @Generated(message = "Excluded from code coverage since used for testing purposes") - AuthenticatedUser getAuthenticatedUser(String userID) throws IdentityOAuth2Exception { - // set domain name - if (UserCoreUtil.getDomainFromThreadLocal() == null) { - UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(userID)); - } - if (OpenBankingConfigParser.getInstance().isPSUFederated()) { - AuthenticatedUser authenticatedUser = - AuthenticatedUser.createFederateAuthenticatedUserFromSubjectIdentifier(userID); - authenticatedUser.setUserStoreDomain(OAuth2Util.getUserStoreForFederatedUser(authenticatedUser)); - authenticatedUser.setTenantDomain(MultitenantUtils.getTenantDomain(userID)); - authenticatedUser.setFederatedIdPName(OpenBankingConfigParser.getInstance().getFederatedIDPName()); - authenticatedUser.setUserName(MultitenantUtils.getTenantAwareUsername(userID)); - return authenticatedUser; - } else { - return AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(userID); - } - } - - @Generated(message = "Excluded from code coverage since used for testing purposes") - Set getAccessTokenDOSet(DetailedConsentResource detailedConsentResource, - AuthenticatedUser authenticatedUser) throws IdentityOAuth2Exception { - - return OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO() - .getAccessTokens(detailedConsentResource.getClientID(), authenticatedUser, - authenticatedUser.getUserStoreDomain(), false); - } - - @Generated(message = "Excluded from code coverage since used for testing purposes") - OAuthRevocationResponseDTO revokeTokenByClient(OAuth2Service oAuth2Service, - OAuthRevocationRequestDTO revocationRequestDTO) { - - return oAuth2Service.revokeTokenByOAuthClient(revocationRequestDTO); - } - - @Override - public ConsentResource updateConsentStatus(String consentId, String newConsentStatus) - throws ConsentManagementException { - - if (StringUtils.isBlank(consentId) || StringUtils.isBlank(newConsentStatus)) { - - log.error("Consent ID, userID or newConsentStatus is missing. Cannot proceed."); - throw new ConsentManagementException("Cannot proceed without Consent ID, userID or newConsentStatus."); - } - - Connection connection = DatabaseUtil.getDBConnection(); - ConsentResource updatedConsentResource; - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Get the existing consent to validate status - if (log.isDebugEnabled()) { - log.debug("Retrieving the consent for ID:" + consentId.replaceAll("[\r\n]", "") - + " to validate status"); - } - - // Update consent status with new status - if (log.isDebugEnabled()) { - log.debug("Updating the status of the consent for ID:" + consentId.replaceAll("[\r\n]", "")); - } - - DetailedConsentResource existingConsentResource = consentCoreDAO - .getDetailedConsentResource(connection, consentId, false); - String existingConsentStatus = existingConsentResource.getCurrentStatus(); - ArrayList authResources = existingConsentResource.getAuthorizationResources(); - - updatedConsentResource = consentCoreDAO.updateConsentStatus(connection, consentId, newConsentStatus); - - // Previous consent status is not added in reason because it can be null - String auditMessage = "Consent status updated to " + newConsentStatus; - for (AuthorizationResource authResource : authResources) { - // Create an audit record execute state change listener - HashMap consentDataMap = new HashMap<>(); - consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, existingConsentResource); - postStateChange(connection, consentCoreDAO, consentId, authResource.getUserID(), newConsentStatus, - existingConsentStatus, auditMessage, existingConsentResource.getClientID(), consentDataMap); - } - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return updatedConsentResource; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBConsentDataInsertionException e) { - log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public ArrayList getConsentsEligibleForExpiration(String statusesEligibleForExpiration) - throws ConsentManagementException { - - Connection connection = DatabaseUtil.getDBConnection(); - ArrayList detailedConsentResources; - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - log.debug("Retrieving consents which has expiration time attribute."); - detailedConsentResources = consentCoreDAO.getExpiringConsents(connection, - statusesEligibleForExpiration); - // Commit transactions - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return detailedConsentResources; - } catch (OBConsentDataRetrievalException e) { - log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - private void postStateChange(Connection connection, ConsentCoreDAO consentCoreDAO, String consentID, - String userID, String newConsentStatus, String previousConsentStatus, String reason, - String clientId, Map consentDataMap) - throws OBConsentDataInsertionException, ConsentManagementException { - - createAuditRecord(connection, consentCoreDAO, consentID, userID, newConsentStatus, previousConsentStatus, - reason); - ConsentStateChangeListenerImpl.getInstance().onStateChange(consentID, userID, newConsentStatus, - previousConsentStatus, reason, clientId, consentDataMap); - } - - public AuthorizationResource updateAuthorizationStatus(String authorizationId, String newAuthorizationStatus) - throws ConsentManagementException { - - if (StringUtils.isBlank(authorizationId) || StringUtils.isBlank(newAuthorizationStatus)) { - - log.error("Authorization ID or newAuthorizationStatus is missing. Cannot proceed."); - throw new ConsentManagementException("Cannot proceed without Authorization ID or newAuthorizationStatus" + - "."); - } - - Connection connection = DatabaseUtil.getDBConnection(); - AuthorizationResource updatedAuthorizationResource; - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Update authorization status with new status - if (log.isDebugEnabled()) { - log.debug("Updating the status of the authorization for ID:" + - authorizationId.replaceAll("[\r\n]", "")); - } - updatedAuthorizationResource = consentCoreDAO.updateAuthorizationStatus(connection, authorizationId, - newAuthorizationStatus); - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return updatedAuthorizationResource; - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - public void updateAuthorizationUser(String authorizationID, String userID) - throws ConsentManagementException { - - if (StringUtils.isBlank(authorizationID) || StringUtils.isBlank(userID)) { - - log.error("Authorization ID or user ID is missing. Cannot proceed."); - throw new ConsentManagementException("Cannot proceed without Authorization ID or UserID."); - } - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); - try { - // Updating the authorized user - if (log.isDebugEnabled()) { - log.debug("Updating the status of the user for authorization ID:" + - authorizationID.replaceAll("[\r\n]", "")); - } - consentCoreDAO.updateAuthorizationUser(connection, authorizationID, - userID); - - // Commit transaction - DatabaseUtil.commitTransaction(connection); - log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return; - } catch (OBConsentDataUpdationException e) { - log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new ConsentManagementException(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } - } finally { - log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/ConsentStateChangeListenerImpl.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/ConsentStateChangeListenerImpl.java deleted file mode 100644 index fa9ce72f..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/ConsentStateChangeListenerImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.impl; - -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import com.wso2.openbanking.accelerator.common.event.executor.model.OBEvent; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.mgt.service.internal.ConsentManagementDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.service.listener.ConsentStateChangeListener; - -import java.util.HashMap; -import java.util.Map; - -/** - * Consent state change listener implementation. - */ -public class ConsentStateChangeListenerImpl implements ConsentStateChangeListener { - - private static volatile ConsentStateChangeListenerImpl instance; - - private ConsentStateChangeListenerImpl() { - - } - - public static ConsentStateChangeListenerImpl getInstance() { - - if (instance == null) { - synchronized (ConsentStateChangeListenerImpl.class) { - if (instance == null) { - instance = new ConsentStateChangeListenerImpl(); - } - } - } - return instance; - } - - @Override - public void onStateChange(String consentID, String userID, String newConsentStatus, String previousConsentStatus, - String reason, String clientId, Map consentDataMap) - throws ConsentManagementException { - - OBEventQueue obEventQueue = ConsentManagementDataHolder.getInstance().getOBEventQueue(); - - Map eventData = new HashMap<>(); - eventData.put("ConsentId", consentID); - eventData.put("UserId", userID); - eventData.put("PreviousConsentStatus", previousConsentStatus); - eventData.put("Reason", reason); - eventData.put("ClientId", clientId); - eventData.put("ConsentDataMap", consentDataMap); - - obEventQueue.put(new OBEvent(newConsentStatus, eventData)); - - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/internal/ConsentManagementDataHolder.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/internal/ConsentManagementDataHolder.java deleted file mode 100644 index a50ed80d..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/internal/ConsentManagementDataHolder.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.internal; - -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl; - -/** - * Data holder for consent management service. - */ -public class ConsentManagementDataHolder { - - private OAuth2Service oAuth2Service; - private static volatile ConsentManagementDataHolder instance; - private OBEventQueue obEventQueue; - private final AccessTokenDAOImpl accessTokenDAO; - - private ConsentManagementDataHolder() { - this.accessTokenDAO = new AccessTokenDAOImpl(); - } - - public static ConsentManagementDataHolder getInstance() { - - if (instance == null) { - synchronized (ConsentManagementDataHolder.class) { - if (instance == null) { - instance = new ConsentManagementDataHolder(); - } - } - } - return instance; - } - - public OAuth2Service getOAuth2Service() { - - return oAuth2Service; - } - - public void setOAuth2Service(OAuth2Service oAuth2Service) { - - this.oAuth2Service = oAuth2Service; - } - - public void setOBEventQueue(OBEventQueue obEventQueue) { - - this.obEventQueue = obEventQueue; - } - - public OBEventQueue getOBEventQueue() { - - return obEventQueue; - } - - public AccessTokenDAOImpl getAccessTokenDAO() { - return accessTokenDAO; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/internal/ConsentManagementServiceComponent.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/internal/ConsentManagementServiceComponent.java deleted file mode 100644 index 2a7e4cff..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/internal/ConsentManagementServiceComponent.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingRuntimeException; -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.consent.mgt.service.ConsentCoreService; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.identity.oauth2.OAuth2Service; - -import java.sql.SQLException; - -/** - * Consent Management Core Service Component. - */ -@Component(name = "com.wso2.openbanking.accelerator.consent.mgt.service.ConsentManagementServiceComponent", - immediate = true) -public class ConsentManagementServiceComponent { - - private static Log log = LogFactory.getLog(ConsentManagementServiceComponent.class); - - @Activate - protected void activate(ComponentContext context) { - - ConsentCoreService consentCoreService = new ConsentCoreServiceImpl(); - - // Verify Open Banking consent database connection when the server starts up - try { - boolean isConnectionActive = JDBCPersistenceManager.getInstance().getDBConnection() - .isValid(OpenBankingConfigParser.getInstance().getConnectionVerificationTimeout()); - - if (!isConnectionActive) { - log.error("The connection is not active"); - throw new OpenBankingRuntimeException("The connection is not active"); - } - } catch (SQLException e) { - log.error("Database connection is not active, cannot proceed"); - throw new OpenBankingRuntimeException("Database connection is not active, cannot proceed"); - } - - // Verify Open Banking retention database connection when the server starts up - if (OpenBankingConfigParser.getInstance().isConsentDataRetentionEnabled()) { - try { - boolean isConnectionActive = JDBCPersistenceManager.getInstance().getDBConnection().isValid( - OpenBankingConfigParser.getInstance().getRetentionDataSourceConnectionVerificationTimeout()); - - if (!isConnectionActive) { - log.error("The connection is not active for retention datasource"); - throw new OpenBankingRuntimeException("The connection is not active for retention datasource"); - } - } catch (SQLException e) { - log.error("Database connection is not active for retention datasource, cannot proceed"); - throw new OpenBankingRuntimeException("Database connection is not active for retention datasource, " + - "cannot proceed"); - } - } - - context.getBundleContext().registerService(ConsentCoreService.class.getName(), consentCoreService, null); - log.debug("Consent Management Service is registered successfully."); - } - - @Deactivate - protected void deactivate(ComponentContext ctxt) { - log.debug("Consent Management Service is deactivated"); - } - - @Reference( - name = "identity.oauth.service", - service = OAuth2Service.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOAuth2Service" - ) - protected void setOAuth2Service(OAuth2Service oAuth2Service) { - - ConsentManagementDataHolder.getInstance().setOAuth2Service(oAuth2Service); - log.debug("OAuth2Service is activated"); - } - - protected void unsetOAuth2Service(OAuth2Service oAuth2Service) { - - ConsentManagementDataHolder.getInstance().setOAuth2Service(oAuth2Service); - } - - @Reference( - service = OBEventQueue.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOBEventQueue" - ) - - protected void setOBEventQueue(OBEventQueue obEventQueue) { - - ConsentManagementDataHolder.getInstance().setOBEventQueue(obEventQueue); - } - - protected void unsetOBEventQueue(OBEventQueue obEventQueue) { - - ConsentManagementDataHolder.getInstance().setOBEventQueue(null); - } - - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/listener/ConsentStateChangeListener.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/listener/ConsentStateChangeListener.java deleted file mode 100644 index e2fab0a1..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/java/com/wso2/openbanking/accelerator/consent/mgt/service/listener/ConsentStateChangeListener.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.listener; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; - -import java.util.Map; - -/** - * Consent state change listener interface. - */ -public interface ConsentStateChangeListener { - - /** - * This method is used to put events to OBEventQueue related to different consent state changes. - * - * @param consentID consent ID - * @param userID user ID - * @param newConsentStatus new consent status after state change - * @param previousConsentStatus previous consent status - * @param reason reason for changing consent state - * @param clientId client ID - * @param consentDataMap consent data map holding different consent related data - * @throws ConsentManagementException thrown if an error occurs - */ - public void onStateChange(String consentID, String userID, String newConsentStatus, - String previousConsentStatus, String reason, String clientId, - Map consentDataMap) throws ConsentManagementException; -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/resources/findbugs-include.xml deleted file mode 100644 index 0882a6d1..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,17 +0,0 @@ - diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/OBConsentMgtCoreServiceTests.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/OBConsentMgtCoreServiceTests.java deleted file mode 100644 index 360eafe6..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/service/impl/OBConsentMgtCoreServiceTests.java +++ /dev/null @@ -1,3401 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.impl; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.event.executor.OBEventQueue; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.consent.mgt.dao.ConsentCoreDAO; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataDeletionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataInsertionException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataRetrievalException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.exceptions.OBConsentDataUpdationException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.persistence.ConsentStoreInitializer; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import com.wso2.openbanking.accelerator.consent.mgt.service.internal.ConsentManagementDataHolder; -import com.wso2.openbanking.accelerator.consent.mgt.service.util.ConsentMgtServiceTestData; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO; -import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; - -import java.sql.Connection; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import static org.mockito.Matchers.any; - -/** - * Test for Open Banking consent management core service. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({DatabaseUtil.class, ConsentStoreInitializer.class, ConsentManagementDataHolder.class, - OpenBankingConfigParser.class}) -public class OBConsentMgtCoreServiceTests { - - private ConsentCoreServiceImpl consentCoreServiceImpl; - private ConsentCoreDAO mockedConsentCoreDAO; - private String sampleID; - private ConsentManagementDataHolder consentManagementDataHolderMock; - private OBEventQueue obEventQueueMock; - - @BeforeClass - public void initTest() { - - consentCoreServiceImpl = new ConsentCoreServiceImpl(); - mockedConsentCoreDAO = Mockito.mock(ConsentCoreDAO.class); - consentManagementDataHolderMock = Mockito.mock(ConsentManagementDataHolder.class); - obEventQueueMock = Mockito.mock(OBEventQueue.class); - } - - @BeforeMethod - public void mock() throws ConsentManagementException, IdentityOAuth2Exception { - - sampleID = UUID.randomUUID().toString(); - mockStaticClasses(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test (priority = 2) - public void testCreateAuthorizableConsent() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), Mockito.any()); - - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleTestConsentResource(), ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE, true); - - Assert.assertNotNull(detailedConsentResource); - Assert.assertNotNull(detailedConsentResource.getConsentID()); - Assert.assertNotNull(detailedConsentResource.getClientID()); - Assert.assertNotNull(detailedConsentResource.getReceipt()); - Assert.assertNotNull(detailedConsentResource.getConsentType()); - Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); - } - - @Test (priority = 2) - public void testCreateAuthorizableConsentWithIsImplicitAuthFalse() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), Mockito.any()); - - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleTestConsentResource(), ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE, false); - - Assert.assertNotNull(detailedConsentResource); - Assert.assertNotNull(detailedConsentResource.getConsentID()); - Assert.assertNotNull(detailedConsentResource.getClientID()); - Assert.assertNotNull(detailedConsentResource.getReceipt()); - Assert.assertNotNull(detailedConsentResource.getConsentType()); - Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); - } - - @Test (priority = 2) - public void testCreateAuthorizableConsentWithAttributes() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) - .when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(Mockito.any(), - Mockito.any()); - - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResourceWithAttributes(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE, true); - - Assert.assertNotNull(detailedConsentResource); - Assert.assertNotNull(detailedConsentResource.getConsentID()); - Assert.assertNotNull(detailedConsentResource.getClientID()); - Assert.assertNotNull(detailedConsentResource.getReceipt()); - Assert.assertNotNull(detailedConsentResource.getConsentType()); - Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); - Assert.assertNotNull(detailedConsentResource.getConsentAttributes()); - } - - @Test (priority = 2) - public void testCreateAuthorizableConsentWithoutUserID() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) - .when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), Mockito.any()); - - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResourceWithAttributes(), null, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE, true); - - Assert.assertNotNull(detailedConsentResource); - Assert.assertNotNull(detailedConsentResource.getConsentID()); - Assert.assertNotNull(detailedConsentResource.getClientID()); - Assert.assertNotNull(detailedConsentResource.getReceipt()); - Assert.assertNotNull(detailedConsentResource.getConsentType()); - Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentWithoutClientID() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); - consentResource.setClientID(null); - - consentCoreServiceImpl.createAuthorizableConsent(consentResource, Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentWithoutReceipt() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); - consentResource.setReceipt(null); - - consentCoreServiceImpl.createAuthorizableConsent(consentResource, Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentWithoutConsentType() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); - consentResource.setConsentType(null); - - consentCoreServiceImpl.createAuthorizableConsent(consentResource, Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentWithoutCurrentStatus() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); - consentResource.setCurrentStatus(null); - - consentCoreServiceImpl.createAuthorizableConsent(consentResource, Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentWithImplicitAndNoAuthStatus() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) - .when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResourceWithAttributes(), null, null, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentWithImplicitAndNoAuthType() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) - .when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResourceWithAttributes(), null, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, null, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateAuthorizableConsentRollback() throws Exception { - - Mockito.doThrow(OBConsentDataInsertionException.class).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData - .getSampleTestConsentResource(), ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE, true); - } - - @Test - public void testCreateExclusiveConsent() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) - .when(mockedConsentCoreDAO).storeConsentResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(Mockito.any(), - Mockito.anyObject()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), Mockito.anyObject()); - - DetailedConsentResource exclusiveConsent = - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - Assert.assertNotNull(exclusiveConsent); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentDataUpdateError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentDataInsertError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithoutClientID() throws Exception { - - ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - sampleConsentResource.setClientID(null); - - consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithoutReceipt() throws Exception { - - ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - sampleConsentResource.setReceipt(null); - - consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithoutConsentType() throws Exception { - - ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - sampleConsentResource.setConsentType(null); - - consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithoutConsentStatus() throws Exception { - - ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - sampleConsentResource.setCurrentStatus(null); - - consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithoutUserID() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - null, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithouAuthStatus() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithouAuthType() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithImplicitAuthFalse() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithouApplicableExistingConsentStatus() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, null, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithouNewExistingConsentStatus() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - null, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateExclusiveConsentWithouNewCurrentConsentStatus() throws Exception { - - consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - null, true); - } - - @Test - public void testRevokeConsent() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( - retrievedDetailedConsentResource.getConsentID(), retrievedDetailedConsentResource.getCurrentStatus())) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.anyString()); - - boolean isConsentRevoked = new MockConsentCoreServiceImpl() - .revokeConsentWithReason(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - - Assert.assertTrue(isConsentRevoked); - } - - @Test - public void testRevokeConsentAndTokens() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( - retrievedDetailedConsentResource.getConsentID(), retrievedDetailedConsentResource.getCurrentStatus())) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.anyString()); - - boolean isConsentRevoked = new MockConsentCoreServiceImpl() - .revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - true); - - - Assert.assertTrue(isConsentRevoked); - } - - @Test - public void testRevokeConsentAndTokensTokenRevokeError() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( - retrievedDetailedConsentResource.getConsentID(), retrievedDetailedConsentResource.getCurrentStatus())) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.anyString()); - try { - boolean isConsentRevoked = new MockConsentCoreServiceImplTokenError() - .revokeConsentWithReason(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - true, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - Assert.assertTrue(isConsentRevoked); - } catch (Exception e) { - Assert.assertTrue(e instanceof ConsentManagementException); - } - - } - - @Test - public void testRevokeConsentWithoutConsentAttributes() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - retrievedDetailedConsentResource.setConsentAttributes(null); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( - retrievedDetailedConsentResource.getConsentID(), retrievedDetailedConsentResource.getCurrentStatus())) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.anyString()); - - boolean isConsentRevoked = new MockConsentCoreServiceImpl() - .revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false); - - Assert.assertTrue(isConsentRevoked); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentWithoutConsentID() throws Exception { - - consentCoreServiceImpl.revokeConsentWithReason(null, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentWithoutNewConsentStatus() throws Exception { - - consentCoreServiceImpl.revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - null, ConsentMgtServiceTestData.SAMPLE_USER_ID, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentWithoutApplicableStatusToRevoke() throws Exception { - - consentCoreServiceImpl.revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentWithInvalidApplicableStatus() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - - consentCoreServiceImpl.revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentDataRetrievalError() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - - consentCoreServiceImpl.revokeConsentWithReason(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentDataInsertionError() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - new MockConsentCoreServiceImpl().revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeConsentDataUpdationError() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doThrow(OBConsentDataUpdationException.class).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - - consentCoreServiceImpl.revokeConsentWithReason(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); - } - - @Test - public void testRevokeExistingApplicableConsents() throws Exception { - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); - - Mockito.doReturn(detailedConsentResources).when(mockedConsentCoreDAO) - .searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.any()); - - Assert.assertTrue(consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - false)); - } - - @Test - public void testRevokeExistingApplicableConsentsWithTokens() throws Exception { - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); - - Mockito.doReturn(detailedConsentResources).when(mockedConsentCoreDAO) - .searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.any()); - - Assert.assertTrue(new MockConsentCoreServiceImpl().revokeExistingApplicableConsents(sampleID, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - true)); - } - - @Test - public void testRevokeExistingApplicableConsentsWithConsentsWithNoAttributes() throws Exception { - - DetailedConsentResource detailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - detailedConsentResource.setConsentAttributes(null); - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(detailedConsentResource); - - Mockito.doReturn(detailedConsentResources).when(mockedConsentCoreDAO) - .searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - - consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsUpdateError() throws Exception { - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); - - Mockito.doReturn(detailedConsentResources).when(mockedConsentCoreDAO) - .searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doThrow(OBConsentDataUpdationException.class).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - - consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsInsertionError() throws Exception { - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); - - Mockito.doReturn(detailedConsentResources).when(mockedConsentCoreDAO) - .searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsWithoutClientID() throws Exception { - - consentCoreServiceImpl.revokeExistingApplicableConsents(null, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsWithoutRevokedConsentStatus() throws Exception { - - consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsWithoutUserID() throws Exception { - - consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, - null, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS - , false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsWithoutConsentType() throws Exception { - - consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, - ConsentMgtServiceTestData.SAMPLE_USER_ID, null, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS - , false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testRevokeExistingApplicableConsentsWithoutApplicableStatusToRevoke() throws Exception { - - consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, - null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS - , false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileErrorWhenRetrieval() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .getConsentResource(Mockito.any(), Mockito.anyString()); - - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileRollBackWhenCreation() throws Exception { - - ConsentResource storedConsentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - - Mockito.doReturn(storedConsentResource).when(mockedConsentCoreDAO) - .getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class).when(mockedConsentCoreDAO) - .storeConsentFile(Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - Mockito.anyString()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileRollBackWhenUpdating() throws Exception { - - ConsentResource storedConsentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - - Mockito.doReturn(storedConsentResource).when(mockedConsentCoreDAO) - .getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataUpdationException.class).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - storedConsentResource.getCurrentStatus()); - } - - @Test(expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileWithInvalidStatus() - throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); - consentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - - Mockito.doReturn(consentResource).when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), - Mockito.anyString()); - - // Create consent file - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); - } - - @Test(expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileWithoutFileContent() throws Exception { - - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(null), ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); - } - - @Test(expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileWithoutConsentID() throws Exception { - - ConsentFile sampleConsentFile = - ConsentMgtServiceTestData.getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE); - - sampleConsentFile.setConsentID(null); - consentCoreServiceImpl.createConsentFile(sampleConsentFile, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); - } - - @Test(expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileWithoutNewConsentStatus() - throws Exception { - - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), - null, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); - } - - @Test(expectedExceptions = ConsentManagementException.class) - public void testCreateConsentFileWithoutApplicableStatusForFileUpload() - throws Exception { - - consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, - null); - } - - @Test - public void testGetConsent() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()).when(mockedConsentCoreDAO) - .getConsentResource(Mockito.any(), Mockito.anyString()); - - // Get consent - ConsentResource retrievedConsentResource = consentCoreServiceImpl.getConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResource().getConsentID(), false); - - Assert.assertNotNull(retrievedConsentResource); - } - - @Test - public void testGetConsentWithAttributes() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResourceWithAttributes()) - .when(mockedConsentCoreDAO).getConsentResourceWithAttributes(Mockito.any(), Mockito.anyString()); - - // Get consent - ConsentResource retrievedConsentResource = consentCoreServiceImpl.getConsent(ConsentMgtServiceTestData - .getSampleStoredTestConsentResource().getConsentID(), true); - - Assert.assertNotNull(retrievedConsentResource); - Assert.assertNotNull(retrievedConsentResource.getConsentAttributes()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentRollBackWhenRetrieve() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .getConsentResource(Mockito.any(), Mockito.anyString()); - - // Get consent - consentCoreServiceImpl.getConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource().getConsentID(), - false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentWithoutConsentID() throws Exception { - - consentCoreServiceImpl.getConsent(null, false); - } - - @Test - public void testGetDetailedConsent() throws Exception { - - DetailedConsentResource detailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(detailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - - // Get consent - DetailedConsentResource retrievedConsentResource = - consentCoreServiceImpl.getDetailedConsent(detailedConsentResource.getConsentID()); - - Assert.assertNotNull(retrievedConsentResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetDetailedConsentWithoutConsentID() throws Exception { - - consentCoreServiceImpl.getDetailedConsent(null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetDetailedConsentRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - consentCoreServiceImpl.getDetailedConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource() - .getConsentID()); - } - - @Test - public void testCreateConsentAuthorization() throws Exception { - - AuthorizationResource sampleAuthorizationResource = - ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) - .when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), Mockito.any()); - - //Create a consent authorization resource - AuthorizationResource storedAuthorizationResource = - consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); - - Assert.assertNotNull(storedAuthorizationResource); - Assert.assertNotNull(storedAuthorizationResource.getAuthorizationID()); - Assert.assertNotNull(storedAuthorizationResource.getConsentID()); - Assert.assertNotNull(storedAuthorizationResource.getAuthorizationType()); - Assert.assertNotNull(storedAuthorizationResource.getUserID()); - Assert.assertNotNull(storedAuthorizationResource.getAuthorizationStatus()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAuthorizationRollbackWhenCreation() throws Exception { - - AuthorizationResource sampleAuthorizationResource = - ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID); - - Mockito.doThrow(OBConsentDataInsertionException.class).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), Mockito.any()); - - // Get consent - consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAuthorizationWithoutConsentID() throws Exception { - - AuthorizationResource sampleAuthorizationResource = - ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null); - - //Create a consent authorization resource - consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAuthorizationWithoutAuthorizationStatus() throws Exception { - - AuthorizationResource sampleAuthorizationResource = - ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID); - - // Explicitly setting authorization status to null - sampleAuthorizationResource.setAuthorizationStatus(null); - - //Create a consent authorization resource - consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAuthorizationWithoutAuthorizationType() throws Exception { - - AuthorizationResource sampleAuthorizationResource = - ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID); - sampleAuthorizationResource.setAuthorizationType(null); - - //Create a consent authorization resource - consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAuthorizationWithoutAuthorizationUserID() throws Exception { - - AuthorizationResource sampleAuthorizationResource = - ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID); - sampleAuthorizationResource.setUserID(null); - - //Create a consent authorization resource - consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); - } - - @Test - public void testCreateConsentAccountMapping() throws Exception { - - AuthorizationResource storedAuthorizationResource = - ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource(); - - ConsentMappingResource storedConsentMappingResource = - ConsentMgtServiceTestData.getSampleStoredTestConsentMappingResource(sampleID); - - Mockito.doReturn(storedConsentMappingResource).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), Mockito.any()); - - ArrayList storedConsentMappingResources = - consentCoreServiceImpl.createConsentAccountMappings(storedAuthorizationResource.getAuthorizationID(), - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP); - - Assert.assertNotNull(storedConsentMappingResources); - for (ConsentMappingResource resource : storedConsentMappingResources) { - Assert.assertNotNull(resource.getAccountID()); - Assert.assertNotNull(resource.getPermission()); - Assert.assertNotNull(resource.getAuthorizationID()); - Assert.assertEquals(resource.getMappingStatus(), ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); - } - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAccountMappingRollBackWhenCreation() throws Exception { - - AuthorizationResource storedAuthorizationResource = - ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource(); - - Mockito.doThrow(OBConsentDataInsertionException.class).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.createConsentAccountMappings(storedAuthorizationResource.getAuthorizationID(), - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAccountMappingWithoutAuthID() throws Exception { - - consentCoreServiceImpl.createConsentAccountMappings(null, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testCreateConsentAccountMappingWithoutAccountAndPermissionsMap() throws Exception { - - consentCoreServiceImpl.createConsentAccountMappings(sampleID, new HashMap<>()); - } - - @Test - public void testDeactivateAccountMappings() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.any()); - Assert.assertTrue(consentCoreServiceImpl - .deactivateAccountMappings(ConsentMgtServiceTestData.UNMATCHED_MAPPING_IDS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testDeactivateAccountMappingsWithEmptyMappingIDList() throws Exception { - - consentCoreServiceImpl.deactivateAccountMappings(new ArrayList<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testDeactivateAccountMappingsRollback() throws Exception { - - Mockito.doThrow(OBConsentDataUpdationException.class).when(mockedConsentCoreDAO) - .updateConsentMappingStatus(Mockito.any(), Mockito.any(), Mockito.any()); - consentCoreServiceImpl.deactivateAccountMappings(ConsentMgtServiceTestData.UNMATCHED_MAPPING_IDS); - } - - @Test - public void testUpdateAccountMappingPermissionWithEmptyMap() { - - try { - consentCoreServiceImpl.updateAccountMappingPermission(new HashMap<>()); - Assert.fail("Expected ConsentManagementException to be thrown"); - } catch (ConsentManagementException e) { - Assert.assertEquals(e.getMessage(), "Cannot proceed since account mapping IDs are not provided"); - } - } - - @Test - public void testUpdateAccountMappingPermission() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingPermission(Mockito.any(), - Mockito.any()); - Assert.assertTrue(consentCoreServiceImpl - .updateAccountMappingPermission(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_PERMISSION_MAP)); - } - - @Test - public void testSearchConsents() throws Exception { - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); - - Mockito.doReturn(detailedConsentResources) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - - consentCoreServiceImpl.searchDetailedConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, - ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, - ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, - 12345L, 23456L, null, null); - } - - @Test - public void testSearchConsentsInRetention() throws Exception { - - ArrayList detailedConsentResources = new ArrayList<>(); - detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); - - Mockito.doReturn(detailedConsentResources) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - - consentCoreServiceImpl.searchDetailedConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, - ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, - ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, - 12345L, 23456L, null, null, false); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSearchConsentsRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - - consentCoreServiceImpl.searchDetailedConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, - ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, - ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, - 12345L, 23456L, null, null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSearchConsentsRetrieveErrorInRetention() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - - consentCoreServiceImpl.searchDetailedConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, - ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, - ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, - 12345L, 23456L, null, null, true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSearchConsentsWithLimits() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - - consentCoreServiceImpl.searchDetailedConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, - ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, - ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, - 12345L, 23456L, 1, 0); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSearchConsentsInRetentionDBWithLimits() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), - Mockito.anyInt()); - - consentCoreServiceImpl.searchDetailedConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, - ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, - ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, - 12345L, 23456L, 1, 0, true); - } - - @Test - public void testBindUserAccountsToConsentWithAccountIdList() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).updateAuthorizationUser(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).updateAuthorizationStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - Assert.assertTrue(consentCoreServiceImpl - .bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID_LIST, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test - public void testBindUserAccountsToConsent() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).updateAuthorizationUser(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).updateAuthorizationStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - Assert.assertTrue(consentCoreServiceImpl - .bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithoutNewCurrentConsentStatus() throws Exception { - - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithoutConsentID() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - consentResource.setConsentID(null); - - consentCoreServiceImpl.bindUserAccountsToConsent(consentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithoutClientID() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - consentResource.setClientID(null); - - consentCoreServiceImpl.bindUserAccountsToConsent(consentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithotConsentType() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - consentResource.setConsentType(null); - - consentCoreServiceImpl.bindUserAccountsToConsent(consentResource, - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithoutUserID() throws Exception { - - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - null, "authID", ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithoutAuthID() throws Exception { - - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, null, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithoutNewAuthStatus() throws Exception { - - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, null, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentWithEmptyAccountsAndPermissionsMap() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", new HashMap<>(), - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentDataUpdateError() throws Exception { - - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateAuthorizationUser(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testBindUserAccountsToConsentDataInsertError() throws Exception { - - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredTestConsentResource(), - ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test - public void testReAuthorizeExistingAuthResources() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); - } - - @Test - public void testReAuthorizeExistingAuthResourceAccountsAddScenario() throws Exception { - - ConsentMappingResource consentMappingResource = - ConsentMgtServiceTestData.getSampleTestConsentMappingResource(sampleID); - consentMappingResource.setAccountID("accountID1"); - ArrayList mappingResources = new ArrayList<>(); - mappingResources.add(consentMappingResource); - - DetailedConsentResource detailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - detailedConsentResource.setConsentMappingResources(mappingResources); - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - Mockito.doReturn(detailedConsentResource) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); - } - - @Test - public void testReAuthorizeExistingAuthResourceNoAccountsRemoveOrAddScenario() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP2, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); - } - - @Test - public void testReAuthorizeExistingAuthResourceAccountsRemoveScenario() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP3, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); - } - - @Test - public void testReAuthorizeExistingAuthResourcesWithoutMatchingStatuses() throws Exception { - - ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredTestConsentResource(); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutConsentID() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl.reAuthorizeExistingAuthResource(null, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutAuthID() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - null, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutUserID() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - sampleID, null, ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutCurrentConsentStatus() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutApplicableConsentStatus() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutNewConsentStatus() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesWithoutAccountsAndPermissionsMap() throws Exception { - - Assert.assertTrue(consentCoreServiceImpl - .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>(), ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - consentCoreServiceImpl.reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesDataInsertError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleConsentMappingResourcesList(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST)) - .when(mockedConsentCoreDAO).getConsentMappingResources(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - consentCoreServiceImpl.reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeExistingAuthResourcesDataUpdateError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleConsentMappingResourcesList(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST)) - .when(mockedConsentCoreDAO).getConsentMappingResources(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), Mockito.anyObject(), - Mockito.anyString()); - consentCoreServiceImpl.reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - } - - @Test - public void storeConsentAttributes() throws Exception { - - consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void storeConsentAttributesWithoutParameters() throws Exception { - - consentCoreServiceImpl.storeConsentAttributes(null, null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void storeConsentAttributesWithoutConsentId() throws Exception { - - consentCoreServiceImpl.storeConsentAttributes(null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void storeConsentAttributesWithoutAttributeMap() throws Exception { - - consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, - null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void storeConsentAttributesEmptyAttributeMap() throws Exception { - - consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void storeConsentAttributesDataInsertError() throws Exception { - - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentAttributes(Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - } - - @Test - public void testGetConsentAttributesWithAttributeKeys() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentAttributesObject(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).getConsentAttributes(Mockito.any(), Mockito.anyString(), - Mockito.anyObject()); - ConsentAttributes consentAttributes = - consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - Assert.assertNotNull(consentAttributes); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAttributesWithoutConsentID() throws Exception { - - consentCoreServiceImpl.getConsentAttributes(null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAttributesDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentAttributes(Mockito.any(), Mockito.anyString()); - consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, new ArrayList<>()); - } - - @Test - public void testGetConsentAttributes() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentAttributesObject(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).getConsentAttributes(Mockito.any(), Mockito.anyString()); - ConsentAttributes consentAttributes = - consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - Assert.assertNotNull(consentAttributes); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAttributesWithoutAttributeKeys() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentAttributes(Mockito.any(), Mockito.anyString()); - consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAttributesWithoutAttributesWithoutConsentID() throws Exception { - - consentCoreServiceImpl.getConsentAttributes(null); - } - - @Test - public void testGetConsentAttributesByName() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP) - .when(mockedConsentCoreDAO).getConsentAttributesByName(Mockito.any(), Mockito.anyString()); - Map retrievedAttributesMap = - consentCoreServiceImpl.getConsentAttributesByName("x-request-id"); - Assert.assertTrue(retrievedAttributesMap.containsKey("x-request-id")); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAttributesByNameWithoutAttributeName() throws Exception { - - consentCoreServiceImpl.getConsentAttributesByName(null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAttributesByNameDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentAttributesByName(Mockito.any(), Mockito.anyString()); - consentCoreServiceImpl.getConsentAttributesByName("x-request-id"); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentIdByConsentAttributeNameAndValueWithoutAttributeName() throws Exception { - - consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue(null, - "domestic-payments"); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentIdByConsentAttributeNameAndValueWithoutAttributeValues() throws Exception { - - consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue("payment-type", - null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentIdByConsentAttributeNameAndValueDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentIdByConsentAttributeNameAndValue(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue("payment-type", - "domestic-payments"); - } - - @Test - public void testGetConsentIdByConsentAttributeNameAndValue() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.SAMPLE_CONSENT_IS_ARRAY) - .when(mockedConsentCoreDAO).getConsentIdByConsentAttributeNameAndValue(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - ArrayList consentIdList = consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue( - "payment-type", "domestic-payments"); - Assert.assertFalse(consentIdList.isEmpty()); - } - - @Test - public void testGetConsentFile() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT)) - .when(mockedConsentCoreDAO).getConsentFile(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - ConsentFile consentFile = consentCoreServiceImpl - .getConsentFile(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - Assert.assertNotNull(consentFile); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentFileWithoutConsentID() throws Exception { - - consentCoreServiceImpl.getConsentFile(null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentFileDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - consentCoreServiceImpl.getConsentFile(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - } - - @Test - public void testGetAuthorizationResource() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) - .when(mockedConsentCoreDAO).getAuthorizationResource(Mockito.any(), Mockito.anyString()); - AuthorizationResource authorizationResource = - consentCoreServiceImpl.getAuthorizationResource(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource().getAuthorizationID()); - Assert.assertNotNull(authorizationResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetAuthorizationResourceWithoutAuthID() throws Exception { - - consentCoreServiceImpl.getAuthorizationResource(null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetAuthorizationResourceDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getAuthorizationResource(Mockito.any(), Mockito.anyString()); - consentCoreServiceImpl.getAuthorizationResource(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource().getAuthorizationID()); - } - - @Test - public void testSearchConsentStatusAuditRecords() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleStoredTestConsentStatusAuditRecordsList(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).getConsentStatusAuditRecords(Mockito.any(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString(), - Mockito.anyBoolean()); - ArrayList consentStatusAuditRecords = - consentCoreServiceImpl.searchConsentStatusAuditRecords(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_ACTION_BY, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_AUDIT_ID); - Assert.assertNotNull(consentStatusAuditRecords); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSearchConsentStatusAuditRecordsDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecords(Mockito.any(), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString(), - Mockito.anyBoolean()); - consentCoreServiceImpl.searchConsentStatusAuditRecords(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_ACTION_BY, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, ConsentMgtServiceTestData.SAMPLE_AUDIT_ID); - } - - @Test - public void testSearchAuthorizations() throws Exception { - - ArrayList consentIDs = new ArrayList<>(); - consentIDs.add(UUID.randomUUID().toString()); - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleAuthorizationResourcesList(consentIDs)) - .when(mockedConsentCoreDAO).searchConsentAuthorizations(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - ArrayList retrievedAuthorizations = - consentCoreServiceImpl.searchAuthorizations(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - Assert.assertNotNull(retrievedAuthorizations); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSearchAuthorizationsDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsentAuthorizations(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.searchAuthorizations(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test - public void testDeleteConsentAttributes() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(Mockito.any(), - Mockito.anyString(), Mockito.anyObject()); - consentCoreServiceImpl.deleteConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testDeleteConsentAttributesDeleteError() throws Exception { - - Mockito.doThrow(OBConsentDataDeletionException.class) - .when(mockedConsentCoreDAO).deleteConsentAttributes(Mockito.any(), Mockito.anyString(), - Mockito.anyObject()); - consentCoreServiceImpl.deleteConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testDeleteConsentAttributesWithoutConsentID() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(Mockito.any(), - Mockito.anyString(), Mockito.anyObject()); - consentCoreServiceImpl.deleteConsentAttributes(null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testDeleteConsentAttributesWithoutAttributeKeysList() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(Mockito.any(), - Mockito.anyString(), Mockito.anyObject()); - consentCoreServiceImpl.deleteConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - null); - } - - @Test - public void testReAuthorizeConsentWithNewAuthResource() throws Exception { - - AuthorizationResource authorizationResource = ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(sampleID); - ArrayList consentIDs = new ArrayList<>(); - consentIDs.add(sampleID); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleAuthorizationResourcesList(consentIDs)) - .when(mockedConsentCoreDAO).searchConsentAuthorizations(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(authorizationResource) - .when(mockedConsentCoreDAO).updateAuthorizationStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(authorizationResource).when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), - Mockito.anyObject()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(sampleID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceDataRetrieveError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).searchConsentAuthorizations(Mockito.any(), Mockito.any(), Mockito.any()); - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceDataUpdateError() throws Exception { - - ArrayList consentIDs = new ArrayList<>(); - consentIDs.add(sampleID); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleAuthorizationResourcesList(consentIDs)) - .when(mockedConsentCoreDAO).searchConsentAuthorizations(Mockito.any(), Mockito.any(), Mockito.any()); - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateAuthorizationStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceDataInsertError() throws Exception { - - AuthorizationResource authorizationResource = ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(sampleID); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) - .when(mockedConsentCoreDAO).searchConsents(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt()); - Mockito.doReturn(authorizationResource) - .when(mockedConsentCoreDAO).updateAuthorizationStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - Mockito.doReturn(authorizationResource).when(mockedConsentCoreDAO).storeAuthorizationResource(Mockito.any(), - Mockito.anyObject()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutConsentID() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(null, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutUserID() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, null, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutAccountsMap() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutCurrentConsentStatus() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, null, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutNewConsentStatus() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutNewExistingAuthStatus() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutNewAuthStatus() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - null, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testReAuthorizeConsentWithNewAuthResourceWithoutNewAuthType() throws Exception { - - consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, null); - } - - private void mockStaticClasses() throws ConsentManagementException, IdentityOAuth2Exception { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(Mockito.mock(Connection.class)); - PowerMockito.when(DatabaseUtil.getRetentionDBConnection()).thenReturn(Mockito.mock(Connection.class)); - - PowerMockito.mockStatic(ConsentStoreInitializer.class); - PowerMockito.when(ConsentStoreInitializer.getInitializedConsentCoreDAOImpl()).thenReturn(mockedConsentCoreDAO); - PowerMockito.when(ConsentStoreInitializer - .getInitializedConsentRetentionDAOImpl()).thenReturn(mockedConsentCoreDAO); - - PowerMockito.mockStatic(ConsentManagementDataHolder.class); - PowerMockito.when(ConsentManagementDataHolder.getInstance()).thenReturn(consentManagementDataHolderMock); - - PowerMockito.when(consentManagementDataHolderMock.getOBEventQueue()).thenReturn(obEventQueueMock); - - AccessTokenDAOImpl accessTokenDAOMock = Mockito.mock(AccessTokenDAOImpl.class); - Mockito.doNothing().when(accessTokenDAOMock).revokeAccessTokens(Mockito.any(String[].class)); - PowerMockito.when(consentManagementDataHolderMock.getAccessTokenDAO()).thenReturn(accessTokenDAOMock); - - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Map configuration = new HashMap<>(); - configuration.put(OpenBankingConstants.CONSENT_ID_CLAIM_NAME, "OB_CONSENT_ID"); - Mockito.when(openBankingConfigParserMock.getConfiguration()).thenReturn(configuration); - Mockito.when(openBankingConfigParserMock.isConsentDataRetentionEnabled()).thenReturn(true); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - } - - @Test - public void testAmendConsentData() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - ConsentResource consentResource = - consentCoreServiceImpl.amendConsentData(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - - Assert.assertNotNull(consentResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendConsentDataWithoutConsentID() throws Exception { - - consentCoreServiceImpl.amendConsentData(null, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - - } - - @Test - public void testAmendConsentValidityPeriod() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - ConsentResource consentResource = - consentCoreServiceImpl.amendConsentData(sampleID, null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - - Assert.assertNotNull(consentResource); - } - - @Test - public void testAmendConsentReceipt() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - ConsentResource consentResource = - consentCoreServiceImpl.amendConsentData(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - null, ConsentMgtServiceTestData.SAMPLE_USER_ID); - - Assert.assertNotNull(consentResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendConsentDataWithoutReceiptAndValidityTime() throws Exception { - - consentCoreServiceImpl.amendConsentData(sampleID, null, null, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendConsentDataUpdateError() throws Exception { - - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.amendConsentData(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendConsentDataRetrieveError() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - - consentCoreServiceImpl.amendConsentData(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendConsentDataInsertError() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.amendConsentData(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test - public void testUpdateConsentStatus() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateConsentStatusDataRetrievalError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateConsentStatusDataInsertError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyObject(), - Mockito.anyObject()); - - consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateConsentStatusDataUpdateError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateConsentStatus(Mockito.any(), Mockito.anyObject(), - Mockito.anyObject()); - - consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateConsentStatusWithoutConsentId() throws Exception { - - consentCoreServiceImpl.updateConsentStatus(null, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateConsentStatusWithoutUserId() throws Exception { - - consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateConsentStatusWithoutConsentStatus() throws Exception { - - consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, - null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentsEligibleForExpirationDataRetrievalError() throws Exception { - - Mockito.doThrow(new OBConsentDataRetrievalException("Error")) - .when(mockedConsentCoreDAO).getExpiringConsents(Mockito.any(), Mockito.anyString()); - ArrayList consentsEligibleForExpiration = - consentCoreServiceImpl.getConsentsEligibleForExpiration("authorised"); - - Assert.assertTrue(!consentsEligibleForExpiration.isEmpty()); - Assert.assertEquals(consentsEligibleForExpiration.get(0).getConsentID(), - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList().get(0).getConsentID()); - } - - @Test - public void testGetConsentsEligibleForExpiration() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) - .when(mockedConsentCoreDAO).getExpiringConsents(Mockito.any(), Mockito.anyString()); - ArrayList consentsEligibleForExpiration = - consentCoreServiceImpl.getConsentsEligibleForExpiration("authorised"); - - Assert.assertTrue(!consentsEligibleForExpiration.isEmpty()); - Assert.assertEquals(consentsEligibleForExpiration.get(0).getConsentID(), - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList().get(0).getConsentID()); - } - - @Test - public void testRevokeConsentWithoutReason() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( - retrievedDetailedConsentResource.getConsentID(), - retrievedDetailedConsentResource.getCurrentStatus())) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.anyString()); - - boolean isConsentRevoked = new MockConsentCoreServiceImpl() - .revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - - Assert.assertTrue(isConsentRevoked); - } - - @Test (priority = 1) - public void testRevokeConsentWithUserIDWithoutReason() throws Exception { - - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - Mockito.doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentResource()).when(mockedConsentCoreDAO) - .updateConsentStatus(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( - retrievedDetailedConsentResource.getConsentID(), - retrievedDetailedConsentResource.getCurrentStatus())) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.any(), Mockito.anyString()); - - boolean isConsentRevoked = new MockConsentCoreServiceImpl() - .revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID); - - Assert.assertTrue(isConsentRevoked); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateAuthorizationStatusWithoutAuthId() throws Exception { - - consentCoreServiceImpl.updateAuthorizationStatus(null, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateAuthorizationStatusWithoutNewAuthStatus() throws Exception { - - consentCoreServiceImpl.updateAuthorizationStatus(ConsentMgtServiceTestData.CONSENT_ID, - null); - } - - @Test - public void testUpdateAuthorizationStatus() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).updateAuthorizationStatus(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.updateAuthorizationStatus(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateAuthorizationUserWithoutAuthorizationID() throws Exception { - - consentCoreServiceImpl.updateAuthorizationUser(null, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testUpdateAuthorizationUserWithoutUserID() throws Exception { - - consentCoreServiceImpl.updateAuthorizationUser(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, - null); - } - - @Test - public void testUpdateAuthorizationUser() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) - .when(mockedConsentCoreDAO).updateAuthorizationUser(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.updateAuthorizationUser(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, - ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - private void setInitialDataForAmendDetailedConsentSuccessFlow() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - - Mockito.doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(Mockito.any(), - Mockito.anyString(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(Mockito.any(), - Mockito.anyObject()); - } - - @Test - public void testAmendDetailedConsentData() throws Exception { - - setInitialDataForAmendDetailedConsentSuccessFlow(); - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - - Assert.assertNotNull(detailedConsentResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutConsentID() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(null, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test - public void testAmendDetailedConsentDataWithoutReceiptOnly() throws Exception { - - setInitialDataForAmendDetailedConsentSuccessFlow(); - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - null, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - - Assert.assertNotNull(detailedConsentResource); - } - - @Test - public void testAmendDetailedConsentDataWithoutValidityTimeOnly() throws Exception { - - setInitialDataForAmendDetailedConsentSuccessFlow(); - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.amendDetailedConsent(sampleID, null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - - Assert.assertNotNull(detailedConsentResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutReceiptAndValidityTime() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(sampleID, null, null, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutUserId() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, null, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutAuthId() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, null, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutNewConsentStatus() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, null, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutNewConsentAttributes() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithoutAccountIdMapWithPermissions() throws Exception { - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - null, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test - public void testAmendDetailedConsentDataWithAdditionalAmendmentData() throws Exception { - - setInitialDataForAmendDetailedConsentSuccessFlow(); - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(new ConsentMappingResource()).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - - DetailedConsentResource detailedConsentResource = - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.getSampleAdditionalConsentAmendmentDataMap()); - - Assert.assertNotNull(detailedConsentResource); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithAdditionalAmendmentDataWithoutConsentIdInAuthResources() - throws Exception { - - setInitialDataForAmendDetailedConsentSuccessFlow(); - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.getSampleAdditionalConsentAmendmentDataMapWithoutConsentId()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataWithAdditionalAmendmentDataWithoutAccountIdInMappingResources() - throws Exception { - - setInitialDataForAmendDetailedConsentSuccessFlow(); - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - ConsentMgtServiceTestData.getSampleAdditionalConsentAmendmentDataMapWithoutAccountId()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataUpdateError() throws Exception { - - Mockito.doThrow(OBConsentDataUpdationException.class) - .when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), Mockito.anyString(), - Mockito.anyString()); - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataRetrieveError() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataInsertError() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testAmendDetailedConsentDataDeletionError() throws Exception { - - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentReceipt(Mockito.any(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentValidityTime(Mockito.any(), - Mockito.anyString(), Mockito.anyLong()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getConsentResource(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) - .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(Mockito.any(), Mockito.anyObject()); - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - Mockito.doReturn(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) - .when(mockedConsentCoreDAO).storeConsentMappingResource(Mockito.any(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).updateConsentMappingStatus(Mockito.any(), - Mockito.anyObject(), Mockito.anyString()); - - Mockito.doThrow(OBConsentDataDeletionException.class).when(mockedConsentCoreDAO) - .deleteConsentAttributes(Mockito.any(), Mockito.anyString(), Mockito.anyObject()); - Mockito.doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(Mockito.any(), - Mockito.anyObject()); - consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, - ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, - ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, - ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, - ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, - ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, - ConsentMgtServiceTestData.SAMPLE_USER_ID, - new HashMap<>()); - } - - @Test - public void testStoreConsentAmendmentHistory() throws Exception { - - boolean result = consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, - ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), - ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); - - Assert.assertNotNull(result); - } - - @Test - public void testStoreConsentAmendmentHistoryWithoutPassingCurrentConsent() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - ConsentHistoryResource consentHistoryResource = - new ConsentHistoryResource(); - consentHistoryResource.setTimestamp(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP); - consentHistoryResource.setReason(ConsentMgtServiceTestData.SAMPLE_AMENDMENT_REASON); - consentHistoryResource.setDetailedConsentResource(ConsentMgtServiceTestData - .getSampleDetailedStoredTestCurrentConsentResource()); - - boolean result = consentCoreServiceImpl.storeConsentAmendmentHistory( - ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - consentHistoryResource, null); - - Assert.assertNotNull(result); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testStoreConsentAmendmentHistoryWithoutConsentID() throws Exception { - - consentCoreServiceImpl.storeConsentAmendmentHistory(null, - ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), - ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testStoreConsentAmendmentHistoryWithoutConsentHistoryResource() throws Exception { - - consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, - null, - ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testStoreConsentAmendmentHistoryWithZeroAsConsentAmendedTimestamp() throws Exception { - - ConsentHistoryResource consentHistoryResource = ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(); - consentHistoryResource.setTimestamp(0); - consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, consentHistoryResource, - ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testStoreConsentAmendmentHistoryWithoutConsentAmendedReason() throws Exception { - - ConsentHistoryResource consentHistoryResource = ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(); - consentHistoryResource.setReason(null); - consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, - consentHistoryResource, - ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testStoreConsentAmendmentHistoryDataInsertError() throws Exception { - - Mockito.doThrow(OBConsentDataInsertionException.class) - .when(mockedConsentCoreDAO).storeConsentAmendmentHistory(Mockito.any(), Mockito.anyString(), - Mockito.anyLong(), Mockito.anyString(), Mockito.anyString(), Mockito.anyObject(), Mockito.anyString()); - - consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, - ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), - ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testStoreConsentAmendmentHistoryDataRetrievalError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, - ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), null); - } - - @Test () - public void testGetConsentAmendmentHistoryData() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentHistoryDataMap()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - Map consentAmendmentHistory = - consentCoreServiceImpl.getConsentAmendmentHistoryData(sampleID); - - Assert.assertTrue(consentAmendmentHistory.containsKey(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - Assert.assertNotNull(consentAmendmentHistory.get(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - } - - @Test - public void testGetConsentAmendmentHistoryDataWithOnlyBasicConsentData() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleConsentHistoryBasicConsentDataMap()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - Map consentAmendmentHistory = - consentCoreServiceImpl.getConsentAmendmentHistoryData(sampleID); - - Assert.assertTrue(consentAmendmentHistory.containsKey(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - Assert.assertNotNull(consentAmendmentHistory.get(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - } - - @Test - public void testGetConsentAmendmentHistoryDataWithOnlyConsentAttributesData() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleConsentHistoryConsentAttributesDataMap()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - Map consentAmendmentHistory = - consentCoreServiceImpl.getConsentAmendmentHistoryData(sampleID); - - Assert.assertTrue(consentAmendmentHistory.containsKey(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - Assert.assertNotNull(consentAmendmentHistory.get(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - } - - @Test - public void testGetConsentAmendmentHistoryDataWithOnlyConsentMappingsData() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleConsentHistoryConsentMappingsDataMap()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - Map consentAmendmentHistory = - consentCoreServiceImpl.getConsentAmendmentHistoryData(sampleID); - - Assert.assertTrue(consentAmendmentHistory.containsKey(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - Assert.assertNotNull(consentAmendmentHistory.get(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID)); - } - - @Test - public void testGetConsentAmendmentHistoryDataWithNoConsentHistoryEntries() throws Exception { - - Mockito.doReturn(new HashMap<>()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - Map consentAmendmentHistory = - consentCoreServiceImpl.getConsentAmendmentHistoryData(sampleID); - - Assert.assertEquals(0, consentAmendmentHistory.size()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAmendmentHistoryDataWithoutConsentID() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentHistoryDataMap()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - consentCoreServiceImpl.getConsentAmendmentHistoryData(null); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentAmendmentHistoryDataRetrieveError() throws Exception { - - Mockito.doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentHistoryDataMap()) - .when(mockedConsentCoreDAO).retrieveConsentAmendmentHistory(Mockito.any(), any(ArrayList.class)); - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getDetailedConsentResource(Mockito.any(), Mockito.anyString(), - Mockito.anyBoolean()); - - consentCoreServiceImpl.getConsentAmendmentHistoryData(sampleID); - } - - @Test - public void testRevokeTokensByClientId() throws Exception { - MockConsentCoreServiceImpl mockConsentCoreService = new MockConsentCoreServiceImpl(); - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - mockConsentCoreService.revokeTokens( - retrievedDetailedConsentResource, ConsentMgtServiceTestData.SAMPLE_USER_ID); - } - - @Test - public void testRevokeTokensByClientIdError() { - MockConsentCoreServiceImplTokenError mockedConsentCoreServiceImplTokenError = - new MockConsentCoreServiceImplTokenError(); - DetailedConsentResource retrievedDetailedConsentResource = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - try { - mockedConsentCoreServiceImplTokenError.revokeTokens( - retrievedDetailedConsentResource, ConsentMgtServiceTestData.SAMPLE_USER_ID); - } catch (Exception e) { - Assert.assertTrue(e instanceof IdentityOAuth2Exception); - } - } - - @Test - public void testSyncRetentionDatabaseWithPurgedConsent() throws Exception { - - DetailedConsentResource detailedConsent = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - ArrayList consentIds = new ArrayList<>(); - ArrayList consentStatusAuditRecords = new ArrayList<>(); - consentStatusAuditRecords.add(new ConsentStatusAuditRecord()); - consentIds.add(detailedConsent.getConsentID()); - - Mockito.doReturn(consentIds).when(mockedConsentCoreDAO) - .getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(detailedConsent).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(null).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), any(AuthorizationResource.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentAttributes(Mockito.any(), any(ConsentAttributes.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentFile(Mockito.any(), any(ConsentFile.class)); - Mockito.doReturn(new ConsentMappingResource()).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), any(ConsentMappingResource.class)); - Mockito.doReturn(new ConsentStatusAuditRecord()).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), any(ConsentStatusAuditRecord.class)); - Mockito.doReturn(new ConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), any(ConsentResource.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .deleteConsentData(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - - Assert.assertTrue(consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSyncRetentionDatabaseWithPurgedConsentRetentionDisabled() throws Exception { - - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.when(openBankingConfigParserMock.isConsentDataRetentionEnabled()).thenReturn(false); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent(); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testSyncRetentionDatabaseWithPurgedConsentConsentListError() throws Exception { - - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent(); - } - - @Test - public void testSyncRetentionDatabaseWithPurgedConsentFileGetError() throws Exception { - - DetailedConsentResource detailedConsent = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - ArrayList consentIds = new ArrayList<>(); - consentIds.add(detailedConsent.getConsentID()); - - Mockito.doReturn(consentIds).when(mockedConsentCoreDAO) - .getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(detailedConsent).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doThrow(OBConsentDataRetrievalException.class) - .when(mockedConsentCoreDAO).getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doThrow(OBConsentDataRetrievalException.class).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), any(AuthorizationResource.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentAttributes(Mockito.any(), any(ConsentAttributes.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentFile(Mockito.any(), any(ConsentFile.class)); - Mockito.doReturn(new ConsentMappingResource()).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), any(ConsentMappingResource.class)); - Mockito.doReturn(new ConsentStatusAuditRecord()).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), any(ConsentStatusAuditRecord.class)); - Mockito.doReturn(new ConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), any(ConsentResource.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .deleteConsentData(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Assert.assertTrue(consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent()); - } - - @Test - public void testSyncRetentionDatabaseWithPurgedConsentFileStoreError() throws Exception { - - DetailedConsentResource detailedConsent = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - ArrayList consentIds = new ArrayList<>(); - ArrayList consentStatusAuditRecords = new ArrayList<>(); - consentStatusAuditRecords.add(new ConsentStatusAuditRecord()); - consentIds.add(detailedConsent.getConsentID()); - - Mockito.doReturn(consentIds).when(mockedConsentCoreDAO) - .getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(detailedConsent).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(new ConsentFile()).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - - Mockito.doReturn(new ConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), any(ConsentResource.class)); - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), any(AuthorizationResource.class)); - Mockito.doReturn(new ConsentMappingResource()).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), any(ConsentMappingResource.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentAttributes(Mockito.any(), any(ConsentAttributes.class)); - Mockito.doReturn(false).when(mockedConsentCoreDAO) - .storeConsentFile(Mockito.any(), any(ConsentFile.class)); - - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .deleteConsentData(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Assert.assertTrue(consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent()); - } - - @Test - public void testSyncRetentionDatabaseWithPurgedConsentAuditStoreError() throws Exception { - - DetailedConsentResource detailedConsent = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - ArrayList consentIds = new ArrayList<>(); - ArrayList consentStatusAuditRecords = new ArrayList<>(); - consentStatusAuditRecords.add(new ConsentStatusAuditRecord()); - consentIds.add(detailedConsent.getConsentID()); - - Mockito.doReturn(consentIds).when(mockedConsentCoreDAO) - .getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(detailedConsent).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(new ConsentFile()).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - - Mockito.doReturn(new ConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), any(ConsentResource.class)); - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), any(AuthorizationResource.class)); - Mockito.doReturn(new ConsentMappingResource()).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), any(ConsentMappingResource.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentAttributes(Mockito.any(), any(ConsentAttributes.class)); - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .storeConsentFile(Mockito.any(), any(ConsentFile.class)); - Mockito.doReturn(null).when(mockedConsentCoreDAO) - .storeConsentStatusAuditRecord(Mockito.any(), any(ConsentStatusAuditRecord.class)); - - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .deleteConsentData(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Assert.assertTrue(consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent()); - } - - @Test - public void testSyncRetentionDatabaseWithPurgedConsentAttributeStoreError() throws Exception { - - DetailedConsentResource detailedConsent = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - ArrayList consentIds = new ArrayList<>(); - ArrayList consentStatusAuditRecords = new ArrayList<>(); - consentStatusAuditRecords.add(new ConsentStatusAuditRecord()); - consentIds.add(detailedConsent.getConsentID()); - - Mockito.doReturn(consentIds).when(mockedConsentCoreDAO) - .getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(detailedConsent).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(new ConsentFile()).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - - Mockito.doReturn(new ConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), any(ConsentResource.class)); - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), any(AuthorizationResource.class)); - Mockito.doReturn(new ConsentMappingResource()).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), any(ConsentMappingResource.class)); - Mockito.doReturn(false).when(mockedConsentCoreDAO) - .storeConsentAttributes(Mockito.any(), any(ConsentAttributes.class)); - - Assert.assertTrue(consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent()); - } - - @Test - public void testSyncRetentionDatabaseWithPurgedConsentMappingStoreError() throws Exception { - - DetailedConsentResource detailedConsent = - ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); - - ArrayList consentIds = new ArrayList<>(); - ArrayList consentStatusAuditRecords = new ArrayList<>(); - consentStatusAuditRecords.add(new ConsentStatusAuditRecord()); - consentIds.add(detailedConsent.getConsentID()); - - Mockito.doReturn(consentIds).when(mockedConsentCoreDAO) - .getListOfConsentIds(Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(detailedConsent).when(mockedConsentCoreDAO) - .getDetailedConsentResource(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(new ConsentFile()).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - - Mockito.doReturn(new ConsentResource()).when(mockedConsentCoreDAO) - .storeConsentResource(Mockito.any(), any(ConsentResource.class)); - Mockito.doReturn(new AuthorizationResource()).when(mockedConsentCoreDAO) - .storeAuthorizationResource(Mockito.any(), any(AuthorizationResource.class)); - Mockito.doReturn(null).when(mockedConsentCoreDAO) - .storeConsentMappingResource(Mockito.any(), any(ConsentMappingResource.class)); - - Mockito.doReturn(true).when(mockedConsentCoreDAO) - .deleteConsentData(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - Assert.assertTrue(consentCoreServiceImpl.syncRetentionDatabaseWithPurgedConsent()); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentFileError() throws Exception { - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.when(openBankingConfigParserMock.isConsentDataRetentionEnabled()).thenReturn(false); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - consentCoreServiceImpl.getConsentFile("3d22259e-942c-46b8-8f75-a608c677a6e6", true); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentFileErrorRetentionData() throws Exception { - consentCoreServiceImpl.getConsentFile("", true); - } - - @Test - public void testGetConsentFileRetentionDataSuccess() throws Exception { - - Mockito.doReturn(new ConsentFile()).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - ConsentFile consentFile = consentCoreServiceImpl.getConsentFile("3d22259e-942c-46b8-8f75-a608c677a6e6", - true); - Assert.assertNotNull(consentFile); - } - - @Test - public void testGetConsentFileConsentData() throws Exception { - - Mockito.doReturn(new ConsentFile()).when(mockedConsentCoreDAO) - .getConsentFile(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()); - ConsentFile consentFile = consentCoreServiceImpl.getConsentFile("3d22259e-942c-46b8-8f75-a608c677a6e6", - false); - Assert.assertNotNull(consentFile); - } - - @Test - public void testGetConsentStatusAuditRecords() throws Exception { - - ArrayList consentStatusAuditRecords = new ArrayList<>(); - ArrayList consentIds = new ArrayList<>(); - - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - ArrayList statusAuditRecords = - consentCoreServiceImpl.getConsentStatusAuditRecords(consentIds, null, null, false); - Assert.assertNotNull(statusAuditRecords); - } - - @Test - public void testGetConsentStatusAuditRecordsInRetention() throws Exception { - - ArrayList consentStatusAuditRecords = new ArrayList<>(); - ArrayList consentIds = new ArrayList<>(); - - Mockito.doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) - .getConsentStatusAuditRecordsByConsentId(Mockito.any(), any(ArrayList.class), Mockito.anyInt(), - Mockito.anyInt(), Mockito.anyBoolean()); - ArrayList statusAuditRecords = - consentCoreServiceImpl.getConsentStatusAuditRecords(consentIds, null, null, true); - Assert.assertNotNull(statusAuditRecords); - } - - @Test (expectedExceptions = ConsentManagementException.class) - public void testGetConsentStatusAuditRecordsInRetentionError() throws Exception { - ArrayList consentIds = new ArrayList<>(); - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.when(openBankingConfigParserMock.isConsentDataRetentionEnabled()).thenReturn(false); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - consentCoreServiceImpl.getConsentStatusAuditRecords(consentIds, null, null, true); - } -} - -class MockConsentCoreServiceImpl extends ConsentCoreServiceImpl { - - @Override - OAuth2Service getOAuth2Service() { - - return Mockito.mock(OAuth2Service.class); - } - - @Override - AuthenticatedUser getAuthenticatedUser(String userID) { - - return Mockito.mock(AuthenticatedUser.class); - } - - @Override - Set getAccessTokenDOSet(DetailedConsentResource detailedConsentResource, - AuthenticatedUser authenticatedUser) { - - String[] scopes = {"OB_CONSENT_ID" + detailedConsentResource.getConsentID()}; - AccessTokenDO sampleAccessTokenDO = new AccessTokenDO(); - sampleAccessTokenDO.setScope(scopes); - sampleAccessTokenDO.setAccessToken("sample_token"); - - Set accessTokenDOS = new HashSet<>(); - accessTokenDOS.add(sampleAccessTokenDO); - - return accessTokenDOS; - } - - @Override - OAuthRevocationResponseDTO revokeTokenByClient(OAuth2Service oAuth2Service, - OAuthRevocationRequestDTO revocationRequestDTO) { - - return Mockito.mock(OAuthRevocationResponseDTO.class); - } -} - -class MockConsentCoreServiceImplTokenError extends ConsentCoreServiceImpl { - - @Override - OAuth2Service getOAuth2Service() { - - return Mockito.mock(OAuth2Service.class); - } - - @Override - AuthenticatedUser getAuthenticatedUser(String userID) { - - return Mockito.mock(AuthenticatedUser.class); - } - - @Override - Set getAccessTokenDOSet(DetailedConsentResource detailedConsentResource, - AuthenticatedUser authenticatedUser) { - - String[] scopes = {"OB_CONSENT_ID" + detailedConsentResource.getConsentID()}; - AccessTokenDO sampleAccessTokenDO = new AccessTokenDO(); - sampleAccessTokenDO.setScope(scopes); - sampleAccessTokenDO.setAccessToken("sample_token"); - - Set accessTokenDOS = new HashSet<>(); - accessTokenDOS.add(sampleAccessTokenDO); - - return accessTokenDOS; - } - - @Override - OAuthRevocationResponseDTO revokeTokenByClient(OAuth2Service oAuth2Service, - OAuthRevocationRequestDTO revocationRequestDTO) { - - OAuthRevocationResponseDTO errorResponse = new OAuthRevocationResponseDTO(); - errorResponse.setError(true); - errorResponse.setErrorMsg("Error occurred while revoking authorization grant for applications"); - return errorResponse; - } -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/service/util/ConsentMgtServiceTestData.java b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/service/util/ConsentMgtServiceTestData.java deleted file mode 100644 index 08a3eab8..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/java/com/wso2/openbanking/accelerator/consent/mgt/service/util/ConsentMgtServiceTestData.java +++ /dev/null @@ -1,823 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.mgt.service.util; - -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentAttributes; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentFile; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentHistoryResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentMappingResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; -import net.minidev.json.JSONObject; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.UUID; - -/** - * Test data fore consent management service. - */ -public class ConsentMgtServiceTestData { - - public static final String SAMPLE_CONSENT_RECEIPT = "{\"validUntil\": \"2020-10-20\", \"frequencyPerDay\": 1," + - " \"recurringIndicator\": false, \"combinedServiceIndicator\": true}"; - - public static final String SAMPLE_CONSENT_TYPE = "accounts"; - - public static final String SAMPLE_CLIENT_ID = "sampleClientID"; - - public static final int SAMPLE_CONSENT_FREQUENCY = 1; - - public static final Long SAMPLE_CONSENT_VALIDITY_PERIOD = 1638337852L; - - public static final long SAMPLE_CONSENT_AMENDMENT_TIMESTAMP = 1638337852; - - public static final String UNMATCHED_CONSENT_ID = "2222"; - - public static final String UNMATCHED_AUTHORIZATION_ID = "3333"; - - public static final String SAMPLE_MAPPING_ID = "sampleMappingId"; - - public static final String SAMPLE_MAPPING_ID_2 = "sampleMappingId2"; - - public static final String SAMPLE_AUTHORIZATION_ID_1 = "88888"; - - public static final String SAMPLE_AUTHORIZATION_ID_2 = "99999"; - - public static final boolean SAMPLE_RECURRING_INDICATOR = true; - - public static final String SAMPLE_CURRENT_STATUS = "Authorized"; - - public static final String AWAITING_UPLOAD_STATUS = "awaitingUpload"; - - public static final String SAMPLE_PREVIOUS_STATUS = "Received"; - - public static final String SAMPLE_AUTHORIZATION_TYPE = "authorizationType"; - - public static final String CONSENT_ID = "464ef174-9877-4c71-940c-93d6e069eaf9"; - - public static final String SAMPLE_USER_ID = "admin@wso2.com"; - - public static final String SAMPLE_AUDIT_ID = "4321234"; - - public static final String SAMPLE_NEW_USER_ID = "ann@gold.com"; - - public static final String SAMPLE_AUTHORIZATION_STATUS = "awaitingAuthorization"; - - public static final String SAMPLE_ACCOUNT_ID = "123456789"; - - public static final String SAMPLE_MAPPING_STATUS = "active"; - - public static final String SAMPLE_NEW_MAPPING_STATUS = "inactive"; - - public static final String SAMPLE_PERMISSION = "samplePermission"; - - public static final String SAMPLE_REASON = "sample reason"; - - public static final String SAMPLE_ACTION_BY = "admin@wso2.com"; - - public static final String SAMPLE_CONSUMED_STATUS = "Consumed"; - - public static final String SAMPLE_AMENDMENT_REASON = "sampleReason"; - - public static final String SAMPLE_CONSENT_HISTORY_RECEIPT = "{\"validUntil\": \"2020-10-20\", " + - "\"frequencyPerDay\": 5, \"recurringIndicator\": true, \"combinedServiceIndicator\": true}"; - - public static final Long SAMPLE_CONSENT_HISTORY_VALIDITY_PERIOD = 1538337852L; - - public static final long SAMPLE_CONSENT_HISTORY_AMENDMENT_TIMESTAMP = 1538337852; - - public static final String SAMPLE_HISTORY_ID = "sampleHistoryID"; - - public static final Map SAMPLE_CONSENT_ATTRIBUTES_MAP = new HashMap() { - { - put("x-request-id", UUID.randomUUID().toString()); - put("idenpotency-key", UUID.randomUUID().toString()); - put("sampleAttributeKey", "sampleAttributeValue"); - - } - }; - - public static final Map SAMPLE_CONSENT_HISTORY_ATTRIBUTES_MAP = new HashMap() { - { - put("sampleAttributeKey", "sampleAttributeValue"); - put("sampleAttributeKey2", "sampleAttributeValue2"); - put("idenpotency-key", UUID.randomUUID().toString()); - } - }; - - public static final Map> SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP = new HashMap>() { - { - put("accountID1", new ArrayList() { - { - add("permission1"); - add("permission2"); - } - }); - put("accountID2", new ArrayList() { - { - add("permission3"); - add("permission4"); - } - }); - } - }; - - public static final Map> SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP2 = new HashMap>() { - { - put(SAMPLE_ACCOUNT_ID, new ArrayList() { - { - add("permission5"); - add("permission6"); - } - }); - } - }; - - public static final Map> SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP3 = new HashMap>() { - { - put("mismatching account ID", new ArrayList() { - { - add("permission5"); - add("permission6"); - } - }); - } - }; - - public static final ArrayList SAMPLE_CONSENT_ATTRIBUTES_KEYS = new ArrayList() { - { - add("x-request-id"); - add("idenpotency-key"); - } - }; - - public static final ArrayList UNMATCHED_MAPPING_IDS = new ArrayList() { - { - add("4444"); - add("5555"); - } - }; - - public static final HashMap SAMPLE_MAPPING_ID_PERMISSION_MAP = new HashMap() {{ - put("mapping_id_1", "permission_1"); - put("mapping_id_2", "permission_2"); - }}; - - private static final ArrayList SAMPLE_CONSENT_RECEIPTS_LIST = new ArrayList() { - { - add("{\"element1\": \"value1\"}"); - add("{\"element2\": \"value2\"}"); - add("{\"element3\": \"value3\"}"); - } - }; - - public static final ArrayList SAMPLE_CONSENT_TYPES_LIST = new ArrayList() { - { - add("accounts"); - add("payments"); - add("cof"); - } - }; - - public static final ArrayList SAMPLE_CONSENT_STATUSES_LIST = new ArrayList() { - { - add("created"); - add("authorized"); - add("awaitingAuthorization"); - - } - }; - - public static final ArrayList SAMPLE_CLIENT_IDS_LIST = new ArrayList() { - { - add("clientID1"); - add("clientID2"); - add("clientID3"); - - } - }; - - public static final ArrayList SAMPLE_USER_IDS_LIST = new ArrayList() { - { - add("userID1"); - add("userID2"); - add("userID3"); - } - }; - - private static final ArrayList SAMPLE_VALIDITY_PERIOD_LIST = new ArrayList() { - { - add(1613454661L); - add(1623654661L); - add(1633654671L); - } - }; - - public static final ArrayList SAMPLE_ACCOUNT_ID_LIST = new ArrayList() { - { - add(SAMPLE_ACCOUNT_ID); - } - }; - - public static final ArrayList SAMPLE_CONSENT_IS_ARRAY = new ArrayList() { - { - add(CONSENT_ID); - } - }; - - public static final String SAMPLE_CONSENT_FILE = "sample file content"; - - public static ConsentResource getSampleTestConsentResource() { - - ConsentResource consentResource = new ConsentResource(); - consentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - consentResource.setClientID(UUID.randomUUID().toString()); - consentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - consentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - consentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - consentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - consentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - - return consentResource; - } - - public static ConsentResource getSampleStoredTestConsentResource() { - - ConsentResource consentResource = new ConsentResource(); - consentResource.setConsentID(UUID.randomUUID().toString()); - consentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - consentResource.setClientID(UUID.randomUUID().toString()); - consentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - consentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - consentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - consentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - consentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - - return consentResource; - } - - public static ArrayList getSampleAuthorizationResourcesList(ArrayList consentIDs) { - - ArrayList authorizationResources = new ArrayList<>(); - - for (int i = 0; i < consentIDs.size(); i++) { - for (int j = 0; j < 2; j++) { - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(consentIDs.get(i)); - authorizationResource.setAuthorizationType(SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(SAMPLE_USER_IDS_LIST.get(i)); - authorizationResource.setAuthorizationStatus(SAMPLE_AUTHORIZATION_STATUS); - authorizationResources.add(authorizationResource); - } - } - return authorizationResources; - } - - public static ArrayList getSampleConsentMappingResourcesList(ArrayList authIDs) { - - ArrayList consentMappingResources = new ArrayList<>(); - - for (int i = 0; i < authIDs.size(); i++) { - for (int j = 0; j < 2; j++) { - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setAuthorizationID(authIDs.get(i)); - consentMappingResource.setAccountID(SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(SAMPLE_MAPPING_STATUS); - consentMappingResources.add(consentMappingResource); - } - } - return consentMappingResources; - } - - public static DetailedConsentResource getSampleDetailedStoredTestConsentResource() { - - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - detailedConsentResource.setConsentID(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - detailedConsentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - detailedConsentResource.setClientID(UUID.randomUUID().toString()); - detailedConsentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - detailedConsentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - detailedConsentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - detailedConsentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - detailedConsentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - detailedConsentResource.setCreatedTime(System.currentTimeMillis() / 1000); - detailedConsentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - ArrayList authorizationResources = new ArrayList<>(); - authorizationResources.add(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1)); - - ArrayList consentMappingResources = new ArrayList<>(); - consentMappingResources.add(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource().getAuthorizationID())); - consentMappingResources.add(ConsentMgtServiceTestData - .getSampleTestInactiveConsentMappingResource(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource().getAuthorizationID())); - - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - return detailedConsentResource; - } - - public static DetailedConsentResource getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs() { - - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - detailedConsentResource.setConsentID(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - detailedConsentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - detailedConsentResource.setClientID(UUID.randomUUID().toString()); - detailedConsentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - detailedConsentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - detailedConsentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - detailedConsentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - detailedConsentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - detailedConsentResource.setCreatedTime(System.currentTimeMillis() / 1000); - detailedConsentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - ArrayList authorizationResources = new ArrayList<>(); - authorizationResources.add(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource()); - - ConsentMappingResource mappingResource1 = new ConsentMappingResource(); - mappingResource1.setAccountID(UUID.randomUUID().toString()); - - ConsentMappingResource mappingResource2 = new ConsentMappingResource(); - mappingResource2.setAccountID(UUID.randomUUID().toString()); - - ArrayList consentMappingResources = new ArrayList<>(); - consentMappingResources.add(mappingResource1); - consentMappingResources.add(mappingResource2); - - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - return detailedConsentResource; - } - - public static ArrayList getSampleDetailedStoredTestConsentResourcesList() { - - ArrayList detailedConsentResourcesList = new ArrayList<>(); - - for (int i = 0; i < 2; i++) { - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - detailedConsentResource.setConsentID(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); - detailedConsentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - detailedConsentResource.setClientID(UUID.randomUUID().toString()); - detailedConsentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - detailedConsentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - detailedConsentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - detailedConsentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - detailedConsentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - detailedConsentResource.setCreatedTime(System.currentTimeMillis() / 1000); - detailedConsentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - ArrayList authorizationResources = new ArrayList<>(); - authorizationResources.add(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource()); - - ArrayList consentMappingResources = new ArrayList<>(); - consentMappingResources.add(ConsentMgtServiceTestData - .getSampleTestConsentMappingResource(ConsentMgtServiceTestData - .getSampleStoredTestAuthorizationResource().getAuthorizationID())); - - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - detailedConsentResourcesList.add(detailedConsentResource); - } - return detailedConsentResourcesList; - } - - public static ConsentResource getSampleStoredTestConsentResourceWithAttributes() { - - ConsentResource consentResource = new ConsentResource(); - consentResource.setConsentID(UUID.randomUUID().toString()); - consentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - consentResource.setClientID(UUID.randomUUID().toString()); - consentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - consentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - consentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - consentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - consentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - consentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - return consentResource; - } - - public static AuthorizationResource getSampleTestAuthorizationResource(String consentID) { - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(consentID); - authorizationResource.setAuthorizationType(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(ConsentMgtServiceTestData.SAMPLE_USER_ID); - authorizationResource.setAuthorizationStatus(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - - return authorizationResource; - } - - public static AuthorizationResource getSampleTestAuthorizationResource(String consentID, String authorizationId) { - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(consentID); - authorizationResource.setAuthorizationID(authorizationId); - authorizationResource.setAuthorizationType(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(ConsentMgtServiceTestData.SAMPLE_USER_ID); - authorizationResource.setAuthorizationStatus(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - - return authorizationResource; - } - - public static AuthorizationResource getSampleStoredTestAuthorizationResource() { - - AuthorizationResource authorizationResource = new AuthorizationResource(); - authorizationResource.setConsentID(UUID.randomUUID().toString()); - authorizationResource.setAuthorizationID(UUID.randomUUID().toString()); - authorizationResource.setAuthorizationType(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_TYPE); - authorizationResource.setUserID(ConsentMgtServiceTestData.SAMPLE_USER_ID); - authorizationResource.setAuthorizationStatus(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); - authorizationResource.setUpdatedTime(System.currentTimeMillis() / 1000); - - return authorizationResource; - } - - public static ConsentMappingResource getSampleTestConsentMappingResource(String authorizationID) { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setMappingID(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID); - consentMappingResource.setAuthorizationID(authorizationID); - consentMappingResource.setAccountID(ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(ConsentMgtServiceTestData.SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); - - return consentMappingResource; - } - - public static ConsentMappingResource getSampleTestInactiveConsentMappingResource(String authorizationID) { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setMappingID(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2); - consentMappingResource.setAuthorizationID(authorizationID); - consentMappingResource.setAccountID(ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(ConsentMgtServiceTestData.SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_NEW_MAPPING_STATUS); - - return consentMappingResource; - } - - public static ConsentMappingResource getSampleTestConsentHistoryMappingResource(String authorizationID, - String mappingId) { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setMappingID(mappingId); - consentMappingResource.setAuthorizationID(authorizationID); - consentMappingResource.setAccountID(ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(ConsentMgtServiceTestData.SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_NEW_MAPPING_STATUS); - - return consentMappingResource; - } - - public static ConsentMappingResource getSampleStoredTestConsentMappingResource(String authorizationID) { - - ConsentMappingResource consentMappingResource = new ConsentMappingResource(); - consentMappingResource.setMappingID(UUID.randomUUID().toString()); - consentMappingResource.setAuthorizationID(authorizationID); - consentMappingResource.setAccountID(ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID); - consentMappingResource.setPermission(ConsentMgtServiceTestData.SAMPLE_PERMISSION); - consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); - - return consentMappingResource; - } - - public static ConsentStatusAuditRecord getSampleTestConsentStatusAuditRecord(String consentID, - String currentStatus) { - - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(consentID); - consentStatusAuditRecord.setCurrentStatus(currentStatus); - consentStatusAuditRecord.setReason(ConsentMgtServiceTestData.SAMPLE_REASON); - consentStatusAuditRecord.setActionBy(ConsentMgtServiceTestData.SAMPLE_ACTION_BY); - consentStatusAuditRecord.setPreviousStatus(ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); - - return consentStatusAuditRecord; - } - - public static ConsentStatusAuditRecord getSampleStoredTestConsentStatusAuditRecord(String sampleID, - String currentStatus) { - - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(sampleID); - consentStatusAuditRecord.setStatusAuditID(sampleID); - consentStatusAuditRecord.setCurrentStatus(currentStatus); - consentStatusAuditRecord.setReason(ConsentMgtServiceTestData.SAMPLE_REASON); - consentStatusAuditRecord.setActionBy(ConsentMgtServiceTestData.SAMPLE_ACTION_BY); - consentStatusAuditRecord.setPreviousStatus(ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); - consentStatusAuditRecord.setActionTime(System.currentTimeMillis() / 1000); - - return consentStatusAuditRecord; - } - - public static ArrayList getSampleStoredTestConsentStatusAuditRecordsList(String sampleID, - String currentStatus) { - - ArrayList consentStatusAuditRecords = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); - consentStatusAuditRecord.setConsentID(sampleID); - consentStatusAuditRecord.setStatusAuditID(sampleID); - consentStatusAuditRecord.setCurrentStatus(currentStatus); - consentStatusAuditRecord.setReason(ConsentMgtServiceTestData.SAMPLE_REASON); - consentStatusAuditRecord.setActionBy(ConsentMgtServiceTestData.SAMPLE_ACTION_BY); - consentStatusAuditRecord.setPreviousStatus(ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); - consentStatusAuditRecord.setActionTime(System.currentTimeMillis() / 1000); - } - return consentStatusAuditRecords; - } - - public static ConsentAttributes getSampleTestConsentAttributesObject(String consentID) { - - ConsentAttributes consentAttributes = new ConsentAttributes(); - consentAttributes.setConsentID(consentID); - consentAttributes.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - return consentAttributes; - } - - public static ConsentFile getSampleConsentFileObject(String fileContent) { - - ConsentFile consentFile = new ConsentFile(); - consentFile.setConsentID(UUID.randomUUID().toString()); - consentFile.setConsentFile(fileContent); - - return consentFile; - } - - public static ConsentHistoryResource getSampleTestConsentHistoryResource() { - - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setTimestamp(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP); - consentHistoryResource.setReason(ConsentMgtServiceTestData.SAMPLE_AMENDMENT_REASON); - consentHistoryResource.setDetailedConsentResource(getSampleDetailedConsentHistoryResource()); - - return consentHistoryResource; - } - - public static DetailedConsentResource getSampleDetailedConsentHistoryResource() { - - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - detailedConsentResource.setConsentID(ConsentMgtServiceTestData.CONSENT_ID); - detailedConsentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_HISTORY_RECEIPT); - detailedConsentResource.setClientID(UUID.randomUUID().toString()); - detailedConsentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - detailedConsentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); - detailedConsentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - detailedConsentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_HISTORY_VALIDITY_PERIOD); - detailedConsentResource.setUpdatedTime(ConsentMgtServiceTestData.SAMPLE_CONSENT_HISTORY_AMENDMENT_TIMESTAMP); - detailedConsentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - detailedConsentResource.setCreatedTime(System.currentTimeMillis() / 1000); - detailedConsentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_HISTORY_ATTRIBUTES_MAP); - - ArrayList authorizationResources = new ArrayList<>(); - authorizationResources.add(ConsentMgtServiceTestData.getSampleTestAuthorizationResource( - ConsentMgtServiceTestData.CONSENT_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1)); - - ArrayList consentMappingResources = new ArrayList<>(); - consentMappingResources.add(ConsentMgtServiceTestData - .getSampleTestConsentHistoryMappingResource(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, - ConsentMgtServiceTestData.SAMPLE_MAPPING_ID)); - - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - return detailedConsentResource; - } - - public static DetailedConsentResource getSampleDetailedStoredTestCurrentConsentResource() { - - DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); - detailedConsentResource.setConsentID(ConsentMgtServiceTestData.CONSENT_ID); - detailedConsentResource.setReceipt(ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - detailedConsentResource.setClientID(UUID.randomUUID().toString()); - detailedConsentResource.setConsentType(ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE); - detailedConsentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); - detailedConsentResource.setConsentFrequency(ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY); - detailedConsentResource.setValidityPeriod(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); - detailedConsentResource.setUpdatedTime(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP); - detailedConsentResource.setRecurringIndicator(ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR); - detailedConsentResource.setCreatedTime(System.currentTimeMillis() / 1000); - detailedConsentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); - - ArrayList authorizationResources = new ArrayList<>(); - authorizationResources.add(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1)); - authorizationResources.add(ConsentMgtServiceTestData - .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.CONSENT_ID, - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_2)); - - ArrayList consentMappingResources = new ArrayList<>(); - consentMappingResources.add(ConsentMgtServiceTestData - .getSampleTestConsentHistoryMappingResource(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, - ConsentMgtServiceTestData.SAMPLE_MAPPING_ID)); - - // new mapping that is not included in the previous state of the consent - consentMappingResources.add(ConsentMgtServiceTestData.getSampleTestConsentHistoryMappingResource( - ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2)); - - detailedConsentResource.setAuthorizationResources(authorizationResources); - detailedConsentResource.setConsentMappingResources(consentMappingResources); - - return detailedConsentResource; - } - - public static Map getSampleDetailedStoredTestConsentHistoryDataMap() { - - Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); - - Map changedAttributesJson = new HashMap<>(); - changedAttributesJson.put("ConsentData", getBasicConsentDataChangedAttributesJson()); - changedAttributesJson.put("ConsentAttributesData", getConsentAttributesDataChangedAttributesJson()); - - Map consentAuthResources = new HashMap<>(); - consentAuthResources.put(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, "null"); - changedAttributesJson.put("ConsentAuthResourceData", consentAuthResources); - - Map consentMappingResources = new HashMap<>(); - JSONObject consentMappingDataJson1 = new JSONObject(); - consentMappingDataJson1.put("MAPPING_STATUS", ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); - consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID, consentMappingDataJson1); - - JSONObject consentMappingDataJson2 = new JSONObject(); - consentMappingDataJson2.put("MAPPING_STATUS", ConsentMgtServiceTestData.SAMPLE_NEW_MAPPING_STATUS); - consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2, consentMappingDataJson2); - - consentMappingResources.put(UUID.randomUUID().toString(), "null"); - changedAttributesJson.put("ConsentMappingData", consentMappingResources); - - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); - consentHistoryResource.setReason("SampleReason"); - consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); - return consentAmendmentHistoryDataMap; - } - - private static String getBasicConsentDataChangedAttributesJson() { - - JSONObject consentBasicDataJson = new JSONObject(); - consentBasicDataJson.put("RECEIPT", ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); - consentBasicDataJson.put("UPDATED_TIME", - String.valueOf(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP)); - consentBasicDataJson.put("VALIDITY_TIME", - String.valueOf(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD)); - consentBasicDataJson.put("CURRENT_STATUS", ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); - return consentBasicDataJson.toString(); - } - - private static String getConsentAttributesDataChangedAttributesJson() { - - JSONObject consentAttributesDataJson = new JSONObject(); - consentAttributesDataJson.put("sample_consent_attribute_name", "sample_consent_attribute_value"); - consentAttributesDataJson.put("sampleAttributeKey", null); - return consentAttributesDataJson.toString(); - } - - public static Map getSampleConsentHistoryBasicConsentDataMap() { - - Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); - Map changedAttributesJson = new HashMap<>(); - changedAttributesJson.put("ConsentData", getBasicConsentDataChangedAttributesJson()); - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); - consentHistoryResource.setReason("SampleReason"); - consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); - return consentAmendmentHistoryDataMap; - } - - public static Map getSampleConsentHistoryConsentAttributesDataMap() { - - Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); - Map changedAttributesJson = new HashMap<>(); - changedAttributesJson.put("ConsentAttributesData", getConsentAttributesDataChangedAttributesJson()); - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); - consentHistoryResource.setReason("SampleReason"); - consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); - return consentAmendmentHistoryDataMap; - } - - public static Map getSampleConsentHistoryConsentMappingsDataMap() { - - Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); - - Map changedAttributesJson = new HashMap<>(); - - Map consentMappingResources = new HashMap<>(); - JSONObject consentMappingDataJson1 = new JSONObject(); - consentMappingDataJson1.put("MAPPING_STATUS", ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); - consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID, consentMappingDataJson1); - - JSONObject consentMappingDataJson2 = new JSONObject(); - consentMappingDataJson2.put("MAPPING_STATUS", "null"); - consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2, consentMappingDataJson2); - changedAttributesJson.put("ConsentMappingData", consentMappingResources); - - ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); - consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); - consentHistoryResource.setReason("SampleReason"); - consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); - return consentAmendmentHistoryDataMap; - } - - public static Map getSampleAdditionalConsentAmendmentDataMap() { - - Map additionalAmendmentData = new HashMap<>(); - Map newUserAuthResources = new HashMap<>(); - Map> newUserAccountMappings = new HashMap<>(); - - AuthorizationResource newAuthResource = getSampleStoredTestAuthorizationResource(); - newUserAuthResources.put(SAMPLE_NEW_USER_ID, newAuthResource); - - ConsentMappingResource consentMappingResource = getSampleStoredTestConsentMappingResource(null); - ArrayList consentMappingResourceList = new ArrayList(); - consentMappingResourceList.add(consentMappingResource); - newUserAccountMappings.put(SAMPLE_NEW_USER_ID, consentMappingResourceList); - - additionalAmendmentData - .put(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES, newUserAuthResources); - additionalAmendmentData - .put(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES, newUserAccountMappings); - return additionalAmendmentData; - } - - public static Map getSampleAdditionalConsentAmendmentDataMapWithoutConsentId() { - - Map additionalAmendmentData = new HashMap<>(); - Map newUserAuthResources = new HashMap<>(); - Map> newUserAccountMappings = new HashMap<>(); - - AuthorizationResource newAuthResource = getSampleStoredTestAuthorizationResource(); - newAuthResource.setConsentID(null); - newUserAuthResources.put(SAMPLE_NEW_USER_ID, newAuthResource); - - ConsentMappingResource consentMappingResource = getSampleStoredTestConsentMappingResource(null); - ArrayList consentMappingResourceList = new ArrayList(); - consentMappingResourceList.add(consentMappingResource); - newUserAccountMappings.put(SAMPLE_NEW_USER_ID, consentMappingResourceList); - - additionalAmendmentData - .put(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES, newUserAuthResources); - additionalAmendmentData - .put(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES, newUserAccountMappings); - return additionalAmendmentData; - } - - public static Map getSampleAdditionalConsentAmendmentDataMapWithoutAccountId() { - - Map additionalAmendmentData = new HashMap<>(); - Map newUserAuthResources = new HashMap<>(); - Map> newUserAccountMappings = new HashMap<>(); - - AuthorizationResource newAuthResource = getSampleStoredTestAuthorizationResource(); - newUserAuthResources.put(SAMPLE_NEW_USER_ID, newAuthResource); - - ConsentMappingResource consentMappingResource = getSampleStoredTestConsentMappingResource(null); - consentMappingResource.setAccountID(null); - ArrayList consentMappingResourceList = new ArrayList(); - consentMappingResourceList.add(consentMappingResource); - newUserAccountMappings.put(SAMPLE_NEW_USER_ID, consentMappingResourceList); - - additionalAmendmentData - .put(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES, newUserAuthResources); - additionalAmendmentData - .put(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES, newUserAccountMappings); - return additionalAmendmentData; - } - -} diff --git a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/resources/testng.xml b/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/resources/testng.xml deleted file mode 100644 index 78e08e53..00000000 --- a/open-banking-accelerator/components/consent-management/com.wso2.openbanking.accelerator.consent.mgt.service/src/test/resources/testng.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/pom.xml b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/pom.xml deleted file mode 100644 index 3d7a58f5..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/pom.xml +++ /dev/null @@ -1,237 +0,0 @@ - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.event.notifications.service - bundle - WSO2 Open Banking - Event Notification Service Module - - - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - - - org.apache.commons - commons-lang3 - provided - - - org.testng - testng - test - - - org.mockito - mockito-all - - - org.powermock - powermock-module-testng - - - org.powermock - powermock-api-mockito - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.service - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.junit.jupiter - junit-jupiter - RELEASE - test - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - org.apache.synapse - synapse-core - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - **/*Constants.class - **/*Component.class - **/*DataHolder.class - src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/**/*SqlStatements.* - **/exceptions/* - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.8 - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.event.notifications.service.internal - - - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - com.wso2.openbanking.accelerator.common.*;version="${project.version}", - org.apache.commons.lang3;version="${commons-lang.version}" - com.wso2.openbanking.accelerator.consent.mgt.service.*;version="${project.version}", - - - !com.wso2.openbanking.accelerator.event.notifications.service.internal, - com.wso2.openbanking.accelerator.event.notifications.service.*;version="${project.version}", - - - javax.ws.rs-api;scope=compile;inline=false, - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/constants/EventNotificationConstants.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/constants/EventNotificationConstants.java deleted file mode 100644 index 835e2248..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/constants/EventNotificationConstants.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.constants; - -/** - * Event Notification Constants. - */ -public class EventNotificationConstants { - - //Service level constants - public static final String X_WSO2_CLIENT_ID = "x-wso2-client_id"; - - //Event Notification Status - public static final String ACK = "ACK"; - public static final String ERROR = "ERR"; - public static final String OPEN = "OPEN"; - - //Response Status - public static final String NOT_FOUND = "NOTFOUND"; - public static final String OK = "OK"; - public static final String CREATED = "CREATED"; - public static final String BAD_REQUEST = "BADREQUEST"; - public static final String NO_CONTENT = "NO_CONTENT"; - public static final String INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR"; - //Database columns - public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; - public static final String CLIENT_ID = "CLIENT_ID"; - public static final String RESOURCE_ID = "RESOURCE_ID"; - public static final String STATUS = "STATUS"; - public static final String UPDATED_TIMESTAMP = "UPDATED_TIMESTAMP"; - public static final String EVENT_INFO = "EVENT_INFO"; - public static final String EVENT_TYPE = "EVENT_TYPE"; - public static final String SUBSCRIPTION_ID = "SUBSCRIPTION_ID"; - public static final String CALLBACK_URL = "CALLBACK_URL"; - public static final String TIME_STAMP = "TIMESTAMP"; - public static final String SPEC_VERSION = "SPEC_VERSION"; - public static final String REQUEST = "REQUEST"; - - //Error Constants - public static final String INVALID_REQUEST = "invalid_request"; - public static final String EVENT_NOTIFICATION_CREATION_ERROR = "Error occurred while saving event " + - "notifications in the database"; - public static final String MISSING_REQ_PAYLOAD = "No request payload found"; - public static final String MISSING_HEADER_PARAM_CLIENT_ID = "Missing header x-wso2-client_id"; - public static final String MISSING_HEADER_PARAM_RESOURCE_ID = "Missing header x-wso2-resource_id"; - public static final String ERROR_IN_EVENT_POLLING_REQUEST = "Error in event polling request"; - public static final String INVALID_CHARS_IN_HEADER_ERROR = "Invalid characters found in the request headers"; - - //Polling request params - public static final String SET_ERRORS = "setErrs"; - public static final String MAX_EVENTS = "maxEvents"; - public static final String DESCRIPTION = "description"; - public static final String RETURN_IMMEDIATELY = "returnImmediately"; - - //Polling response params - public static final String SETS = "sets"; - public static final String MORE_AVAILABLE = "moreAvailable"; - public static final String NOTIFICATIONS_ID = "notificationsID"; - - // Event Subscription Request Params - public static final String SUBSCRIPTION_ID_PARAM = "subscriptionId"; - public static final String CALLBACK_URL_PARAM = "callbackUrl"; - public static final String VERSION_PARAM = "version"; - public static final String EVENT_TYPE_PARAM = "eventTypes"; - public static final String DATA_PARAM = "data"; - - public static final String DB_ERROR_UPDATING = "Database error while updating notification with ID : " + - "'%s' in the database. "; - public static final String DB_ERROR_NOTIFICATION_RETRIEVE = "Error occurred while retrieving" + - " notifications for client ID : '%s'."; - public static final String DB_FAILED_ERROR_NOTIFICATION_STORING = "Failed to store error notification with ID : "; - public static final String DB_ERROR_STORING_ERROR_NOTIFICATION = "Error occurred while closing the " + - "event-notification database connection"; - public static final String DB_ERROR_EVENTS_RETRIEVE = "Error occurred while retrieving events for" + - " notifications ID : '%s'."; - public static final String PARSE_ERROR_NOTIFICATION_ID = "Error occurred while parsing events for" + - " notifications ID : '%s'."; - public static final String DB_CONN_ESTABLISHED = "Database connection is established to get notification " + - "for client ID : '%s' in the database. "; - public static final String RETRIEVED_NOTIFICATION_CLIENT = "Retrieved notification for client ID: '%s'. "; - - public static final String RETRIEVED_EVENTS_NOTIFICATION = "Retrieved events for notification ID: '%s'. "; - public static final String NO_NOTIFICATIONS_FOUND_CLIENT = "No notifications found for client ID - '%s'"; - public static final String NO_EVENTS_NOTIFICATION_ID = "No events found for notification ID - '%s'"; - public static final String INVALID_CLIENT_ID = "Invalid mandatory parameter x-wso2-client-id."; - public static final String DATABASE_CONNECTION_CLOSE_LOG_MSG = "Closing database connection"; - - public static final String ERROR_STORING_EVENT_SUBSCRIPTION = "Error occurred while storing event " + - "subscription in the database. "; - public static final String ERROR_UPDATING_EVENT_SUBSCRIPTION = "Error occurred while updating event " + - "subscription in the database. "; - public static final String ERROR_RETRIEVING_EVENT_SUBSCRIPTION = "Error occurred while retrieving event " + - "subscription in the database. "; - public static final String ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS = "Error occurred while retrieving event " + - "subscriptions in the database."; - public static final String ERROR_DELETING_EVENT_SUBSCRIPTION = "Error occurred while deleting event " + - "subscription in the database. "; - public static final String EVENT_SUBSCRIPTION_NOT_FOUND = "Event subscription not found."; - public static final String EVENT_SUBSCRIPTIONS_NOT_FOUND = "Event subscriptions not found for the given client id."; - public static final String ERROR_HANDLING_EVENT_SUBSCRIPTION = "Error occurred while handling the event " + - "subscription request"; -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAO.java deleted file mode 100644 index 26325d13..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAO.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; - -import java.util.List; -import java.util.Map; - -/** - * Aggregated Polling DAO impl. - */ -public interface AggregatedPollingDAO { - - /** - * This method is to update the notification status by ID, allowed values are. - * OPEN,ACK and ERR - * - * @param notificationId Notification ID to update - * @param notificationStatus Notification status to update - * @return Update is success or not - * @throws OBEventNotificationException Exception when updating notification status by ID - */ - Boolean updateNotificationStatusById(String notificationId, String notificationStatus) - throws OBEventNotificationException; - - /** - * This method is to store event notifications error details in the OB_NOTIFICATION table. - * - * @param notificationError Notification error details - * @return Stored event notifications error details - * @throws OBEventNotificationException Exception when storing event notifications error details - */ - Map storeErrorNotification(NotificationError notificationError) - throws OBEventNotificationException; - - /** - * This method is to retrieve given number of notifications in the OB_NOTIFICATION table by client and status. - * - * @param clientId Client ID to retrieve notifications - * @param status Notification status to retrieve - * @param max Maximum number of notifications to retrieve - * @return List of notifications by client and status - * @throws OBEventNotificationException Exception when retrieving notifications by client ID and status - */ - List getNotificationsByClientIdAndStatus(String clientId, String - status, int max) throws OBEventNotificationException; - - /** - * This method is to retrieve notifications by NotificationID. - * - * @param notificationId Notification ID to retrieve - * @return List of notifications by notification ID - * @throws OBEventNotificationException Exception when retrieving notifications by notification ID - */ - List getEventsByNotificationID(String notificationId) throws OBEventNotificationException; - - /** - * This method is to retrieve notifications in the OB_NOTIFICATION table by status. - * - * @param status Notification status to retrieve - * @return List of notifications by status - * @throws OBEventNotificationException Exception when retrieving notifications by status - */ - List getNotificationsByStatus(String status) throws OBEventNotificationException; - - /** - * This method is to retrieve notificationsCount by ClientId and Status. - * - * @param clientId Client ID to retrieve notifications - * @param eventStatus Notification status to retrieve - * @return List of notifications by status and client id - * @throws OBEventNotificationException Exception when retrieving notification count by client ID and status - */ - int getNotificationCountByClientIdAndStatus(String clientId, String eventStatus) - throws OBEventNotificationException; - - /** - * This method is to retrieve the notification status. - * - * @param notificationId Notification ID to retrieve - * @return Notification status by notification ID - * @throws OBEventNotificationException Exception when retrieving notification status - */ - boolean getNotificationStatus(String notificationId) throws OBEventNotificationException; -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAOImpl.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAOImpl.java deleted file mode 100644 index a14b74b7..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAOImpl.java +++ /dev/null @@ -1,448 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Savepoint; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Default PollingDAO Impl. - */ -public class AggregatedPollingDAOImpl implements AggregatedPollingDAO { - - private static Log log = LogFactory.getLog(AggregatedPollingDAOImpl.class); - protected NotificationPollingSqlStatements sqlStatements; - - - public AggregatedPollingDAOImpl(NotificationPollingSqlStatements notificationPollingSqlStatements) { - this.sqlStatements = notificationPollingSqlStatements; - } - - @Override - public Boolean updateNotificationStatusById(String notificationId, String notificationStatus) - throws OBEventNotificationException { - - Connection connection = DatabaseUtil.getDBConnection(); - if (log.isDebugEnabled()) { - log.debug(String.format("Database connection is established for updating notification with " + - "ID : '%s' in the database. ", notificationId.replaceAll("[\r\n]", ""))); - } - try { - connection.setAutoCommit(false); - Savepoint savepoint = connection.setSavepoint(); - final String sql = sqlStatements.updateNotificationStatusQueryById(); - try (PreparedStatement updateNotificationStatusById = connection.prepareStatement(sql)) { - Timestamp currentTimeStamp = new Timestamp(new Date().getTime()); - updateNotificationStatusById.setString(1, notificationStatus); - updateNotificationStatusById.setTimestamp(2, currentTimeStamp); - updateNotificationStatusById.setString(3, notificationId); - - int affectedRows = updateNotificationStatusById.executeUpdate(); - - if (affectedRows != 0) { - connection.commit(); - if (log.isDebugEnabled()) { - log.debug(String.format("Updated notification with Notification ID '%s'", - notificationId.replaceAll("[\r\n]", ""))); - } - - return true; - } else { - if (log.isDebugEnabled()) { - log.debug(String.format("Failed updating notification with ID : '%s'", - notificationId.replaceAll("[\r\n]", ""))); - } - return false; - } - } catch (SQLException e) { - connection.rollback(savepoint); - log.error(String.format(EventNotificationConstants.DB_ERROR_UPDATING, - notificationId.replaceAll("[\r\n]", "")), e); - throw new OBEventNotificationException(String.format(EventNotificationConstants.DB_ERROR_UPDATING, - notificationId)); - } - } catch (SQLException e) { - log.debug("SQL exception when updating notification status", e); - throw new OBEventNotificationException("Database error while closing the connection to the" + - " the database."); - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public Map storeErrorNotification(NotificationError notificationError) - throws OBEventNotificationException { - - Map response = new HashMap<>(); - Connection connection = DatabaseUtil.getDBConnection(); - - try { - connection.setAutoCommit(false); - - if (log.isDebugEnabled()) { - log.debug(String.format("Database connection is established for storing error notification with ID" + - " : '%s' in the database. ", - notificationError.getNotificationId().replaceAll("[\r\n]", ""))); - } - - final String storeErrorNotificationQuery = sqlStatements.storeErrorNotificationQuery(); - try (PreparedStatement storeErrorNotificationPreparedStatement = - connection.prepareStatement(storeErrorNotificationQuery)) { - - storeErrorNotificationPreparedStatement.setString(1, notificationError. - getNotificationId()); - storeErrorNotificationPreparedStatement.setString(2, notificationError. - getErrorCode()); - storeErrorNotificationPreparedStatement.setString(3, notificationError. - getErrorDescription()); - - int affectedRows = storeErrorNotificationPreparedStatement.executeUpdate(); - if (affectedRows == 1) { - connection.commit(); - if (log.isDebugEnabled()) { - log.debug(String.format("Successfully stored error notification with ID:'%s'.", - notificationError.getNotificationId().replaceAll("[\r\n]", ""))); - } - response.put(notificationError.getNotificationId(), notificationError); - } else { - if (log.isDebugEnabled()) { - log.debug(String.format("Failed store error notification with ID:'%s'.", - notificationError.getNotificationId().replaceAll("[\r\n]", ""))); - } - throw new OBEventNotificationException(EventNotificationConstants. - DB_FAILED_ERROR_NOTIFICATION_STORING + notificationError.getNotificationId()); - } - - } catch (SQLException e) { - connection.rollback(); - throw new OBEventNotificationException(EventNotificationConstants. - DB_ERROR_STORING_ERROR_NOTIFICATION, e); - } - } catch (SQLException e) { - throw new OBEventNotificationException(EventNotificationConstants.DB_ERROR_STORING_ERROR_NOTIFICATION, e); - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return response; - } - - @Override - public List getNotificationsByClientIdAndStatus(String clientId, String status, int max) - throws OBEventNotificationException { - - List notificationList; - Connection connection = DatabaseUtil.getDBConnection(); - try { - notificationList = new ArrayList<>(); - - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.DB_CONN_ESTABLISHED, - clientId.replaceAll("[\r\n]", ""))); - } - - final String sql = sqlStatements.getMaxNotificationsQuery(); - try (PreparedStatement getNotificationsPreparedStatement = connection.prepareStatement(sql)) { - getNotificationsPreparedStatement.setString(1, clientId); - getNotificationsPreparedStatement.setString(2, status); - getNotificationsPreparedStatement.setInt(3, max); - - try (ResultSet notificationResultSet = getNotificationsPreparedStatement.executeQuery()) { - if (notificationResultSet.next()) { - - //bring pointer back to the top of the result set if not on the top - if (!notificationResultSet.isBeforeFirst()) { - notificationResultSet.beforeFirst(); - } - - //read event notifications from the result set - while (notificationResultSet.next()) { - NotificationDTO notification = new NotificationDTO(); - - notification.setNotificationId(notificationResultSet.getString - (EventNotificationConstants.NOTIFICATION_ID)); - notification.setClientId(notificationResultSet.getString - (EventNotificationConstants.CLIENT_ID)); - notification.setResourceId(notificationResultSet.getString - (EventNotificationConstants.RESOURCE_ID)); - notification.setStatus(notificationResultSet.getString - (EventNotificationConstants.STATUS)); - notification.setUpdatedTimeStamp((notificationResultSet.getTimestamp( - (EventNotificationConstants.UPDATED_TIMESTAMP)).getTime())); - - notificationList.add(notification); - } - notificationResultSet.close(); - getNotificationsPreparedStatement.close(); - - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.RETRIEVED_NOTIFICATION_CLIENT, - clientId.replaceAll("[\r\n]", ""))); - } - } else { - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.NO_NOTIFICATIONS_FOUND_CLIENT, - clientId.replaceAll("[\r\n]", ""))); - } - } - } - } catch (SQLException e) { - throw new OBEventNotificationException(String.format - (EventNotificationConstants.DB_ERROR_NOTIFICATION_RETRIEVE, clientId), e); - } - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return notificationList; - } - - @Override - public List getEventsByNotificationID(String notificationId) - throws OBEventNotificationException { - - List eventList = new ArrayList<>(); - - Connection connection = DatabaseUtil.getDBConnection(); - try { - - final String sql = sqlStatements.getEventsByNotificationIdQuery(); - - try (PreparedStatement getEventsPreparedStatement = connection.prepareStatement(sql)) { - - getEventsPreparedStatement.setString(1, notificationId); - - try (ResultSet eventsResultSet = getEventsPreparedStatement.executeQuery()) { - if (eventsResultSet.next()) { - - //bring pointer back to the top of the result set if not on the top - if (!eventsResultSet.isBeforeFirst()) { - eventsResultSet.beforeFirst(); - } - - //read event notifications from the result set - while (eventsResultSet.next()) { - NotificationEvent event = new NotificationEvent(); - event.setNotificationId(eventsResultSet.getString - (EventNotificationConstants.NOTIFICATION_ID)); - event.setEventType(eventsResultSet.getString - (EventNotificationConstants.EVENT_TYPE)); - event.setEventInformation(EventNotificationServiceUtil. - getEventJSONFromString(eventsResultSet.getString - (EventNotificationConstants.EVENT_INFO))); - eventList.add(event); - } - eventsResultSet.close(); - getEventsPreparedStatement.close(); - - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.RETRIEVED_EVENTS_NOTIFICATION, - notificationId.replaceAll("[\r\n]", ""))); - } - } else { - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.NO_EVENTS_NOTIFICATION_ID, - notificationId.replaceAll("[\r\n]", ""))); - } - } - } catch (ParseException e) { - log.error(String.format(EventNotificationConstants.PARSE_ERROR_NOTIFICATION_ID, - notificationId.replaceAll("[\r\n]", "")), e); - throw new OBEventNotificationException(String.format ( - EventNotificationConstants.PARSE_ERROR_NOTIFICATION_ID, notificationId), e); - } - } catch (SQLException e) { - log.error(String.format(EventNotificationConstants.DB_ERROR_EVENTS_RETRIEVE, - notificationId.replaceAll("[\r\n]", "")), e); - throw new OBEventNotificationException(String.format - (EventNotificationConstants.DB_ERROR_EVENTS_RETRIEVE, notificationId), e); - } - - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return eventList; - } - - @Override - public List getNotificationsByStatus(String status) throws OBEventNotificationException { - List notificationList; - Connection connection = DatabaseUtil.getDBConnection(); - try { - notificationList = new ArrayList<>(); - final String sql = sqlStatements.getNotificationsByState(); - try (PreparedStatement getNotificationsPreparedStatement = connection.prepareStatement(sql)) { - getNotificationsPreparedStatement.setString(1, status); - - try (ResultSet notificationResultSet = getNotificationsPreparedStatement.executeQuery()) { - if (notificationResultSet.next()) { - //bring pointer back to the top of the result set if not on the top - if (!notificationResultSet.isBeforeFirst()) { - notificationResultSet.beforeFirst(); - } - //read event notifications from the result set - while (notificationResultSet.next()) { - NotificationDTO notification = new NotificationDTO(); - notification.setNotificationId(notificationResultSet.getString - (EventNotificationConstants.NOTIFICATION_ID)); - notification.setClientId(notificationResultSet.getString - (EventNotificationConstants.CLIENT_ID)); - notification.setResourceId(notificationResultSet.getString - (EventNotificationConstants.RESOURCE_ID)); - notification.setStatus(notificationResultSet.getString - (EventNotificationConstants.STATUS)); - notification.setUpdatedTimeStamp((notificationResultSet.getTimestamp( - (EventNotificationConstants.UPDATED_TIMESTAMP)).getTime())); - notificationList.add(notification); - } - notificationResultSet.close(); - getNotificationsPreparedStatement.close(); - if (log.isDebugEnabled()) { - log.debug( - EventNotificationConstants.RETRIEVED_NOTIFICATION_CLIENT); - } - } else { - if (log.isDebugEnabled()) { - log.debug(EventNotificationConstants.NO_NOTIFICATIONS_FOUND_CLIENT); - } - } - } - } catch (SQLException e) { - throw new OBEventNotificationException(EventNotificationConstants.DB_ERROR_NOTIFICATION_RETRIEVE, e); - } - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return notificationList; - } - - @Override - public int getNotificationCountByClientIdAndStatus(String clientId, String eventStatus) - throws OBEventNotificationException { - - Connection connection = DatabaseUtil.getDBConnection(); - try { - - final String sql = sqlStatements.getNotificationsCountQuery(); - try (PreparedStatement getNotificationCount = connection.prepareStatement(sql)) { - - getNotificationCount.setString(1, clientId); - getNotificationCount.setString(2, eventStatus); - - try (ResultSet notificationCountResultSet = getNotificationCount.executeQuery()) { - if (notificationCountResultSet.next()) { - - int count = notificationCountResultSet.getInt("NOTIFICATION_COUNT"); - notificationCountResultSet.close(); - getNotificationCount.close(); - - if (log.isDebugEnabled()) { - log.debug(String.format("Retrieved notification count for client ID: '%s'. ", - clientId.replaceAll("[\r\n]", ""))); - } - - return count; - } else { - if (log.isDebugEnabled()) { - log.debug(String.format( - EventNotificationConstants.NO_NOTIFICATIONS_FOUND_CLIENT, - clientId.replaceAll("[\r\n]", ""))); - } - - return 0; - } - } - } catch (SQLException e) { - throw new OBEventNotificationException(String.format - (EventNotificationConstants.DB_ERROR_NOTIFICATION_RETRIEVE, clientId), e); - } - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - @Override - public boolean getNotificationStatus(String notificationId) throws OBEventNotificationException { - - boolean isOpenStatus = false; - Connection connection = DatabaseUtil.getDBConnection(); - try { - - final String sql = sqlStatements.getNotificationByNotificationId(); - try (PreparedStatement getNotificationStatus = connection.prepareStatement(sql)) { - getNotificationStatus.setString(1, notificationId); - - try (ResultSet notificationResultSet = getNotificationStatus.executeQuery()) { - if (notificationResultSet.next()) { - - if (EventNotificationConstants.OPEN.equals(notificationResultSet. - getString("STATUS"))) { - isOpenStatus = true; - } - - return isOpenStatus; - } else { - if (log.isDebugEnabled()) { - log.debug(String.format("No notifications found for notification ID - '%s'", - notificationId.replaceAll("[\r\n]", ""))); - } - } - } - } catch (SQLException e) { - throw new OBEventNotificationException(String.format - ("Error occurred while retrieving status for the notifications ID : '%s'.", - notificationId), e); - } - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return false; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAO.java deleted file mode 100644 index 0ff62185..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAO.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; - -import java.sql.Connection; -import java.util.ArrayList; - -/** - * Event Publisher DAO interface. - */ -public interface EventPublisherDAO { - - /** - * This method is used to persist event notifications in the database. - * @param connection Database connection - * @param notificationDTO Notification details DTO - * @param eventsList List of notification events - * @return NotificationID of the saved notification. - * @throws OBEventNotificationException Exception when persisting event notification data - */ - String persistEventNotification(Connection connection, NotificationDTO notificationDTO, - ArrayList eventsList) throws OBEventNotificationException; - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAOImpl.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAOImpl.java deleted file mode 100644 index de7e06f8..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAOImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.ArrayList; - -/** - * Persisting event notifications to database. - */ -public class EventPublisherDAOImpl implements EventPublisherDAO { - - private static Log log = LogFactory.getLog(EventPublisherDAOImpl.class); - protected NotificationPublisherSqlStatements sqlStatements; - - public EventPublisherDAOImpl(NotificationPublisherSqlStatements notificationPublisherSqlStatements) { - this.sqlStatements = notificationPublisherSqlStatements; - } - - @Override - public String persistEventNotification(Connection connection, NotificationDTO notificationDTO, - ArrayList eventsList) throws OBEventNotificationException { - - int result; - int[] noOfRows; - String persistEventNotification = sqlStatements.getStoreNotification(); - String persistEvents = sqlStatements.getStoreNotificationEvents(); - - try (PreparedStatement persistEventNotificationStmnt = - connection.prepareStatement(persistEventNotification); - PreparedStatement persistEventsStmt = connection.prepareStatement(persistEvents)) { - - log.debug("Setting parameters to prepared statement to add event notification "); - - persistEventNotificationStmnt.setString(1, notificationDTO.getNotificationId()); - persistEventNotificationStmnt.setString(2, notificationDTO.getClientId()); - persistEventNotificationStmnt.setString(3, notificationDTO.getResourceId()); - persistEventNotificationStmnt.setString(4, notificationDTO.getStatus()); - - // with result, we can determine whether the insertion was successful or not - result = persistEventNotificationStmnt.executeUpdate(); - - // to insert notification events - for (NotificationEvent event : eventsList) { - persistEventsStmt.setString(1, notificationDTO.getNotificationId()); - persistEventsStmt.setString(2, event.getEventType()); - persistEventsStmt.setString(3, event.getEventInformation().toString()); - persistEventsStmt.addBatch(); - } - noOfRows = persistEventsStmt.executeBatch(); - } catch (SQLException e) { - log.error(EventNotificationConstants.EVENT_NOTIFICATION_CREATION_ERROR, e); - throw new OBEventNotificationException(EventNotificationConstants. - EVENT_NOTIFICATION_CREATION_ERROR, e); - } - // Confirm that the data are updated successfully - if (result > 0 && noOfRows.length != 0) { - log.info("Created the event notification successfully"); - return notificationDTO.getNotificationId(); - } else { - throw new OBEventNotificationException("Failed to create the event notification."); - } - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAO.java deleted file mode 100644 index dc41501e..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAO.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; - -import java.sql.Connection; -import java.util.List; - -/** - * Event Notification Subscription DAO interface. - */ -public interface EventSubscriptionDAO { - - /** - * This method is used to store event notification subscription in the database. - * - * @param connection Database connection. - * @param eventSubscription EventSubscription object. - * @return EventSubscription object. - * @throws OBEventNotificationException Exception when storing event subscription - */ - EventSubscription storeEventSubscription(Connection connection, EventSubscription eventSubscription) - throws OBEventNotificationException; - - /** - * This method is used to store subscribed event types in the database. - * - * @param connection Database connection. - * @param subscriptionId Subscription ID. - * @param eventTypes Event types to be stored. - * @return List of strings with subscribed event types. - * @throws OBEventNotificationException Exception when storing subscribed event types - */ - List storeSubscribedEventTypes(Connection connection, String subscriptionId, List eventTypes) - throws OBEventNotificationException; - - /** - * This method is used to retrieve an event subscription by a subscription ID. - * - * @param connection Database connection. - * @param subscriptionId Subscription ID. - * @return EventSubscription model. - * @throws OBEventNotificationException Exception when retrieving event subscription by subscription ID - */ - EventSubscription getEventSubscriptionBySubscriptionId(Connection connection, String subscriptionId) - throws OBEventNotificationException; - - /** - * This method is used to retrieve all event subscriptions a client. - * - * @param connection Database connection. - * @param clientId Client ID. - * @return List of EventSubscription models. - * @throws OBEventNotificationException Exception when retrieving event subscriptions by client ID - */ - List getEventSubscriptionsByClientId(Connection connection, String clientId) - throws OBEventNotificationException; - - /** - * This method is used to retrieve all event subscriptions by event type. - * - * @param connection Database connection. - * @param eventType Event type that need to be subscribed by the retrieving subscriptions. - * @return List of EventSubscription models. - * @throws OBEventNotificationException Exception when retrieving event subscriptions by event type - */ - List getEventSubscriptionsByEventType(Connection connection, String eventType) - throws OBEventNotificationException; - - /** - * This method is used to update an event subscription. - * - * @param connection Database connection. - * @param eventSubscription eventSubscription object. - * @return true if update was successful. - * @throws OBEventNotificationException Exception when updating event subscription - */ - Boolean updateEventSubscription(Connection connection, EventSubscription eventSubscription) - throws OBEventNotificationException; - - /** - * This method is used to delete an event subscription. - * - * @param connection Database connection. - * @param subscriptionId Subscription ID. - * @return true if deletion was successful. - * @throws OBEventNotificationException Exception when deleting event subscription - */ - Boolean deleteEventSubscription(Connection connection, String subscriptionId) throws OBEventNotificationException; - - /** - * This method is used to delete subscribed event types of a subscription. - * - * @param connection Database connection. - * @param subscriptionId subscription ID. - * @return true if deletion was successful. - * @throws OBEventNotificationException Exception when deleting subscribed event types - */ - Boolean deleteSubscribedEventTypes(Connection connection, String subscriptionId) - throws OBEventNotificationException; - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAOImpl.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAOImpl.java deleted file mode 100644 index 7f86e8fa..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAOImpl.java +++ /dev/null @@ -1,309 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import static java.sql.Statement.EXECUTE_FAILED; - -/** - * Default EventSubscriptionDAO Impl. - */ -public class EventSubscriptionDAOImpl implements EventSubscriptionDAO { - private static Log log = LogFactory.getLog(EventSubscriptionDAOImpl.class); - - protected EventSubscriptionSqlStatements sqlStatements; - - public EventSubscriptionDAOImpl(EventSubscriptionSqlStatements sqlStatements) { - this.sqlStatements = sqlStatements; - } - - public EventSubscription storeEventSubscription(Connection connection, EventSubscription eventSubscription) - throws OBEventNotificationException { - - int storeSubscriptionAffectedRows; - - UUID subscriptionId = UUID.randomUUID(); - long unixTime = Instant.now().getEpochSecond(); - eventSubscription.setSubscriptionId(subscriptionId.toString()); - eventSubscription.setTimeStamp(unixTime); - eventSubscription.setStatus(EventNotificationConstants.CREATED); - - final String sql = sqlStatements.storeEventSubscriptionQuery(); - try (PreparedStatement storeEventSubscriptionStatement = connection.prepareStatement(sql)) { - storeEventSubscriptionStatement.setString(1, eventSubscription.getSubscriptionId()); - storeEventSubscriptionStatement.setString(2, eventSubscription.getClientId()); - storeEventSubscriptionStatement.setString(3, eventSubscription.getCallbackUrl()); - storeEventSubscriptionStatement.setLong(4, eventSubscription.getTimeStamp()); - storeEventSubscriptionStatement.setString(5, eventSubscription.getSpecVersion()); - storeEventSubscriptionStatement.setString(6, eventSubscription.getStatus()); - storeEventSubscriptionStatement.setString(7, eventSubscription.getRequestData()); - storeSubscriptionAffectedRows = storeEventSubscriptionStatement.executeUpdate(); - if (storeSubscriptionAffectedRows == 0) { - log.error("Failed to store the event notification subscription."); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when storing the event types of the subscription", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION); - } - return eventSubscription; - } - - @Override - public List storeSubscribedEventTypes(Connection connection, String subscriptionId, List eventTypes) - throws OBEventNotificationException { - - final String sql = sqlStatements.storeSubscribedEventTypesQuery(); - try (PreparedStatement storeSubscribedEventTypesStatement = connection.prepareStatement(sql)) { - for (String eventType : eventTypes) { - storeSubscribedEventTypesStatement.setString(1, subscriptionId); - storeSubscribedEventTypesStatement.setString(2, eventType); - storeSubscribedEventTypesStatement.addBatch(); - } - int[] storeSubscribedEventTypesAffectedRows = storeSubscribedEventTypesStatement.executeBatch(); - for (int affectedRows : storeSubscribedEventTypesAffectedRows) { - if (affectedRows == 0 || affectedRows == EXECUTE_FAILED) { - log.error("Failed to store the subscribed event types."); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION); - } - } - } catch (SQLException e) { - log.error("SQL exception when storing the subscribed event types.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION); - } - log.debug("Stored the subscribed event types successfully."); - return eventTypes; - - } - - @Override - public EventSubscription getEventSubscriptionBySubscriptionId(Connection connection, String subscriptionId) - throws OBEventNotificationException { - EventSubscription retrievedSubscription = new EventSubscription(); - List eventTypes = new ArrayList<>(); - - final String sql = sqlStatements.getEventSubscriptionBySubscriptionIdQuery(); - try (PreparedStatement getEventSubscriptionBySubscriptionIdStatement = connection.prepareStatement(sql)) { - getEventSubscriptionBySubscriptionIdStatement.setString(1, subscriptionId); - try (ResultSet resultSet = getEventSubscriptionBySubscriptionIdStatement.executeQuery()) { - if (resultSet.next()) { - mapResultSetToEventSubscription(retrievedSubscription, resultSet); - resultSet.beforeFirst(); // Reset the cursor position to the beginning of the result set. - while (resultSet.next()) { - String eventType = resultSet.getString(EventNotificationConstants.EVENT_TYPE); - if (eventType != null) { - eventTypes.add(eventType); - } - } - if (!eventTypes.isEmpty()) { - retrievedSubscription.setEventTypes(eventTypes); - } - } else { - log.error("No event notification subscription found for the given subscription id."); - throw new OBEventNotificationException( - EventNotificationConstants.EVENT_SUBSCRIPTION_NOT_FOUND); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscription.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscription.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - return retrievedSubscription; - } - - @Override - public List getEventSubscriptionsByClientId(Connection connection, String clientId) - throws OBEventNotificationException { - List retrievedSubscriptions = new ArrayList<>(); - - final String sql = sqlStatements.getEventSubscriptionsByClientIdQuery(); - try (PreparedStatement getEventSubscriptionsByClientIdStatement = connection.prepareStatement(sql)) { - getEventSubscriptionsByClientIdStatement.setString(1, clientId); - try (ResultSet resultSet = getEventSubscriptionsByClientIdStatement.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - EventSubscription eventSubscription = new EventSubscription(); - List eventTypes = new ArrayList<>(); - mapResultSetToEventSubscription(eventSubscription, resultSet); - resultSet.previous(); - while (resultSet.next()) { - if (eventSubscription.getSubscriptionId().equals(resultSet. - getString(EventNotificationConstants.SUBSCRIPTION_ID))) { - if (resultSet.getString(EventNotificationConstants.EVENT_TYPE) != null) { - eventTypes.add(resultSet.getString(EventNotificationConstants.EVENT_TYPE)); - } - } else { - resultSet.previous(); - break; - } - } - if (!eventTypes.isEmpty()) { - eventSubscription.setEventTypes(eventTypes); - } - retrievedSubscriptions.add(eventSubscription); - } - log.debug("Retrieved the event notification subscriptions successfully."); - } - return retrievedSubscriptions; - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscriptions.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscriptions.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS); - } - } - - @Override - public List getEventSubscriptionsByEventType(Connection connection, String eventType) - throws OBEventNotificationException { - List retrievedSubscriptions = new ArrayList<>(); - - final String sql = sqlStatements.getEventSubscriptionsByEventTypeQuery(); - try (PreparedStatement getEventSubscriptionsByClientIdAndEventTypeStatement = - connection.prepareStatement(sql)) { - getEventSubscriptionsByClientIdAndEventTypeStatement.setString(1, eventType); - try (ResultSet resultSet = getEventSubscriptionsByClientIdAndEventTypeStatement.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - EventSubscription eventSubscription = new EventSubscription(); - List eventTypes = new ArrayList<>(); - mapResultSetToEventSubscription(eventSubscription, resultSet); - resultSet.previous(); - while (resultSet.next()) { - if (eventSubscription.getSubscriptionId().equals(resultSet. - getString(EventNotificationConstants.SUBSCRIPTION_ID))) { - if (resultSet.getString(EventNotificationConstants.EVENT_TYPE) != null) { - eventTypes.add(resultSet.getString(EventNotificationConstants.EVENT_TYPE)); - } - } else { - resultSet.previous(); - break; - } - } - if (!eventTypes.isEmpty()) { - eventSubscription.setEventTypes(eventTypes); - } - retrievedSubscriptions.add(eventSubscription); - } - log.debug("Retrieved the event notification subscriptions successfully."); - } - return retrievedSubscriptions; - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscriptions.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscriptions.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS); - } - } - - @Override - public Boolean updateEventSubscription(Connection connection, EventSubscription eventSubscription) - throws OBEventNotificationException { - boolean isUpdated = false; - final String sql = sqlStatements.updateEventSubscriptionQuery(); - try (PreparedStatement updateEventSubscriptionStatement = connection.prepareStatement(sql)) { - updateEventSubscriptionStatement.setString(1, eventSubscription.getCallbackUrl()); - updateEventSubscriptionStatement.setLong(2, Instant.now().getEpochSecond()); - updateEventSubscriptionStatement.setString(3, eventSubscription.getRequestData()); - updateEventSubscriptionStatement.setString(4, eventSubscription.getSubscriptionId()); - int affectedRows = updateEventSubscriptionStatement.executeUpdate(); - if (affectedRows > 0) { - log.debug("Event notification subscription is successfully updated."); - isUpdated = true; - } - } catch (SQLException e) { - log.error("SQL exception when updating event notification subscription", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_UPDATING_EVENT_SUBSCRIPTION); - } - return isUpdated; - } - - @Override - public Boolean deleteEventSubscription(Connection connection, String subscriptionId) - throws OBEventNotificationException { - - final String sql = sqlStatements.updateEventSubscriptionStatusQuery(); - try (PreparedStatement deleteEventSubscriptionStatement = connection.prepareStatement(sql)) { - deleteEventSubscriptionStatement.setString(1, "DELETED"); - deleteEventSubscriptionStatement.setString(2, subscriptionId); - int affectedRows = deleteEventSubscriptionStatement.executeUpdate(); - if (affectedRows == 0) { - log.debug("Failed deleting event notification subscription."); - return false; - } - log.debug("Event notification subscription is successfully deleted from the database."); - return true; - } catch (SQLException e) { - log.error("SQL exception when deleting event notification subscription data.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_DELETING_EVENT_SUBSCRIPTION); - } - } - - @Override - public Boolean deleteSubscribedEventTypes(Connection connection, String subscriptionId) - throws OBEventNotificationException { - boolean isDeleted = false; - int affectedRowsCount; - final String deleteEventTypesQuery = sqlStatements.deleteSubscribedEventTypesQuery(); - try (PreparedStatement deleteEventTypesStatement = connection.prepareStatement(deleteEventTypesQuery)) { - deleteEventTypesStatement.setString(1, subscriptionId); - affectedRowsCount = deleteEventTypesStatement.executeUpdate(); - if (affectedRowsCount > 0) { - log.debug("Successfully deleted the subscribed event types"); - isDeleted = true; - } - } catch (SQLException e) { - log.error("SQL exception when deleting subscribed event types. ", e); - throw new OBEventNotificationException( - "Error occurred while deleting the event notification subscription."); - } - return isDeleted; - } - - private void mapResultSetToEventSubscription(EventSubscription response, ResultSet resultSet) throws SQLException { - response.setSubscriptionId(resultSet.getString(EventNotificationConstants.SUBSCRIPTION_ID)); - response.setClientId(resultSet.getString(EventNotificationConstants.CLIENT_ID)); - response.setCallbackUrl(resultSet.getString(EventNotificationConstants.CALLBACK_URL)); - response.setTimeStamp(resultSet.getLong(EventNotificationConstants.TIME_STAMP)); - response.setSpecVersion(resultSet.getString(EventNotificationConstants.SPEC_VERSION)); - response.setStatus(resultSet.getString(EventNotificationConstants.STATUS)); - response.setRequestData(resultSet.getString(EventNotificationConstants.REQUEST)); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionSqlStatements.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionSqlStatements.java deleted file mode 100644 index ee06d675..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionSqlStatements.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023-2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -/** - * SQL queries to store, retrieve, update and delete event notification subscriptions. - */ -public class EventSubscriptionSqlStatements { - - public String storeEventSubscriptionQuery() { - return "INSERT INTO OB_NOTIFICATION_SUBSCRIPTION (SUBSCRIPTION_ID, CLIENT_ID, CALLBACK_URL, TIMESTAMP, " + - "SPEC_VERSION, STATUS, REQUEST) VALUES (?,?,?,?,?,?,?)"; - } - - public String storeSubscribedEventTypesQuery() { - return "INSERT INTO OB_NOTIFICATION_SUBSCRIBED_EVENTS (SUBSCRIPTION_ID, EVENT_TYPE) VALUES (?,?)"; - } - - public String getEventSubscriptionBySubscriptionIdQuery() { - return "SELECT ns.SUBSCRIPTION_ID, ns.CLIENT_ID, ns.REQUEST, ns.CALLBACK_URL, ns.TIMESTAMP, ns.SPEC_VERSION, " + - "ns.STATUS, nse.EVENT_TYPE FROM OB_NOTIFICATION_SUBSCRIPTION ns LEFT JOIN " + - "OB_NOTIFICATION_SUBSCRIBED_EVENTS nse ON ns.SUBSCRIPTION_ID = nse.SUBSCRIPTION_ID WHERE " + - "ns.SUBSCRIPTION_ID = ? AND ns.STATUS = 'CREATED'"; - } - - public String getEventSubscriptionsByClientIdQuery() { - return "SELECT ns.SUBSCRIPTION_ID, ns.CLIENT_ID, ns.REQUEST, ns.CALLBACK_URL, ns.TIMESTAMP, ns.SPEC_VERSION, " + - "ns.STATUS, nse.EVENT_TYPE FROM OB_NOTIFICATION_SUBSCRIPTION ns LEFT JOIN " + - "OB_NOTIFICATION_SUBSCRIBED_EVENTS nse ON ns.SUBSCRIPTION_ID = nse.SUBSCRIPTION_ID WHERE " + - "ns.CLIENT_ID = ? AND ns.STATUS = 'CREATED'"; - } - - public String getEventSubscriptionsByEventTypeQuery() { - return "SELECT ns.SUBSCRIPTION_ID, ns.CLIENT_ID, ns.REQUEST, ns.CALLBACK_URL, ns.TIMESTAMP, ns.SPEC_VERSION, " + - "ns.STATUS, nse.EVENT_TYPE FROM OB_NOTIFICATION_SUBSCRIPTION ns LEFT JOIN " + - "OB_NOTIFICATION_SUBSCRIBED_EVENTS nse ON ns.SUBSCRIPTION_ID = nse.SUBSCRIPTION_ID WHERE " + - "ns.SUBSCRIPTION_ID IN (SELECT ns.SUBSCRIPTION_ID FROM OB_NOTIFICATION_SUBSCRIPTION ns LEFT " + - "JOIN OB_NOTIFICATION_SUBSCRIBED_EVENTS nse ON ns.SUBSCRIPTION_ID = nse.SUBSCRIPTION_ID WHERE " + - "nse.EVENT_TYPE = ? AND ns.STATUS = 'CREATED')"; - } - - public String updateEventSubscriptionQuery() { - return "UPDATE OB_NOTIFICATION_SUBSCRIPTION SET CALLBACK_URL = ?, TIMESTAMP = ?, REQUEST = ?" + - "WHERE SUBSCRIPTION_ID = ?"; - } - - public String updateEventSubscriptionStatusQuery() { - return "UPDATE OB_NOTIFICATION_SUBSCRIPTION SET STATUS = ? WHERE SUBSCRIPTION_ID = ? AND STATUS = 'CREATED'"; - } - - public String deleteSubscribedEventTypesQuery() { - return "DELETE FROM OB_NOTIFICATION_SUBSCRIBED_EVENTS WHERE SUBSCRIPTION_ID = ?"; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/MSSQLNotificationPollingSqlStatements.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/MSSQLNotificationPollingSqlStatements.java deleted file mode 100644 index e1c879d2..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/MSSQLNotificationPollingSqlStatements.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.util.Generated; - -/** - * MSSQL Queries for Event Polling. - */ -@Generated(message = "Returns sql statements to the dao method") -public class MSSQLNotificationPollingSqlStatements extends NotificationPollingSqlStatements { - - @Override - public String getMaxNotificationsQuery() { - - return "SELECT * FROM OB_NOTIFICATION WHERE CLIENT_ID = ? AND STATUS = ? ORDER BY NOTIFICATION_ID " + - "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/NotificationPollingSqlStatements.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/NotificationPollingSqlStatements.java deleted file mode 100644 index 9b1e553c..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/NotificationPollingSqlStatements.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -/** - * SQL queries to store and retrieve event notifications. - */ -public class NotificationPollingSqlStatements { - - public String getEventsByNotificationIdQuery() { - - return "SELECT * FROM OB_NOTIFICATION_EVENT WHERE NOTIFICATION_ID = ?"; - } - - public String getMaxNotificationsQuery() { - - return "SELECT * FROM OB_NOTIFICATION WHERE CLIENT_ID = ? AND STATUS = ? LIMIT ?"; - } - - public String getNotificationsCountQuery() { - - return "SELECT COUNT(*) AS NOTIFICATION_COUNT FROM OB_NOTIFICATION WHERE CLIENT_ID = ? AND STATUS = ?"; - } - - public String storeErrorNotificationQuery() { - - return "INSERT INTO OB_NOTIFICATION_ERROR (NOTIFICATION_ID, ERROR_CODE, DESCRIPTION) VALUES (?,?,?)"; - } - - public String updateNotificationStatusQueryById() { - - return "UPDATE OB_NOTIFICATION SET STATUS = ?, UPDATED_TIMESTAMP= ? WHERE NOTIFICATION_ID = ?"; - } - - public String getNotificationByNotificationId() { - - return "SELECT NOTIFICATION_ID, STATUS FROM OB_NOTIFICATION WHERE NOTIFICATION_ID = ?"; - } - - public String getNotificationsByState() { - - return "SELECT * FROM OB_NOTIFICATION WHERE STATUS = ?"; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/NotificationPublisherSqlStatements.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/NotificationPublisherSqlStatements.java deleted file mode 100644 index 292dde5c..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/NotificationPublisherSqlStatements.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -/** - * SQL statements to store event notifications. - */ -public class NotificationPublisherSqlStatements { - - public String getStoreNotification() { - - final String storeNotifications = "INSERT INTO OB_NOTIFICATION (NOTIFICATION_ID, CLIENT_ID, " + - "RESOURCE_ID, STATUS) VALUES (?,?,?,?)"; - return storeNotifications; - } - - public String getStoreNotificationEvents() { - - final String storeNotificationEvents = - "INSERT INTO OB_NOTIFICATION_EVENT (NOTIFICATION_ID, EVENT_TYPE, EVENT_INFO) VALUES (?,?,?)"; - return storeNotificationEvents; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlEventSubscriptionDAOImpl.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlEventSubscriptionDAOImpl.java deleted file mode 100644 index e3d56cff..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlEventSubscriptionDAOImpl.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Postgres SQL EventSubscriptionDAO Impl. - */ -public class PostgreSqlEventSubscriptionDAOImpl extends EventSubscriptionDAOImpl { - - private static final Log log = LogFactory.getLog(PostgreSqlEventSubscriptionDAOImpl.class); - - public PostgreSqlEventSubscriptionDAOImpl(EventSubscriptionSqlStatements sqlStatements) { - super(sqlStatements); - } - - @Override - public EventSubscription storeEventSubscription(Connection connection, EventSubscription eventSubscription) - throws OBEventNotificationException { - - int storeSubscriptionAffectedRows; - - UUID subscriptionId = UUID.randomUUID(); - long unixTime = Instant.now().getEpochSecond(); - eventSubscription.setSubscriptionId(subscriptionId.toString()); - eventSubscription.setTimeStamp(unixTime); - eventSubscription.setStatus(EventNotificationConstants.CREATED); - - final String sql = sqlStatements.storeEventSubscriptionQuery(); - try (PreparedStatement storeEventSubscriptionStatement = connection.prepareStatement(sql)) { - storeEventSubscriptionStatement.setString(1, eventSubscription.getSubscriptionId()); - storeEventSubscriptionStatement.setString(2, eventSubscription.getClientId()); - storeEventSubscriptionStatement.setString(3, eventSubscription.getCallbackUrl()); - storeEventSubscriptionStatement.setLong(4, eventSubscription.getTimeStamp()); - storeEventSubscriptionStatement.setString(5, eventSubscription.getSpecVersion()); - storeEventSubscriptionStatement.setString(6, eventSubscription.getStatus()); - storeEventSubscriptionStatement.setObject(7, eventSubscription.getRequestData(), - java.sql.Types.OTHER); - storeSubscriptionAffectedRows = storeEventSubscriptionStatement.executeUpdate(); - if (storeSubscriptionAffectedRows == 0) { - log.error("Failed to store the event notification subscription."); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when storing the event types of the subscription", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION); - } - return eventSubscription; - } - - @Override - public List getEventSubscriptionsByClientId(Connection connection, String clientId) - throws OBEventNotificationException { - List retrievedSubscriptions = new ArrayList<>(); - - final String sql = sqlStatements.getEventSubscriptionsByClientIdQuery(); - try (PreparedStatement getEventSubscriptionsByClientIdStatement = connection.prepareStatement(sql, - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - getEventSubscriptionsByClientIdStatement.setString(1, clientId); - try (ResultSet resultSet = getEventSubscriptionsByClientIdStatement.executeQuery()) { - if (resultSet.isBeforeFirst()) { - while (resultSet.next()) { - EventSubscription eventSubscription = new EventSubscription(); - List eventTypes = new ArrayList<>(); - mapResultSetToEventSubscription(eventSubscription, resultSet); - resultSet.previous(); - while (resultSet.next()) { - if (eventSubscription.getSubscriptionId().equals(resultSet. - getString(EventNotificationConstants.SUBSCRIPTION_ID))) { - if (resultSet.getString(EventNotificationConstants.EVENT_TYPE) != null) { - eventTypes.add(resultSet.getString(EventNotificationConstants.EVENT_TYPE)); - } - } else { - resultSet.previous(); - break; - } - } - if (!eventTypes.isEmpty()) { - eventSubscription.setEventTypes(eventTypes); - } - retrievedSubscriptions.add(eventSubscription); - } - log.debug("Retrieved the event notification subscriptions successfully."); - } - return retrievedSubscriptions; - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscriptions.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscriptions.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS); - } - } - - @Override - public EventSubscription getEventSubscriptionBySubscriptionId(Connection connection, String subscriptionId) - throws OBEventNotificationException { - EventSubscription retrievedSubscription = new EventSubscription(); - List eventTypes = new ArrayList<>(); - - final String sql = sqlStatements.getEventSubscriptionBySubscriptionIdQuery(); - try (PreparedStatement getEventSubscriptionBySubscriptionIdStatement = connection.prepareStatement(sql, - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - getEventSubscriptionBySubscriptionIdStatement.setString(1, subscriptionId); - try (ResultSet resultSet = getEventSubscriptionBySubscriptionIdStatement.executeQuery()) { - if (resultSet.next()) { - mapResultSetToEventSubscription(retrievedSubscription, resultSet); - resultSet.beforeFirst(); // Reset the cursor position to the beginning of the result set. - while (resultSet.next()) { - String eventType = resultSet.getString(EventNotificationConstants.EVENT_TYPE); - if (eventType != null) { - eventTypes.add(eventType); - } - } - if (!eventTypes.isEmpty()) { - retrievedSubscription.setEventTypes(eventTypes); - } - } else { - log.error("No event notification subscription found for the given subscription id."); - throw new OBEventNotificationException( - EventNotificationConstants.EVENT_SUBSCRIPTION_NOT_FOUND); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscription.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - } catch (SQLException e) { - log.error("SQL exception when retrieving the event notification subscription.", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_RETRIEVING_EVENT_SUBSCRIPTION); - } - return retrievedSubscription; - } - - @Override - public Boolean updateEventSubscription(Connection connection, EventSubscription eventSubscription) - throws OBEventNotificationException { - boolean isUpdated = false; - final String sql = sqlStatements.updateEventSubscriptionQuery(); - try (PreparedStatement updateEventSubscriptionStatement = connection.prepareStatement(sql)) { - updateEventSubscriptionStatement.setString(1, eventSubscription.getCallbackUrl()); - updateEventSubscriptionStatement.setLong(2, Instant.now().getEpochSecond()); - updateEventSubscriptionStatement.setObject(3, eventSubscription.getRequestData(), - java.sql.Types.OTHER); - updateEventSubscriptionStatement.setString(4, eventSubscription.getSubscriptionId()); - int affectedRows = updateEventSubscriptionStatement.executeUpdate(); - if (affectedRows > 0) { - log.debug("Event notification subscription is successfully updated."); - isUpdated = true; - } - } catch (SQLException e) { - log.error("SQL exception when updating event notification subscription", e); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_UPDATING_EVENT_SUBSCRIPTION); - } - return isUpdated; - } - - private void mapResultSetToEventSubscription(EventSubscription response, ResultSet resultSet) throws SQLException { - response.setSubscriptionId(resultSet.getString(EventNotificationConstants.SUBSCRIPTION_ID)); - response.setClientId(resultSet.getString(EventNotificationConstants.CLIENT_ID)); - response.setCallbackUrl(resultSet.getString(EventNotificationConstants.CALLBACK_URL)); - response.setTimeStamp(resultSet.getLong(EventNotificationConstants.TIME_STAMP)); - response.setSpecVersion(resultSet.getString(EventNotificationConstants.SPEC_VERSION)); - response.setStatus(resultSet.getString(EventNotificationConstants.STATUS)); - response.setRequestData(resultSet.getString(EventNotificationConstants.REQUEST)); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlPollingDAOImpl.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlPollingDAOImpl.java deleted file mode 100644 index 0421e4ec..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlPollingDAOImpl.java +++ /dev/null @@ -1,250 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -/** - * PostgreSql event polling dao class. - */ -@Generated(message = "Postgres Implementation") -public class PostgreSqlPollingDAOImpl extends AggregatedPollingDAOImpl { - - private static Log log = LogFactory.getLog(PostgreSqlPollingDAOImpl.class); - - public PostgreSqlPollingDAOImpl(NotificationPollingSqlStatements notificationPollingSqlStatements) { - super(notificationPollingSqlStatements); - } - - @Override - public List getNotificationsByClientIdAndStatus(String clientId, String status, int max) - throws OBEventNotificationException { - - List notificationList; - Connection connection = DatabaseUtil.getDBConnection(); - try { - - notificationList = new ArrayList<>(); - - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.DB_CONN_ESTABLISHED, - clientId.replaceAll("[\r\n]", ""))); - } - - final String sql = sqlStatements.getMaxNotificationsQuery(); - try (PreparedStatement getNotificationsPreparedStatement = connection.prepareStatement(sql, - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - getNotificationsPreparedStatement.setString(1, clientId); - getNotificationsPreparedStatement.setString(2, status); - getNotificationsPreparedStatement.setInt(3, max); - - try (ResultSet notificationResultSet = getNotificationsPreparedStatement.executeQuery()) { - if (notificationResultSet.next()) { - - //bring pointer back to the top of the result set if not on the top - if (!notificationResultSet.isBeforeFirst()) { - notificationResultSet.beforeFirst(); - } - - //read event notifications from the result set - while (notificationResultSet.next()) { - NotificationDTO notification = new NotificationDTO(); - - notification.setNotificationId(notificationResultSet.getString - (EventNotificationConstants.NOTIFICATION_ID)); - notification.setClientId(notificationResultSet.getString - (EventNotificationConstants.CLIENT_ID)); - notification.setResourceId(notificationResultSet.getString - (EventNotificationConstants.RESOURCE_ID)); - notification.setStatus(notificationResultSet.getString - (EventNotificationConstants.STATUS)); - notification.setUpdatedTimeStamp((notificationResultSet.getTimestamp( - (EventNotificationConstants.UPDATED_TIMESTAMP)).getTime())); - - notificationList.add(notification); - } - notificationResultSet.close(); - getNotificationsPreparedStatement.close(); - - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.RETRIEVED_NOTIFICATION_CLIENT, - clientId.replaceAll("[\r\n]", ""))); - } - - } else { - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.NO_NOTIFICATIONS_FOUND_CLIENT, - clientId.replaceAll("[\r\n]", ""))); - } - } - } - } catch (SQLException e) { - throw new OBEventNotificationException(String.format - (EventNotificationConstants.DB_ERROR_NOTIFICATION_RETRIEVE, - clientId), e); - } - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return notificationList; - } - - @Override - public List getEventsByNotificationID(String notificationId) - throws OBEventNotificationException { - - List eventList = new ArrayList<>(); - - Connection connection = DatabaseUtil.getDBConnection(); - try { - - final String sql = sqlStatements.getEventsByNotificationIdQuery(); - - try (PreparedStatement getEventsPreparedStatement = connection.prepareStatement(sql, - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - - getEventsPreparedStatement.setString(1, notificationId); - - try (ResultSet eventsResultSet = getEventsPreparedStatement.executeQuery()) { - if (eventsResultSet.next()) { - - //bring pointer back to the top of the result set if not on the top - if (!eventsResultSet.isBeforeFirst()) { - eventsResultSet.beforeFirst(); - } - - //read event notifications from the result set - while (eventsResultSet.next()) { - NotificationEvent event = new NotificationEvent(); - event.setNotificationId(eventsResultSet.getString - (EventNotificationConstants.NOTIFICATION_ID)); - event.setEventType(eventsResultSet.getString - (EventNotificationConstants.EVENT_TYPE)); - event.setEventInformation(EventNotificationServiceUtil. - getEventJSONFromString(eventsResultSet.getString - (EventNotificationConstants.EVENT_INFO))); - eventList.add(event); - } - eventsResultSet.close(); - getEventsPreparedStatement.close(); - - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.RETRIEVED_EVENTS_NOTIFICATION, - notificationId.replaceAll("[\r\n]", ""))); - } - } else { - if (log.isDebugEnabled()) { - log.debug(String.format(EventNotificationConstants.NO_EVENTS_NOTIFICATION_ID, - notificationId.replaceAll("[\r\n]", ""))); - } - } - } catch (ParseException e) { - log.error(String.format(EventNotificationConstants.PARSE_ERROR_NOTIFICATION_ID, - notificationId.replaceAll("[\r\n]", "")), e); - throw new OBEventNotificationException(String.format ( - EventNotificationConstants.PARSE_ERROR_NOTIFICATION_ID, notificationId), e); - } - } catch (SQLException e) { - log.error(String.format(EventNotificationConstants.DB_ERROR_EVENTS_RETRIEVE, - notificationId.replaceAll("[\r\n]", "")), e); - throw new OBEventNotificationException(String.format - (EventNotificationConstants.DB_ERROR_EVENTS_RETRIEVE, notificationId), e); - } - - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - - return eventList; - } - - @Override - public List getNotificationsByStatus(String status) - throws OBEventNotificationException { - List notificationList; - Connection connection = DatabaseUtil.getDBConnection(); - try { - notificationList = new ArrayList<>(); - final String sql = sqlStatements.getMaxNotificationsQuery(); - try (PreparedStatement getNotificationsPreparedStatement = connection.prepareStatement(sql, - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - getNotificationsPreparedStatement.setString(1, status); - try (ResultSet notificationResultSet = getNotificationsPreparedStatement.executeQuery()) { - if (notificationResultSet.next()) { - //bring pointer back to the top of the result set if not on the top - if (!notificationResultSet.isBeforeFirst()) { - notificationResultSet.beforeFirst(); - } - //read event notifications from the result set - while (notificationResultSet.next()) { - NotificationDTO notification = new NotificationDTO(); - notification.setNotificationId(notificationResultSet.getString - (EventNotificationConstants.NOTIFICATION_ID)); - notification.setClientId(notificationResultSet.getString - (EventNotificationConstants.CLIENT_ID)); - notification.setResourceId(notificationResultSet.getString - (EventNotificationConstants.RESOURCE_ID)); - notification.setStatus(notificationResultSet.getString - (EventNotificationConstants.STATUS)); - notification.setUpdatedTimeStamp((notificationResultSet.getTimestamp( - (EventNotificationConstants.UPDATED_TIMESTAMP)).getTime())); - notificationList.add(notification); - } - notificationResultSet.close(); - getNotificationsPreparedStatement.close(); - if (log.isDebugEnabled()) { - log.debug( - EventNotificationConstants.RETRIEVED_NOTIFICATION_CLIENT); - } - } else { - if (log.isDebugEnabled()) { - log.debug( - EventNotificationConstants.NO_NOTIFICATIONS_FOUND_CLIENT); - } - } - } - } catch (SQLException e) { - throw new OBEventNotificationException( - EventNotificationConstants.DB_ERROR_NOTIFICATION_RETRIEVE, e); - } - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - return notificationList; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventNotificationErrorDTO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventNotificationErrorDTO.java deleted file mode 100644 index 1121b211..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventNotificationErrorDTO.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dto; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Error model for Event Notifications. - */ -public class EventNotificationErrorDTO { - - private String errorDescription; - private String error; - - @JsonProperty("error_description") - public String getErrorDescription() { - - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - - this.errorDescription = errorDescription; - } - - @JsonProperty("error") - public String getError() { - - return error; - } - - public void setError(String error) { - - this.error = error; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventPollingDTO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventPollingDTO.java deleted file mode 100644 index 8fb476f9..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventPollingDTO.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dto; - -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Event Polling DTO. - */ -public class EventPollingDTO { - - //Set to true by default as WSO2 Open Banking don't support long polling - private final Boolean returnImmediately = true; - private String clientId = null; - private int maxEvents = 0; - private List ack = new ArrayList<>(); - private Map errors = new HashMap<>(); - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public Boolean getReturnImmediately() { - return returnImmediately; - } - - public int getMaxEvents() { - return maxEvents; - } - - public void setMaxEvents(int maxEvents) { - this.maxEvents = maxEvents; - } - - public List getAck() { - return ack; - } - - public void setAck(String ack) { - this.ack.add(ack); - } - - public Map getErrors() { - return errors; - } - - public void setErrors(String notificationId, NotificationError errorNotification) { - this.errors.put(notificationId, errorNotification); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventSubscriptionDTO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventSubscriptionDTO.java deleted file mode 100644 index 3f19bd42..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/EventSubscriptionDTO.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dto; - -import net.minidev.json.JSONObject; - -/** - * Event Subscription DTO. - */ -public class EventSubscriptionDTO { - private String clientId = null; - private String subscriptionId = null; - private JSONObject requestData = null; - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getSubscriptionId() { - return subscriptionId; - } - - public void setSubscriptionId(String subscriptionId) { - this.subscriptionId = subscriptionId; - } - - public JSONObject getRequestData() { - return requestData; - } - - public void setRequestData(JSONObject requestData) { - this.requestData = requestData; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/NotificationCreationDTO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/NotificationCreationDTO.java deleted file mode 100644 index 2985c359..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/NotificationCreationDTO.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dto; - -import net.minidev.json.JSONObject; - -import java.util.HashMap; -import java.util.Map; - -/** - * Event Creation DTO. - */ -public class NotificationCreationDTO { - - private Map events = new HashMap(); - private String clientId = null; - private String resourceId = null; - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public Map getEventPayload() { - return this.events; - } - - public void setEventPayload(String notificationType, JSONObject notificationInfo) { - this.events.put(notificationType, notificationInfo); - } -} - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/NotificationDTO.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/NotificationDTO.java deleted file mode 100644 index b8ae5e20..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/dto/NotificationDTO.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dto; - -/** - * DAO class to map notification data to db. - */ -public class NotificationDTO { - String notificationId = null; - String clientId = null; - String resourceId = null; - String status = null; - Long updatedTimeStamp = null; - - public String getNotificationId() { - return notificationId; - } - - public void setNotificationId(String notificationId) { - this.notificationId = notificationId; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public Long getUpdatedTimeStamp() { - return updatedTimeStamp; - } - - public void setUpdatedTimeStamp(Long updatedTimeStamp) { - this.updatedTimeStamp = updatedTimeStamp; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/exceptions/OBEventNotificationException.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/exceptions/OBEventNotificationException.java deleted file mode 100644 index acd42226..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/exceptions/OBEventNotificationException.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.exceptions; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * Event Notification Exceptions. - */ -public class OBEventNotificationException extends OpenBankingException { - - public OBEventNotificationException(String message) { - super(message); - } - - public OBEventNotificationException(String message, Throwable e) { - super(message, e); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventCreationServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventCreationServiceHandler.java deleted file mode 100644 index df5bd14a..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventCreationServiceHandler.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationCreationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventCreationService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * This is to handle OB Event Creation. - */ -public class DefaultEventCreationServiceHandler implements EventCreationServiceHandler { - - private static final Log log = LogFactory.getLog(DefaultEventCreationServiceHandler.class); - private EventCreationService eventCreationService = new EventCreationService(); - - public void setEventCreationService(EventCreationService eventCreationService) { - this.eventCreationService = eventCreationService; - } - - /** - * This method is used to publish OB events in the accelerator database. - * - * @param notificationCreationDTO Notification details DTO - * @return EventCreationResponse Response after event creation - */ - public EventCreationResponse publishOBEvent(NotificationCreationDTO notificationCreationDTO) { - - //validate if the resourceID is existing - ConsentResource consentResource = null; - ConsentCoreServiceImpl consentCoreService = EventNotificationServiceUtil.getConsentCoreServiceImpl(); - EventCreationResponse eventCreationResponse = new EventCreationResponse(); - - try { - consentResource = consentCoreService.getConsent(notificationCreationDTO.getResourceId(), - false); - - if (log.isDebugEnabled()) { - log.debug("Consent resource available for resource ID " + - consentResource.getConsentID().replaceAll("[\r\n]", "")); - } - } catch (ConsentManagementException e) { - log.error("Consent Management Exception when validating the consent resource", e); - eventCreationResponse.setErrorResponse(String.format("A resource was not found for the resource " + - "id : '%s' in the database. ", notificationCreationDTO.getResourceId())); - eventCreationResponse.setStatus(EventNotificationConstants.BAD_REQUEST); - return eventCreationResponse; - } - - //validate if the clientID is existing - try { - EventNotificationServiceUtil.validateClientId(notificationCreationDTO.getClientId()); - - } catch (OBEventNotificationException e) { - log.error("Invalid client ID", e); - eventCreationResponse.setErrorResponse(String.format("A client was not found" + - " for the client id : '%s' in the database. ", - notificationCreationDTO.getClientId().replaceAll("[\r\n]", ""))); - eventCreationResponse.setStatus(EventNotificationConstants.BAD_REQUEST); - return eventCreationResponse; - } - - String registrationResponse = ""; - try { - registrationResponse = eventCreationService.publishOBEventNotification(notificationCreationDTO); - JSONObject responseJSON = new JSONObject(); - responseJSON.put(EventNotificationConstants.NOTIFICATIONS_ID, registrationResponse); - eventCreationResponse.setStatus(EventNotificationConstants.CREATED); - eventCreationResponse.setResponseBody(responseJSON); - return eventCreationResponse; - - } catch (OBEventNotificationException e) { - log.error("OB Event Notification Creation error", e); - } - - eventCreationResponse.setStatus(EventNotificationConstants.BAD_REQUEST); - eventCreationResponse.setErrorResponse("Error in event creation request payload"); - return eventCreationResponse; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventPollingServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventPollingServiceHandler.java deleted file mode 100644 index 9372f04d..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventPollingServiceHandler.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventPollingDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.AggregatedPollingResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventPollingResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventPollingService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Locale; - -/** - * This is the service handler for event polling. - */ -public class DefaultEventPollingServiceHandler implements EventPollingServiceHandler { - - private static final Log log = LogFactory.getLog(DefaultEventPollingServiceHandler.class); - - public void setEventPollingService(EventPollingService eventPollingService) { - this.eventPollingService = eventPollingService; - } - - private EventPollingService eventPollingService = new EventPollingService(); - - - /** - * This method is used to Poll Events as per request params. - * @param eventPollingRequest JSON request for event polling - * @return EventPollingResponse - */ - public EventPollingResponse pollEvents(JSONObject eventPollingRequest) { - - EventPollingDTO eventPollingDTO = mapPollingRequest(eventPollingRequest); - EventPollingResponse eventPollingResponse = new EventPollingResponse(); - - //Validate clientID of the polling request - try { - EventNotificationServiceUtil.validateClientId(eventPollingDTO.getClientId()); - } catch (OBEventNotificationException e) { - log.error("Invalid client ID", e); - eventPollingResponse.setStatus(EventNotificationConstants.BAD_REQUEST); - eventPollingResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, String.format("A client was not found" + - " for the client id : '%s' in the database.. ", eventPollingDTO.getClientId()))); - return eventPollingResponse; - } - - //Poll events - try { - AggregatedPollingResponse aggregatedPollingResponse = eventPollingService.pollEvents(eventPollingDTO); - eventPollingResponse.setStatus(aggregatedPollingResponse.getStatus()); - eventPollingResponse.setResponseBody(getPollingResponseJSON(aggregatedPollingResponse)); - return eventPollingResponse; - } catch (OBEventNotificationException e) { - log.error("OB Event Notification error" , e); - eventPollingResponse.setStatus(EventNotificationConstants.BAD_REQUEST); - eventPollingResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventPollingResponse; - } - - } - - /** - * This method will map the eventPollingRequest JSON to EventPollingDTO. - * @param eventPollingRequest JSON request for event polling - * @return EventPollingDTO - */ - public EventPollingDTO mapPollingRequest(JSONObject eventPollingRequest) { - - EventPollingDTO eventPollingDTO = new EventPollingDTO(); - eventPollingDTO.setClientId(eventPollingRequest.get(EventNotificationConstants.X_WSO2_CLIENT_ID).toString()); - - if (eventPollingRequest.size() == 0) { - - eventPollingDTO.setMaxEvents(OpenBankingConfigParser.getInstance().getNumberOfSetsToReturn()); - - return eventPollingDTO; - } - - //Set acknowledged events to DTO - if (eventPollingRequest.containsKey(EventNotificationConstants.ACK.toLowerCase(Locale.ROOT))) { - JSONArray acknowledgedEvents = (JSONArray) eventPollingRequest. - get(EventNotificationConstants.ACK.toLowerCase(Locale.ROOT)); - acknowledgedEvents.forEach((event -> { - eventPollingDTO.setAck(event.toString()); - })); - } - - //Set error events to DTO - if (eventPollingRequest.containsKey(EventNotificationConstants.SET_ERRORS)) { - JSONObject errorEvents = (JSONObject) eventPollingRequest. - get(EventNotificationConstants.SET_ERRORS); - errorEvents.keySet().forEach(errorEvent -> { - JSONObject errorEventInformation = (JSONObject) errorEvents.get(errorEvent); - NotificationError notificationError = getNotificationError(errorEventInformation); - notificationError.setNotificationId(errorEvent); - eventPollingDTO.setErrors(errorEvent, notificationError); - }); - } - - //Set maxEvents count to return - if (eventPollingRequest.containsKey(EventNotificationConstants.MAX_EVENTS)) { - eventPollingDTO.setMaxEvents(Integer.parseInt(eventPollingRequest. - get(EventNotificationConstants.MAX_EVENTS).toString())); - } else { - eventPollingDTO.setMaxEvents(OpenBankingConfigParser.getInstance().getNumberOfSetsToReturn()); - } - - return eventPollingDTO; - } - - @Generated(message = "Private method tested when testing the invoked method") - private NotificationError getNotificationError(JSONObject errorEvent) { - - NotificationError notificationError = new NotificationError(); - notificationError.setErrorCode(errorEvent.get( - EventNotificationConstants.ERROR.toLowerCase(Locale.ROOT)).toString()); - notificationError.setErrorDescription( - errorEvent.get(EventNotificationConstants.DESCRIPTION).toString()); - return notificationError; - } - - @Generated(message = "Private method tested when testing the invoked method") - private JSONObject getPollingResponseJSON(AggregatedPollingResponse aggregatedPollingResponse) { - - JSONObject responseJSON = new JSONObject(); - responseJSON.put(EventNotificationConstants.SETS, aggregatedPollingResponse.getSets()); - responseJSON.put(EventNotificationConstants.MORE_AVAILABLE, - aggregatedPollingResponse.isMoreAvailable()); - return responseJSON; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventSubscriptionServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventSubscriptionServiceHandler.java deleted file mode 100644 index e8a281d4..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventSubscriptionServiceHandler.java +++ /dev/null @@ -1,345 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventSubscriptionDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventSubscriptionResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventSubscriptionService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; - -import java.util.ArrayList; -import java.util.List; - -/** - * This is the default service handler for event notification subscription. - */ -public class DefaultEventSubscriptionServiceHandler implements EventSubscriptionServiceHandler { - private static final Log log = LogFactory.getLog(DefaultEventSubscriptionServiceHandler.class); - - private EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - - public void setEventSubscriptionService(EventSubscriptionService eventSubscriptionService) { - this.eventSubscriptionService = eventSubscriptionService; - } - - /** - * This method is used to create event subscriptions. - * - * @param eventSubscriptionRequestDto Event Subscription DTO - * @return EventSubscriptionResponse Event Subscription Response - */ - public EventSubscriptionResponse createEventSubscription(EventSubscriptionDTO eventSubscriptionRequestDto) { - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - - EventSubscriptionResponse clientIdValidation = validateClientId(eventSubscriptionRequestDto.getClientId()); - // check whether clientIdValidation is not null, then return the error response - if (clientIdValidation != null) { - return clientIdValidation; - } - - EventSubscription eventSubscription = mapEventSubscriptionDtoToModel(eventSubscriptionRequestDto); - - try { - EventSubscription createEventSubscriptionResponse = eventSubscriptionService. - createEventSubscription(eventSubscription); - eventSubscriptionResponse.setStatus(HttpStatus.SC_CREATED); - eventSubscriptionResponse. - setResponseBody(mapSubscriptionModelToResponseJson(createEventSubscriptionResponse)); - return eventSubscriptionResponse; - } catch (OBEventNotificationException e) { - log.error("Error occurred while creating event subscription", e); - eventSubscriptionResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventSubscriptionResponse; - } - - } - - /** - * This method is used to retrieve a single event subscription. - * - * @param clientId Client ID of the subscription created - * @param subscriptionId Subscription ID of the subscription created - * @return EventSubscriptionResponse Event Subscription Response containing subscription - * details for the given subscription ID - */ - public EventSubscriptionResponse getEventSubscription(String clientId, String subscriptionId) { - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - - EventSubscriptionResponse clientIdValidation = validateClientId(clientId); - // check whether clientIdValidation is not null, then return the error response - if (clientIdValidation != null) { - return clientIdValidation; - } - - try { - EventSubscription eventSubscription = eventSubscriptionService. - getEventSubscriptionBySubscriptionId(subscriptionId); - eventSubscriptionResponse.setStatus(HttpStatus.SC_OK); - eventSubscriptionResponse.setResponseBody(mapSubscriptionModelToResponseJson(eventSubscription)); - return eventSubscriptionResponse; - } catch (OBEventNotificationException e) { - log.error("Error occurred while retrieving event subscription", e); - if (e.getMessage().equals(EventNotificationConstants.EVENT_SUBSCRIPTION_NOT_FOUND)) { - eventSubscriptionResponse.setStatus(HttpStatus.SC_BAD_REQUEST); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - } else { - eventSubscriptionResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - } - return eventSubscriptionResponse; - } - } - - /** - * This method is used to retrieve all event subscriptions of a client. - * - * @param clientId Client ID - * @return EventSubscriptionResponse Event Subscription Response containing all the subscriptions - */ - public EventSubscriptionResponse getAllEventSubscriptions(String clientId) { - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - - EventSubscriptionResponse clientIdValidation = validateClientId(clientId); - // check whether clientIdValidation is not null, then return the error response - if (clientIdValidation != null) { - return clientIdValidation; - } - - try { - List eventSubscriptionList = eventSubscriptionService. - getEventSubscriptionsByClientId(clientId); - List eventSubscriptionResponseList = new ArrayList<>(); - for (EventSubscription eventSubscription : eventSubscriptionList) { - eventSubscriptionResponseList.add(mapSubscriptionModelToResponseJson(eventSubscription)); - } - eventSubscriptionResponse.setStatus(HttpStatus.SC_OK); - eventSubscriptionResponse.setResponseBody(eventSubscriptionResponseList); - return eventSubscriptionResponse; - } catch (OBEventNotificationException e) { - log.error("Error occurred while retrieving event subscriptions", e); - eventSubscriptionResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventSubscriptionResponse; - } - } - - /** - * This method is used to retrieve all event subscriptions by event type. - * - * @param clientId Client ID - * @param eventType Event Type to retrieve subscriptions - * @return EventSubscriptionResponse Event Subscription Response containing subscriptions per specified - * event type - */ - public EventSubscriptionResponse getEventSubscriptionsByEventType(String clientId, String eventType) { - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - - EventSubscriptionResponse clientIdValidation = validateClientId(clientId); - // check whether clientIdValidation is not null, then return the error response - if (clientIdValidation != null) { - return clientIdValidation; - } - - try { - List eventSubscriptionList = eventSubscriptionService. - getEventSubscriptionsByClientIdAndEventType(eventType); - List eventSubscriptionResponseList = new ArrayList<>(); - for (EventSubscription eventSubscription : eventSubscriptionList) { - eventSubscriptionResponseList.add(mapSubscriptionModelToResponseJson(eventSubscription)); - } - eventSubscriptionResponse.setStatus(HttpStatus.SC_OK); - eventSubscriptionResponse.setResponseBody(eventSubscriptionResponseList); - return eventSubscriptionResponse; - } catch (OBEventNotificationException e) { - log.error("Error occurred while retrieving event subscriptions", e); - eventSubscriptionResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventSubscriptionResponse; - } - } - - /** - * This method is used to update an event subscription. - * - * @param eventSubscriptionUpdateRequestDto Event Subscription Update Request DTO - * @return EventSubscriptionResponse Event Subscription Response containing the updated subscription - */ - public EventSubscriptionResponse updateEventSubscription(EventSubscriptionDTO eventSubscriptionUpdateRequestDto) { - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - - EventSubscriptionResponse clientIdValidation = validateClientId(eventSubscriptionUpdateRequestDto. - getClientId()); - // check whether clientIdValidation is not null, then return the error response - if (clientIdValidation != null) { - return clientIdValidation; - } - - EventSubscription eventSubscription = mapEventSubscriptionDtoToModel(eventSubscriptionUpdateRequestDto); - - try { - Boolean isUpdated = eventSubscriptionService.updateEventSubscription(eventSubscription); - if (!isUpdated) { - eventSubscriptionResponse.setStatus(HttpStatus.SC_BAD_REQUEST); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, - "Event subscription not found.")); - return eventSubscriptionResponse; - } - eventSubscriptionResponse.setStatus(HttpStatus.SC_OK); - EventSubscription eventSubscriptionUpdateResponse = eventSubscriptionService. - getEventSubscriptionBySubscriptionId(eventSubscriptionUpdateRequestDto.getSubscriptionId()); - eventSubscriptionResponse. - setResponseBody(mapSubscriptionModelToResponseJson(eventSubscriptionUpdateResponse)); - return eventSubscriptionResponse; - } catch (OBEventNotificationException e) { - log.error("Error occurred while updating event subscription", e); - eventSubscriptionResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventSubscriptionResponse; - } - } - - /** - * This method is used to delete an event subscription. - * - * @param clientId Client ID - * @param subscriptionId Subscription ID to be deleted - * @return EventSubscriptionResponse Event Subscription Response containing the deleted subscription - */ - public EventSubscriptionResponse deleteEventSubscription(String clientId, String subscriptionId) { - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - - EventSubscriptionResponse clientIdValidation = validateClientId(clientId); - // check whether clientIdValidation is not null, then return the error response - if (clientIdValidation != null) { - return clientIdValidation; - } - try { - Boolean isDeleted = eventSubscriptionService.deleteEventSubscription(subscriptionId); - if (!isDeleted) { - eventSubscriptionResponse.setStatus(HttpStatus.SC_BAD_REQUEST); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, - "Event subscription not found")); - return eventSubscriptionResponse; - } - eventSubscriptionResponse.setStatus(HttpStatus.SC_NO_CONTENT); - return eventSubscriptionResponse; - } catch (OBEventNotificationException e) { - log.error("Error occurred while deleting event subscription", e); - eventSubscriptionResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventSubscriptionResponse; - } - } - - /** - * This method is used to validate the client ID. - * - * @param clientId Client ID - * @return EventSubscriptionResponse Return EventSubscriptionResponse if the client ID is - * invalid, if the client ID is valid, null will be returned. - */ - private EventSubscriptionResponse validateClientId(String clientId) { - try { - EventNotificationServiceUtil.validateClientId(clientId); - } catch (OBEventNotificationException e) { - log.error("Invalid client ID", e); - EventSubscriptionResponse eventSubscriptionResponse = new EventSubscriptionResponse(); - eventSubscriptionResponse.setStatus(HttpStatus.SC_BAD_REQUEST); - eventSubscriptionResponse.setErrorResponse(EventNotificationServiceUtil.getErrorDTO( - EventNotificationConstants.INVALID_REQUEST, e.getMessage())); - return eventSubscriptionResponse; - } - return null; - } - - /** - * This method will map the event subscription DTO to event subscription model - * to be passed to the dao layer. - * - * @param eventSubscriptionDTO Event Subscription DTO - * @return EventSubscription Event Subscription Model mapped - */ - private EventSubscription mapEventSubscriptionDtoToModel(EventSubscriptionDTO eventSubscriptionDTO) { - EventSubscription eventSubscription = new EventSubscription(); - - eventSubscription.setSubscriptionId(eventSubscriptionDTO.getSubscriptionId()); - - JSONObject payload = eventSubscriptionDTO.getRequestData(); - List eventTypes = new ArrayList<>(); - Object eventTypesObj = payload.get(EventNotificationConstants.EVENT_TYPE_PARAM); - if (eventTypesObj instanceof List) { - List eventTypesList = (List) eventTypesObj; - for (Object item : eventTypesList) { - if (item instanceof String) { - eventTypes.add((String) item); - } - } - } - eventSubscription.setEventTypes(eventTypes); - eventSubscription.setCallbackUrl(payload.get(EventNotificationConstants.CALLBACK_URL_PARAM) != null ? - payload.get(EventNotificationConstants.CALLBACK_URL_PARAM).toString() : null); - eventSubscription.setSpecVersion(payload.get(EventNotificationConstants.VERSION_PARAM) != null ? - payload.get(EventNotificationConstants.VERSION_PARAM).toString() : null); - eventSubscription.setClientId(eventSubscriptionDTO.getClientId()); - eventSubscription.setRequestData(payload.toJSONString()); - return eventSubscription; - } - - /** - * This method is used to create the response JSON object from the event subscription model. - * - * @param eventSubscription Event Subscription Model - * @return JSONObject containing mapped subscription - */ - public JSONObject mapSubscriptionModelToResponseJson(EventSubscription eventSubscription) { - JSONObject responsePayload = new JSONObject(); - - if (eventSubscription.getSubscriptionId() != null) { - responsePayload.put(EventNotificationConstants.SUBSCRIPTION_ID_PARAM, - eventSubscription.getSubscriptionId()); - } - if (eventSubscription.getCallbackUrl() != null) { - responsePayload.put(EventNotificationConstants.CALLBACK_URL_PARAM, eventSubscription.getCallbackUrl()); - } - if (eventSubscription.getSpecVersion() != null) { - responsePayload.put(EventNotificationConstants.VERSION_PARAM, eventSubscription.getSpecVersion()); - } - if (eventSubscription.getEventTypes() != null) { - responsePayload.put(EventNotificationConstants.EVENT_TYPE_PARAM, eventSubscription.getEventTypes()); - } - return responsePayload; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventCreationServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventCreationServiceHandler.java deleted file mode 100644 index 671a64c6..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventCreationServiceHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationCreationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; - -/** - * Event creation service handler is used to map the creation request and validate the date before - * calling the service. In need of a custom handling this class can be extended and the extended class - * can be added to the deployment.toml under event_creation_handler to execute the specific class. - */ -public interface EventCreationServiceHandler { - /** - * This method is used to publish OB events in the accelerator database. The method is a generic - * method that is used to persist data into the OB_NOTIFICATION and OB_NOTIFICATION_EVENT tables. - * @param notificationCreationDTO Notification details DTO - * @return For successful request the API will return a JSON with the notificationID - */ - EventCreationResponse publishOBEvent(NotificationCreationDTO notificationCreationDTO); - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventNotificationPersistenceServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventNotificationPersistenceServiceHandler.java deleted file mode 100644 index 720d89a8..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventNotificationPersistenceServiceHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationCreationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.JSONObject; - -/** - * Handler class for persisting event notifications to the database. - */ -public class EventNotificationPersistenceServiceHandler { - private static EventNotificationPersistenceServiceHandler instance = - new EventNotificationPersistenceServiceHandler(); - private DefaultEventCreationServiceHandler defaultEventCreationServiceHandler; - - private EventNotificationPersistenceServiceHandler() { - this.defaultEventCreationServiceHandler = EventNotificationServiceUtil.getDefaultEventCreationServiceHandler(); - } - - public static EventNotificationPersistenceServiceHandler getInstance() { - return instance; - } - - /** - * This method is to persist authorization revoke event. - * - * @param clientId - client ID - * @param resourceId - resource ID - * @param notificationType - notification type - * @param notificationInfo - notification info - * @return EventCreationResponse - */ - public EventCreationResponse persistRevokeEvent(String clientId, - String resourceId, - String notificationType, JSONObject notificationInfo) { - NotificationCreationDTO notificationCreationDTO = - new NotificationCreationDTO(); - notificationCreationDTO.setClientId(clientId); - notificationCreationDTO.setResourceId(resourceId); - notificationCreationDTO.setEventPayload(notificationType, notificationInfo); - return defaultEventCreationServiceHandler.publishOBEvent(notificationCreationDTO); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventPollingServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventPollingServiceHandler.java deleted file mode 100644 index 30a02dfe..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventPollingServiceHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventPollingDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventPollingResponse; -import net.minidev.json.JSONObject; - -/** - * EventPolling Service handler is used to validate and map the polling request to the DTO before calling the - * polling service. For custom validations this class can be extended and the extended class - * can be added to the deployment.toml under event_polling_handler to execute the specific class. - */ -public interface EventPollingServiceHandler { - /** - * This method follows the IETF Specification for SET delivery over HTTP. - * The method supports event acknowledgment in both positive and negative. - * Also, can be used to POLL for available OPEN notifications. - * @param eventPollingRequest JSON request for event polling - * @return EventPollingResponse to the polling endpoint. - */ - EventPollingResponse pollEvents(JSONObject eventPollingRequest); - - /** - * This method is used to map the eventPollingRequest to EventPollingDTO. - * @param eventPollingRequest JSON request for event polling - * @return eventPollingDTO with the request parameters. - */ - EventPollingDTO mapPollingRequest(JSONObject eventPollingRequest); - -} - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventSubscriptionServiceHandler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventSubscriptionServiceHandler.java deleted file mode 100644 index ad161311..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventSubscriptionServiceHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventSubscriptionDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventSubscriptionResponse; -import net.minidev.json.JSONObject; - -/** - * EventSubscription Service handler is used to validate subscription requests before calling the - * subscription service. For custom validations this class can be extended and the extended class - * can be added to the deployment.toml under event_subscription_handler to execute the specific class. - */ -public interface EventSubscriptionServiceHandler { - - /** - * This method is used to create event subscriptions in the accelerator database. The method is a generic - * method that is used to persist data into the NOTIFICATION_SUBSCRIPTION and NOTIFICATION_SUBSCRIPTION_EVENT - * tables. - * - * @param eventSubscriptionRequestDto The request DTO that contains the subscription details. - * @return For successful request the API will return a JSON with the subscriptionId - */ - EventSubscriptionResponse createEventSubscription(EventSubscriptionDTO eventSubscriptionRequestDto); - - /** - * This method is used to retrieve an event subscription by its subscription ID. - * - * @param clientId The client ID of the subscription. - * @param subscriptionId The subscription ID of the subscription. - * @return For successful request the API will return a JSON with the retrieved Subscription. - */ - EventSubscriptionResponse getEventSubscription(String clientId, String subscriptionId); - - /** - * This method is used to retrieve all event subscriptions of a client. - * - * @param clientId The client ID of the subscription. - * @return For successful request the API will return a JSON with the retrieved Subscriptions. - */ - EventSubscriptionResponse getAllEventSubscriptions(String clientId); - - /** - * This method is used to retrieve all event subscriptions by event type. - * - * @param clientId The client ID of the subscription. - * @param eventType The event type that needs to be subscribed by the retrieving subscriptions. - * @return For successful request the API will return a JSON with the retrieved Subscriptions. - */ - EventSubscriptionResponse getEventSubscriptionsByEventType(String clientId, String eventType); - - /** - * This method is used to update an event subscription. - * - * @param eventSubscriptionUpdateRequestDto The request DTO that contains the updating subscription details. - * @return For successful request the API will return a JSON with the updated Subscription. - */ - EventSubscriptionResponse updateEventSubscription(EventSubscriptionDTO eventSubscriptionUpdateRequestDto); - - /** - * This method is used to delete an event subscription. - * - * @param clientId The client ID of the subscription. - * @param subscriptionId The subscription ID of the subscription. - * @return For successful request the API will an OK response. - */ - EventSubscriptionResponse deleteEventSubscription(String clientId, String subscriptionId); - - /** - * This method is used to create the response JSON object from the event subscription model. - * - * @param eventSubscription The event subscription model. - * @return JSONObject - */ - JSONObject mapSubscriptionModelToResponseJson(EventSubscription eventSubscription); - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/internal/EventNotificationComponent.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/internal/EventNotificationComponent.java deleted file mode 100644 index 7b813677..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/internal/EventNotificationComponent.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.service.RealtimeEventNotificationLoaderService; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.util. - activator.PeriodicalEventNotificationConsumerJobActivator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.identity.oauth2.OAuth2Service; - -/** - * The Component class for activating event notification osgi service. - */ -@Component( - name = "com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationComponent", - immediate = true) -public class EventNotificationComponent { - private static Log log = LogFactory.getLog(EventNotificationComponent.class); - - @Activate - protected void activate(ComponentContext context) { - if (log.isDebugEnabled()) { - log.debug("Event Notification Service Component Activated"); - } - - // Check if realtime event notification enabled - if (OpenBankingConfigParser.getInstance().isRealtimeEventNotificationEnabled()) { - /* - * Initialize the blocking queue for storing the realtime event notifications - * Initialize the quartz job for consuming the realtime event notifications - * Initialize the thread for producing the open state realtime event notifications - */ - new Thread(new RealtimeEventNotificationLoaderService()).start(); - new PeriodicalEventNotificationConsumerJobActivator().activate(); - } - } - - /** - * Setters for the descendent OSGI services of the EventNotificationComponent. - * This is added to run the EventNotification OSGI component after the Common module - * @param openBankingConfigurationService OpenBankingConfigurationService - */ - @Reference( - service = OpenBankingConfigurationService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigService" - ) - public void setConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - EventNotificationDataHolder.getInstance().setOpenBankingConfigurationService(openBankingConfigurationService); - } - - public void unsetConfigService(OpenBankingConfigurationService openBankingConfigurationService) { - EventNotificationDataHolder.getInstance().setOpenBankingConfigurationService(null); - } - - /** - * Setters for the descendent OSGI services of the EventNotificationComponent. - * This is added to run the EventNotification OSGI component after the OAuth2Service - */ - @Reference( - service = OAuth2Service.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetOAuth2Service" - ) - - /** - * Setters for the descendent OSGI services of the EventNotificationComponent. - * @param oAuth2Service OAuth2Service - */ - public void setOAuth2Service(OAuth2Service oAuth2Service) { - } - - public void unsetOAuth2Service(OAuth2Service oAuth2Service) { - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/internal/EventNotificationDataHolder.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/internal/EventNotificationDataHolder.java deleted file mode 100644 index 36317c3a..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/internal/EventNotificationDataHolder.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.internal; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.model.RealtimeEventNotification; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.concurrent.LinkedBlockingQueue; - -/** - * Data holder for Open Banking Event Notifications. - */ -public class EventNotificationDataHolder { - private static Log log = LogFactory.getLog(EventNotificationDataHolder.class); - private static volatile EventNotificationDataHolder instance; - private volatile LinkedBlockingQueue realtimeEventNotificationQueue; - private OpenBankingConfigurationService openBankingConfigurationService; - - private EventNotificationDataHolder() { - this.realtimeEventNotificationQueue = new LinkedBlockingQueue<>(); - } - - /** - * Return a singleton instance of the data holder. - * - * @return A singleton instance of the data holder - */ - public static synchronized EventNotificationDataHolder getInstance() { - if (instance == null) { - synchronized (EventNotificationDataHolder.class) { - if (instance == null) { - instance = new EventNotificationDataHolder(); - } - } - } - return instance; - } - - public LinkedBlockingQueue getRealtimeEventNotificationQueue() { - return realtimeEventNotificationQueue; - } - - public OpenBankingConfigurationService getOpenBankingConfigurationService() { - - return openBankingConfigurationService; - } - - public void setOpenBankingConfigurationService( - OpenBankingConfigurationService openBankingConfigurationService) { - - this.openBankingConfigurationService = openBankingConfigurationService; - } - - public void setRealtimeEventNotificationQueue(LinkedBlockingQueue queue) { - this.realtimeEventNotificationQueue = queue; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/AggregatedPollingResponse.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/AggregatedPollingResponse.java deleted file mode 100644 index f94cce75..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/AggregatedPollingResponse.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.model; - -import java.util.HashMap; -import java.util.Map; - -/** - * Default Polling Response Implementation. - */ -public class AggregatedPollingResponse { - - private Map sets = new HashMap<>(); - - //For more available parameter - private int count = 0; - - private String status; - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public Map getSets() { - return sets; - } - - public void setSets(Map sets) { - this.sets = sets; - } - - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } - - public Boolean isMoreAvailable() { - return count > 0 ? true : false; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/EventSubscription.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/EventSubscription.java deleted file mode 100644 index 0909f53c..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/EventSubscription.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.model; - -import java.util.List; - -/** - * This is the Event Subscription Model. - */ -public class EventSubscription { - private String subscriptionId = null; - private String clientId = null; - private String callbackUrl = null; - private Long timeStamp = null; - private String specVersion = null; - private String status = null; - private List eventTypes = null; - private String requestData = null; - - public String getSubscriptionId() { - return subscriptionId; - } - - public void setSubscriptionId(String subscriptionId) { - this.subscriptionId = subscriptionId; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getCallbackUrl() { - return callbackUrl; - } - - public void setCallbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; - } - - public Long getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Long timeStamp) { - this.timeStamp = timeStamp; - } - - public String getSpecVersion() { - return specVersion; - } - - public void setSpecVersion(String specVersion) { - this.specVersion = specVersion; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public List getEventTypes() { - return eventTypes; - } - - public void setEventTypes(List eventTypes) { - this.eventTypes = eventTypes; - } - - public String getRequestData() { - return requestData; - } - - public void setRequestData(String requestData) { - this.requestData = requestData; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/Notification.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/Notification.java deleted file mode 100644 index 1a7aacf6..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/Notification.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.model; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.nimbusds.jose.JOSEException; -import net.minidev.json.JSONObject; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This is the notification model. - */ -public class Notification { - private String iss = null; - private Long iat = null; - private String jti = null; - private String sub = null; - private String aud = null; - private String txn = null; - private Long toe = null; - private Map events = new HashMap(); - - public Long getIat() { - return iat; - } - - public void setIat(Long iat) { - this.iat = iat; - } - - public String getJti() { - return jti; - } - - public void setJti(String jti) { - this.jti = jti; - } - - public String getSub() { - return sub; - } - - public void setSub(String sub) { - this.sub = sub; - } - - public String getAud() { - return aud; - } - - public void setAud(String aud) { - this.aud = aud; - } - - public String getTxn() { - return txn; - } - - public void setTxn(String txn) { - this.txn = txn; - } - - public Long getToe() { - return toe; - } - - public void setToe(Long toe) { - this.toe = toe; - } - - public Map getEvents() { - return events; - } - - public void setEvents(List eventsList) { - - for (NotificationEvent notificationEvent : eventsList) { - this.events.put(notificationEvent.getEventType(), notificationEvent.getEventInformation()); - } - } - - public String getIss() { - return iss; - } - - public void setIss(String iss) { - this.iss = iss; - } - - /** - * This method is to convert the class to a JSONObject. - * @param notification Notification - * @return JSONObject - * @throws IOException IOException when converting the class to JSONObject - * @throws JOSEException JOSEException when converting the class to JSONObject - * @throws IdentityOAuth2Exception IdentityOAuth2Exception when converting the class to JSONObject - */ - public static JsonNode getJsonNode(Notification notification) - throws IOException, JOSEException, IdentityOAuth2Exception { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.convertValue(notification, JsonNode.class); - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/NotificationError.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/NotificationError.java deleted file mode 100644 index 12938666..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/NotificationError.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.model; - -/** - * The notification error model. - */ -public class NotificationError { - private String notificationId = null; - private String errorCode = null; - private String errorDescription = null; - - public String getNotificationId() { - return notificationId; - } - - public void setNotificationId(String notificationId) { - this.notificationId = notificationId; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - public String getErrorDescription() { - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - this.errorDescription = errorDescription; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/NotificationEvent.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/NotificationEvent.java deleted file mode 100644 index beb444d0..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/model/NotificationEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.model; - -import net.minidev.json.JSONObject; - -/** - * This is the notification even model class. - */ -public class NotificationEvent { - - private Integer eventId = null; - private String notificationId = null; - private String eventType = null; - private JSONObject eventInformation; - - public Integer getEventId() { - return eventId; - } - - public void setEventId(Integer eventId) { - this.eventId = eventId; - } - - public String getNotificationId() { - return notificationId; - } - - public void setNotificationId(String notificationId) { - this.notificationId = notificationId; - } - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public JSONObject getEventInformation() { - return eventInformation; - } - - public void setEventInformation(JSONObject eventInformation) { - this.eventInformation = eventInformation; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventPollingStoreInitializer.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventPollingStoreInitializer.java deleted file mode 100644 index a682b49a..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventPollingStoreInitializer.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.persistence; - -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.MSSQLNotificationPollingSqlStatements; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.NotificationPollingSqlStatements; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.PostgreSqlPollingDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Initializer Class for EventPolling Service DB. - */ -@Generated(message = "Datastore initializer classes") -public class EventPollingStoreInitializer { - - private static Log log = LogFactory.getLog(EventPollingStoreInitializer.class); - private static final String MYSQL = "MySQL"; - private static final String POSTGRE = "PostgreSQL"; - private static final String MSSQL = "Microsoft"; - private static final String ORACLE = "Oracle"; - private static final String H2 = "h2"; - - public static AggregatedPollingDAO initializeAggregatedPollingDAO() throws OBEventNotificationException { - - AggregatedPollingDAO aggregatedPollingDAO; - try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection()) { - String driverName = connection.getMetaData().getDriverName(); - - if (driverName.contains(MYSQL) || driverName.contains(H2)) { - aggregatedPollingDAO = new AggregatedPollingDAOImpl(new NotificationPollingSqlStatements()); - } else if (driverName.contains(POSTGRE)) { - aggregatedPollingDAO = new PostgreSqlPollingDAOImpl(new NotificationPollingSqlStatements()); - } else if (driverName.contains(MSSQL)) { - aggregatedPollingDAO = new PostgreSqlPollingDAOImpl(new MSSQLNotificationPollingSqlStatements()); - } else if (driverName.contains(ORACLE)) { - aggregatedPollingDAO = new PostgreSqlPollingDAOImpl(new MSSQLNotificationPollingSqlStatements()); - } else { - throw new OBEventNotificationException("Unhandled DB driver: " + driverName + " detected"); - } - - } catch (SQLException e) { - throw new OBEventNotificationException("Error while getting the database connection : ", e); - } - return aggregatedPollingDAO; - } - - public static AggregatedPollingDAO getAggregatedPollingDAO() throws OBEventNotificationException { - - return initializeAggregatedPollingDAO(); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventPublisherStoreInitializer.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventPublisherStoreInitializer.java deleted file mode 100644 index 0a2d9938..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventPublisherStoreInitializer.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.persistence; - -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventPublisherDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventPublisherDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.NotificationPublisherSqlStatements; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Initialize DB for Event Creation. - */ -@Generated(message = "Datastore initializer classes") -public class EventPublisherStoreInitializer { - - private static Log log = LogFactory.getLog(EventPublisherStoreInitializer.class); - private static final String MYSQL = "MySQL"; - private static final String POSTGRE = "PostgreSQL"; - private static final String MSSQL = "Microsoft"; - private static final String ORACLE = "Oracle"; - private static final String H2 = "h2"; - - public static EventPublisherDAO initializePublisherDAO() throws OBEventNotificationException { - - EventPublisherDAO eventPublisherDAO; - try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection()) { - String driverName = connection.getMetaData().getDriverName(); - - if (driverName.contains(MYSQL) || driverName.contains(H2)) { - eventPublisherDAO = new EventPublisherDAOImpl(new NotificationPublisherSqlStatements()); - } else if (driverName.contains(POSTGRE)) { - eventPublisherDAO = new EventPublisherDAOImpl(new NotificationPublisherSqlStatements()); - } else if (driverName.contains(MSSQL)) { - eventPublisherDAO = new EventPublisherDAOImpl(new NotificationPublisherSqlStatements()); - } else if (driverName.contains(ORACLE)) { - eventPublisherDAO = new EventPublisherDAOImpl(new NotificationPublisherSqlStatements()); - } else { - throw new OBEventNotificationException("Unhandled DB driver: " + driverName + " detected"); - } - } catch (SQLException e) { - throw new OBEventNotificationException("Error while getting the database connection : ", e); - } - - return eventPublisherDAO; - } - - public static EventPublisherDAO getEventCreationDao() throws OBEventNotificationException { - - return initializePublisherDAO(); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventSubscriptionStoreInitializer.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventSubscriptionStoreInitializer.java deleted file mode 100644 index a3d040bf..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/persistence/EventSubscriptionStoreInitializer.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.persistence; - -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventSubscriptionDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventSubscriptionDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventSubscriptionSqlStatements; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.PostgreSqlEventSubscriptionDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Initializer Class for EventSubscription Service DB. - */ -@Generated(message = "Datastore initializer classes") -public class EventSubscriptionStoreInitializer { - - private static Log log = LogFactory.getLog(EventSubscriptionStoreInitializer.class); - private static final String MYSQL = "MySQL"; - private static final String POSTGRE = "PostgreSQL"; - private static final String MSSQL = "Microsoft"; - private static final String ORACLE = "Oracle"; - private static final String H2 = "h2"; - - public static EventSubscriptionDAO initializeSubscriptionDAO() throws OBEventNotificationException { - - EventSubscriptionDAO eventSubscriptionDao; - try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection()) { - String driverName = connection.getMetaData().getDriverName(); - - if (driverName.contains(MYSQL) || driverName.contains(H2)) { - eventSubscriptionDao = new EventSubscriptionDAOImpl(new EventSubscriptionSqlStatements()); - } else if (driverName.contains(POSTGRE)) { - eventSubscriptionDao = new PostgreSqlEventSubscriptionDAOImpl(new EventSubscriptionSqlStatements()); - } else if (driverName.contains(MSSQL)) { - eventSubscriptionDao = new EventSubscriptionDAOImpl(new EventSubscriptionSqlStatements()); - } else if (driverName.contains(ORACLE)) { - eventSubscriptionDao = new EventSubscriptionDAOImpl(new EventSubscriptionSqlStatements()); - } else { - throw new OBEventNotificationException("Unhandled DB driver: " + driverName + " detected"); - } - } catch (SQLException e) { - throw new OBEventNotificationException("Error while getting the database connection : ", e); - } - - return eventSubscriptionDao; - } - - public static EventSubscriptionDAO getEventSubscriptionDao() throws OBEventNotificationException { - - return initializeSubscriptionDAO(); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/model/RealtimeEventNotification.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/model/RealtimeEventNotification.java deleted file mode 100644 index 4ae5dae1..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/model/RealtimeEventNotification.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.model; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.service.RealtimeEventNotificationRequestGenerator; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; - -/** - * Model class for real time event notifications. - */ -public class RealtimeEventNotification { - private String callbackUrl = null; - private String eventSET = null; // Security Event Token to hold the Event Notification Data - private NotificationDTO notificationDTO = null; - - public void setCallbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; - } - - public void setEventSET(String notification) { - this.eventSET = notification; - } - - public void setNotificationDTO(NotificationDTO notificationDTO) { - this.notificationDTO = notificationDTO; - } - - public String getCallbackUrl() { - return callbackUrl; - } - - public String getJsonPayload() { - RealtimeEventNotificationRequestGenerator eventNotificationRequestGenerator = - EventNotificationServiceUtil.getRealtimeEventNotificationRequestGenerator(); - return eventNotificationRequestGenerator.getRealtimeEventNotificationPayload(notificationDTO, eventSET); - } - - public String getNotificationId() { - return notificationDTO.getNotificationId(); - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/DefaultRealtimeEventNotificationRequestGenerator.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/DefaultRealtimeEventNotificationRequestGenerator.java deleted file mode 100644 index 7f9e90f1..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/DefaultRealtimeEventNotificationRequestGenerator.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; - -import java.util.HashMap; -import java.util.Map; - -/** - * Default class for realtime event notification request generation. - * This is to generate the realtime event notification request payload and headers. - */ -public class DefaultRealtimeEventNotificationRequestGenerator implements RealtimeEventNotificationRequestGenerator { - @Override - public String getRealtimeEventNotificationPayload(NotificationDTO notificationDTO, String eventSET) { - return "{\"notificationId\": " + notificationDTO.getNotificationId() + ", \"SET\": " + eventSET + "}"; - } - - @Override - public Map getAdditionalHeaders() { - return new HashMap<>(); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/EventNotificationProducerService.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/EventNotificationProducerService.java deleted file mode 100644 index 72da33fb..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/EventNotificationProducerService.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.nimbusds.jose.JOSEException; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationDataHolder; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.model.RealtimeEventNotification; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventNotificationGenerator; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventPollingService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * This thread is used to produce the event notification and put it into the realtime event notification queue. - */ -public class EventNotificationProducerService implements Runnable { - private static final Log log = LogFactory.getLog(EventPollingService.class); - private final NotificationDTO notificationDTO; - private final List notificationEvents; - - public EventNotificationProducerService( - NotificationDTO notificationDTO, List notificationEvents) { - this.notificationDTO = notificationDTO; - this.notificationEvents = notificationEvents; - } - - @Override - public void run() { - String callbackUrl = EventNotificationServiceUtil.getCallbackURL(notificationDTO.getClientId()); - - LinkedBlockingQueue queue = EventNotificationDataHolder.getInstance(). - getRealtimeEventNotificationQueue(); - EventNotificationGenerator eventNotificationGenerator = EventNotificationServiceUtil. - getEventNotificationGenerator(); - RealtimeEventNotification realtimeEventNotification = new RealtimeEventNotification(); - realtimeEventNotification.setNotificationDTO(notificationDTO); - realtimeEventNotification.setCallbackUrl(callbackUrl); - - try { - Notification notification = eventNotificationGenerator.generateEventNotificationBody( - notificationDTO, notificationEvents); - realtimeEventNotification.setEventSET(eventNotificationGenerator.generateEventNotification( - Notification.getJsonNode(notification))); - - queue.put(realtimeEventNotification); // put the notification into the queue - } catch (InterruptedException e) { - log.error("Error when adding the Realtime Notification with notification ID " + - notificationDTO.getNotificationId() + " into the RealtimeEventNotification Queue", e); - } catch (OBEventNotificationException e) { - log.error("Error when generating the event notification", e); - } catch (IOException | JOSEException | IdentityOAuth2Exception e) { - log.error("Error while processing event notification JSON object", e); - } - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationLoaderService.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationLoaderService.java deleted file mode 100644 index f31ff3bf..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationLoaderService.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.nimbusds.jose.JOSEException; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationDataHolder; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPollingStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.model.RealtimeEventNotification; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventNotificationGenerator; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventPollingService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * This service is used to add open state event notifications to the realtime event notification queue. - * This service is called whenever the server starts. - */ -public class RealtimeEventNotificationLoaderService implements Runnable { - private static final Log log = LogFactory.getLog(EventPollingService.class); - - @Override - public void run() { - // Get all open state event notifications from the database and add them to the queue - try { - LinkedBlockingQueue queue = EventNotificationDataHolder.getInstance(). - getRealtimeEventNotificationQueue(); - AggregatedPollingDAO aggregatedPollingDAO = EventPollingStoreInitializer.getAggregatedPollingDAO(); - EventNotificationGenerator eventNotificationGenerator = EventNotificationServiceUtil. - getEventNotificationGenerator(); - List openNotifications = aggregatedPollingDAO.getNotificationsByStatus( - EventNotificationConstants.OPEN); - - for (NotificationDTO notificationDTO : openNotifications) { - //Get events by notificationId - List notificationEvents = aggregatedPollingDAO. - getEventsByNotificationID(notificationDTO.getNotificationId()); - - Notification responseNotification = eventNotificationGenerator. - generateEventNotificationBody(notificationDTO, notificationEvents); - - String callbackUrl = EventNotificationServiceUtil.getCallbackURL(notificationDTO.getClientId()); - - RealtimeEventNotification realtimeEventNotification = new RealtimeEventNotification(); - realtimeEventNotification.setCallbackUrl(callbackUrl); - realtimeEventNotification.setEventSET(eventNotificationGenerator.generateEventNotification( - Notification.getJsonNode(responseNotification))); - realtimeEventNotification.setNotificationDTO(notificationDTO); - queue.put(realtimeEventNotification); // put the notification into the queue - } - } catch (InterruptedException e) { - log.error("Error when adding the Realtime Notification into the RealtimeEventNotification Queue", e); - } catch (OBEventNotificationException e) { - log.error("Error when generating the event notification", e); - } catch (IOException | JOSEException | IdentityOAuth2Exception e) { - log.error("Error while processing event notification JSON object", e); - } - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationRequestGenerator.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationRequestGenerator.java deleted file mode 100644 index f9e6bf89..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationRequestGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - - -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; - -import java.util.Map; - -/** - * Interface for event notification request metadata generation. For custom class extensions the class name - * is to be referred from the realtime_event_notification_request_generator in deployment.toml - */ -public interface RealtimeEventNotificationRequestGenerator { - /** - * This method is to generate realtime event notification payload. To generate custom values - * for the body this method should be extended. - * - * @param notificationDTO Notification details DTO - * @param eventSET Event set - * @return String payload - */ - String getRealtimeEventNotificationPayload(NotificationDTO notificationDTO, String eventSET); - - /** - * This method is to generate realtime event notification request headers. To generate custom values - * for the body this method should be extended. - * - * @return Map of headers - */ - Map getAdditionalHeaders(); -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationSenderService.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationSenderService.java deleted file mode 100644 index 8b2ae6c9..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationSenderService.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationComponent; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPollingStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; -import java.net.URI; -import java.time.Duration; -import java.time.LocalTime; -import java.util.Map; - -/** - * This method is used to send the HTTP requests to the TPP provided callback URL. - * Exponential backoff and Circuit breaker based retry policy is used to retry failed POST requests. - */ -public class RealtimeEventNotificationSenderService implements Runnable { - - private static final Log log = LogFactory.getLog(EventNotificationComponent.class); - - private static final OpenBankingConfigParser configParser = OpenBankingConfigParser.getInstance(); - private static final int MAX_RETRIES = configParser.getRealtimeEventNotificationMaxRetries(); - private static final int INITIAL_BACKOFF_TIME_IN_SECONDS = - configParser.getRealtimeEventNotificationInitialBackoffTimeInSeconds(); - private static final String BACKOFF_FUNCTION = configParser.getRealtimeEventNotificationBackoffFunction(); - private static final int CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS = - configParser.getRealtimeEventNotificationCircuitBreakerOpenTimeoutInSeconds(); - private static final int TIMEOUT_IN_SECONDS = configParser.getRealtimeEventNotificationTimeoutInSeconds(); - - private CloseableHttpClient httpClient; - private RealtimeEventNotificationRequestGenerator httpRequestGenerator; - private String notificationId; - private String callbackUrl; - private String payloadJson; - - public RealtimeEventNotificationSenderService(String callbackUrl, String payloadJson, - String notificationId) { - try { - this.httpClient = HTTPClientUtils.getRealtimeEventNotificationHttpsClient(); - } catch (OpenBankingException e) { - log.error("Failed to initialize the HTTP client for the realtime event notification", e); - } - this.httpRequestGenerator = EventNotificationServiceUtil.getRealtimeEventNotificationRequestGenerator(); - this.notificationId = notificationId; - this.callbackUrl = callbackUrl; - this.payloadJson = payloadJson; - } - - public void run() { - try { - postWithRetry(); - } catch (OBEventNotificationException e) { - log.error("Failed to send the Real-time event notification with notificationId: " - + notificationId, e); - } - } - - /** - * This method is used to send the HTTP requests to the TPP provided callback URL. - * Exponential backoff and Circuit breaker based retry policy is used to retry failed POST requests. - * - * @throws OBEventNotificationException - */ - private void postWithRetry() throws OBEventNotificationException { - AggregatedPollingDAO aggregatedPollingDAO = - EventPollingStoreInitializer.getAggregatedPollingDAO(); - int retryCount = 0; - long backoffTimeMs = INITIAL_BACKOFF_TIME_IN_SECONDS * 1000L; - boolean circuitBreakerOpen = false; - LocalTime startTime = LocalTime.now(); - - while (retryCount <= MAX_RETRIES && !circuitBreakerOpen) { - try { - // This if closure will execute only if the initial POST request is failed. - // This includes the retry policy and will execute according to the configurations. - if (retryCount > 0) { - if (log.isDebugEnabled()) { - log.debug("HTTP request Retry #" + retryCount + " - waiting for " - + backoffTimeMs + " ms before trying again"); - } - Thread.sleep(backoffTimeMs); - - switch (BACKOFF_FUNCTION) { - case "CONSTANT": - // Backoff time will not be changed - // Retries will happen in constant time frames - break; - case "LINEAR": - // Backoff time will be doubled after each retry - // nextWaitingTime = 2 x previousWaitingTime - backoffTimeMs *= 2; - break; - case "EX": - // Backoff time will be increased exponentially - // nextWaitingTime = startWaitingTime x e^(retryCount) - backoffTimeMs = (long) - (INITIAL_BACKOFF_TIME_IN_SECONDS - * 1000 * Math.exp(retryCount)); - break; - default: - log.error("Invalid backoff function for the realtime event notification retry policy: " - + BACKOFF_FUNCTION); - throw new IllegalArgumentException( - "Invalid backoff function for the realtime event notification retry policy: " - + BACKOFF_FUNCTION); - } - } - - HttpPost httpPost = new HttpPost(URI.create(callbackUrl)); - - for (Map.Entry entry : httpRequestGenerator.getAdditionalHeaders().entrySet()) { - String headerName = entry.getKey(); - String headerValue = entry.getValue(); - httpPost.setHeader(headerName, headerValue); - } - - httpPost.setEntity(new StringEntity(payloadJson, ContentType.APPLICATION_JSON)); - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(TIMEOUT_IN_SECONDS * 1000) - .setConnectionRequestTimeout(TIMEOUT_IN_SECONDS * 1000) - .setSocketTimeout(TIMEOUT_IN_SECONDS * 1000) - .build(); - httpPost.setConfig(requestConfig); - - HttpResponse response = httpClient.execute(httpPost); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - if (log.isDebugEnabled()) { - log.debug("Real-time event notification with notificationId: " + notificationId - + " sent successfully"); - } - aggregatedPollingDAO.updateNotificationStatusById(notificationId, EventNotificationConstants.ACK); - return; - } else { - if (log.isDebugEnabled()) { - log.debug("Real-time event notification with notificationId: " + notificationId - + " sent failed with status code: " + statusCode); - } - } - } catch (IOException | InterruptedException e) { - log.error("Real-time event notification with notificationId: " + notificationId - + " sent failed" + e); - } - - // Circuit breaker will be opened if the retrying time exceeds the configured circuit breaker timeout. - if (Duration.between(startTime, LocalTime.now()).toMillis() - > CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS * 1000) { - circuitBreakerOpen = true; - if (log.isDebugEnabled()) { - log.debug("Circuit breaker open for the realtime event notification with notificationId: " - + notificationId); - } - } - retryCount++; - } - - // If the circuit breaker is opened or the maximum retry count is exceeded, - // the notification status will be updated as ERROR. - aggregatedPollingDAO.updateNotificationStatusById(notificationId, EventNotificationConstants.ERROR); - - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/activator/PeriodicalEventNotificationConsumerJobActivator.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/activator/PeriodicalEventNotificationConsumerJobActivator.java deleted file mode 100644 index 4fcc8bed..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/activator/PeriodicalEventNotificationConsumerJobActivator.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.util.activator; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.util.job.EventNotificationConsumerJob; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime. - util.scheduler.PeriodicalEventNotificationConsumerJobScheduler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.CronExpression; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SimpleScheduleBuilder; -import org.quartz.Trigger; - -import java.text.ParseException; -import java.util.Date; - -import static org.quartz.JobBuilder.newJob; -import static org.quartz.TriggerBuilder.newTrigger; - -/** - * Scheduled Task definition and trigger to perform realtime event notification sending based on the cron string. - */ -@Generated(message = "Excluding from code coverage") -public class PeriodicalEventNotificationConsumerJobActivator { - - private static Log log = LogFactory.getLog(PeriodicalEventNotificationConsumerJobActivator.class); - private static final String PERIODIC_CRON_EXPRESSION = OpenBankingConfigParser - .getInstance().getRealtimeEventNotificationSchedulerCronExpression(); - - public void activate() { - int cronInSeconds = 60; - - try { - CronExpression cron = new CronExpression(PERIODIC_CRON_EXPRESSION); - - Date nextValidTime = cron.getNextValidTimeAfter(new Date()); - Date secondValidTime = cron.getNextValidTimeAfter(nextValidTime); - - cronInSeconds = (int) (secondValidTime.getTime() - nextValidTime.getTime()) / 1000; - - } catch (ParseException e) { - log.error("Error while parsing the event notification scheduler cron expression : " - + PERIODIC_CRON_EXPRESSION, e); - } - - JobDetail job = newJob(EventNotificationConsumerJob.class) - .withIdentity("RealtimeEventNotificationJob", "group2") - .build(); - - Trigger trigger = newTrigger() - .withIdentity("periodicalEvenNotificationTrigger", "group2") - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(cronInSeconds) - .repeatForever()) - .build(); - - try { - Scheduler scheduler = PeriodicalEventNotificationConsumerJobScheduler.getInstance().getScheduler(); - // this check is to remove already stored jobs in clustered mode. - if (scheduler.checkExists(job.getKey())) { - scheduler.deleteJob(job.getKey()); - } - - scheduler.scheduleJob(job, trigger); - log.info("Periodical Realtime Event Notification sender Started with cron : " - + PERIODIC_CRON_EXPRESSION); - } catch (SchedulerException e) { - log.error("Error while starting Periodical Realtime Event Notification sender", e); - } - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/job/EventNotificationConsumerJob.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/job/EventNotificationConsumerJob.java deleted file mode 100644 index d5591990..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/job/EventNotificationConsumerJob.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.util.job; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationDataHolder; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.model.RealtimeEventNotification; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.service.RealtimeEventNotificationSenderService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.DisallowConcurrentExecution; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -import java.util.ArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * Scheduled Task to send realtime event notifications to callback Urls. - * This task is scheduled to run periodically. - * This task consumes all the notifications in the queue and send them to the callback urls. - */ -@Generated(message = "Excluding from code coverage") -@DisallowConcurrentExecution -public class EventNotificationConsumerJob implements Job { - - private static final Log log = LogFactory.getLog(EventNotificationConsumerJob.class); - private static final int THREAD_POOL_SIZE = OpenBankingConfigParser - .getInstance().getEventNotificationThreadpoolSize(); - - @Override - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - ArrayList notifications = consumeNotifications(); - // send notifications to the callback urls - int threads = Math.min(notifications.size(), THREAD_POOL_SIZE); - int threadPoolSize = Math.max(threads, 2); - - ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize); - - for (RealtimeEventNotification notification : notifications) { - String callbackUrl = notification.getCallbackUrl(); - String payload = notification.getJsonPayload(); - Runnable worker = new RealtimeEventNotificationSenderService(callbackUrl, - payload, notification.getNotificationId()); - executor.execute(worker); - } - - executor.shutdown(); - while (!executor.isTerminated()) { } - } - - private static ArrayList consumeNotifications() { - - LinkedBlockingQueue queue = EventNotificationDataHolder.getInstance() - .getRealtimeEventNotificationQueue(); - ArrayList notifications = new ArrayList<>(); - - // consume all notifications in the queue - int key = 0; - while (!queue.isEmpty() && key < THREAD_POOL_SIZE) { - key++; - try { - RealtimeEventNotification notification = queue.take(); - notifications.add(notification); - } catch (InterruptedException ex) { - log.error("Error while consuming notifications from the event notification queue", ex); - } - } - return notifications; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/scheduler/PeriodicalEventNotificationConsumerJobScheduler.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/scheduler/PeriodicalEventNotificationConsumerJobScheduler.java deleted file mode 100644 index 2b58cd55..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/util/scheduler/PeriodicalEventNotificationConsumerJobScheduler.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.util.scheduler; - -import com.wso2.openbanking.accelerator.common.util.Generated; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.impl.StdSchedulerFactory; - -/** - * Periodic realtime event notification job scheduler class. - * This class initialize the scheduler and schedule configured jobs and triggers. - */ -@Generated(message = "Excluding from code coverage") -public class PeriodicalEventNotificationConsumerJobScheduler { - private static volatile PeriodicalEventNotificationConsumerJobScheduler instance; - private static volatile Scheduler scheduler; - private static Log log = LogFactory.getLog(PeriodicalEventNotificationConsumerJobScheduler.class); - - private PeriodicalEventNotificationConsumerJobScheduler() { - initScheduler(); - } - - public static synchronized PeriodicalEventNotificationConsumerJobScheduler getInstance() { - - if (instance == null) { - synchronized (PeriodicalEventNotificationConsumerJobScheduler.class) { - if (instance == null) { - instance = new PeriodicalEventNotificationConsumerJobScheduler(); - } - } - } - return instance; - } - - private void initScheduler() { - - if (instance != null) { - return; - } - synchronized (PeriodicalEventNotificationConsumerJobScheduler.class) { - try { - scheduler = StdSchedulerFactory.getDefaultScheduler(); - scheduler.start(); - } catch (SchedulerException e) { - log.error("Exception while initializing the Real-time Event notification scheduler", e); - } - } - } - - /** - * Returns the scheduler. - * - * @return Scheduler scheduler. - */ - public Scheduler getScheduler() { - return scheduler; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventCreationResponse.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventCreationResponse.java deleted file mode 100644 index 658cad48..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventCreationResponse.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.response; - -import net.minidev.json.JSONObject; - -/** - * This class is to pass the event creation response to the api endpoint. - */ -public class EventCreationResponse { - - private String status; - private JSONObject responseBody; - private String errorResponse; - - public String getErrorResponse() { - return errorResponse; - } - - public void setErrorResponse(String errorResponse) { - this.errorResponse = errorResponse; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public JSONObject getResponseBody() { - return responseBody; - } - - public void setResponseBody(JSONObject responseBody) { - this.responseBody = responseBody; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventPollingResponse.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventPollingResponse.java deleted file mode 100644 index af8b7ee0..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventPollingResponse.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.response; - -import net.minidev.json.JSONObject; - -/** - * This class is used to map the Event Polling service response to the API response. - */ -public class EventPollingResponse { - - private String status; - private JSONObject responseBody; - private Object errorResponse; - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public JSONObject getResponseBody() { - return responseBody; - } - - public void setResponseBody(JSONObject responseBody) { - this.responseBody = responseBody; - } - - public Object getErrorResponse() { - return errorResponse; - } - - public void setErrorResponse(Object errorResponse) { - this.errorResponse = errorResponse; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventSubscriptionResponse.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventSubscriptionResponse.java deleted file mode 100644 index 327ff5f0..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/response/EventSubscriptionResponse.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.response; - -/** - * This class is used to map the Event Subscription service response to the API response. - */ -public class EventSubscriptionResponse { - - private int status; - private Object responseBody; - private Object errorResponse; - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public Object getResponseBody() { - return responseBody; - } - - public void setResponseBody(Object responseBody) { - this.responseBody = responseBody; - } - - public Object getErrorResponse() { - return errorResponse; - } - - public void setErrorResponse(Object errorResponse) { - this.errorResponse = errorResponse; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/DefaultEventNotificationGenerator.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/DefaultEventNotificationGenerator.java deleted file mode 100644 index 5303ae05..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/DefaultEventNotificationGenerator.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.fasterxml.jackson.databind.JsonNode; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.registry.core.utils.UUIDGenerator; - -import java.time.Instant; -import java.util.List; - -/** - * Default Event Notification Response Generator Class. - */ -public class DefaultEventNotificationGenerator implements EventNotificationGenerator { - - private static Log log = LogFactory.getLog(DefaultEventNotificationGenerator.class); - - @Override - public Notification generateEventNotificationBody(NotificationDTO notificationDTO, - List notificationEventList) - throws OBEventNotificationException { - - Notification notification = new Notification(); - //get current time in milliseconds - Long currentTime = Instant.now().getEpochSecond(); - - //generate transaction Identifier - String transactionIdentifier = UUIDGenerator.generateUUID(); - - notification.setIss(OpenBankingConfigParser.getInstance().getEventNotificationTokenIssuer()); - notification.setIat(currentTime); - notification.setAud(notificationDTO.getClientId()); - notification.setJti(notificationDTO.getNotificationId()); - notification.setTxn(transactionIdentifier); - notification.setToe(notificationDTO.getUpdatedTimeStamp()); - notification.setSub(generateSubClaim(notificationDTO)); - notification.setEvents(notificationEventList); - return notification; - } - - @Generated(message = "Excluded from tests as using a util method from a different package") - public String generateEventNotification(JsonNode jsonNode) - throws OBEventNotificationException { - - String payload = EventNotificationServiceUtil.getCustomNotificationPayload(jsonNode); - try { - return IdentityCommonUtil.signJWTWithDefaultKey(payload); - } catch (Exception e) { - log.error("Error while signing the JWT token", e); - throw new OBEventNotificationException("Error while signing the JWT token", e); - } - - } - - @Generated(message = "Private method tested when the used method is tested") - private String generateSubClaim(NotificationDTO notificationDTO) { - String sub = notificationDTO.getClientId(); - return sub; - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventCreationService.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventCreationService.java deleted file mode 100644 index 3ccc63ec..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventCreationService.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventPublisherDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationCreationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPublisherStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.service.EventNotificationProducerService; -import net.minidev.json.JSONObject; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.registry.core.utils.UUIDGenerator; - - -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Map; - -/** - * This is the event creation service class. - */ -public class EventCreationService { - - private static Log log = LogFactory.getLog(EventCreationService.class); - - /** - * The publishOBEventNotification methods will call the dao layer to persist the event - * notifications for event polling request. - * @param notificationCreationDTO Notification Creation DTO - * @return Event Response - * @throws OBEventNotificationException Exception when persisting event notification data - */ - public String publishOBEventNotification(NotificationCreationDTO notificationCreationDTO) - throws OBEventNotificationException { - - Connection connection = DatabaseUtil.getDBConnection(); - NotificationDTO notification = getNotification(notificationCreationDTO); - ArrayList eventsList = getEvents(notificationCreationDTO.getEventPayload()); - - EventPublisherDAO eventPublisherDAO = EventPublisherStoreInitializer.getEventCreationDao(); - String eventResponse = null; - - try { - eventResponse = eventPublisherDAO.persistEventNotification(connection, notification, eventsList); - DatabaseUtil.commitTransaction(connection); - - // Check whether the real time event notification is enabled. - if (OpenBankingConfigParser.getInstance().isRealtimeEventNotificationEnabled()) { - new Thread(new EventNotificationProducerService(notification, eventsList)).start(); - } - return eventResponse; - } catch (OBEventNotificationException e) { - throw new OBEventNotificationException("Error when persisting event notification data", e); - } finally { - log.debug(EventNotificationConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - /** - * The getEvents method is used to get the NotificationEvents Array list from payload. - * - * @param notificationEvents Notification Events to convert - * @return Event notification List - */ - @Generated(message = "Private methods invoked when calling referred method") - private ArrayList getEvents(Map notificationEvents) { - - ArrayList eventsList = new ArrayList<>(); - notificationEvents.keySet().forEach(key -> { - Object eventInfo = notificationEvents.get(key); - NotificationEvent notificationEvent = new NotificationEvent(); - notificationEvent.setEventType(key); - notificationEvent.setEventInformation((JSONObject) eventInfo); - eventsList.add(notificationEvent); - }); - - return eventsList; - } - - /** - * The getNotification method is used to get the NotificationDAO from payload. - * - * @param notificationCreationDTO Notification Creation DTO - * @return Notification Details - */ - @Generated(message = "Private methods invoked when calling referred method") - private NotificationDTO getNotification(NotificationCreationDTO notificationCreationDTO) { - - NotificationDTO notification = new NotificationDTO(); - notification.setNotificationId(UUIDGenerator.generateUUID()); - notification.setClientId(notificationCreationDTO.getClientId()); - notification.setResourceId(notificationCreationDTO.getResourceId()); - notification.setStatus(EventNotificationConstants.OPEN); - - return notification; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventNotificationGenerator.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventNotificationGenerator.java deleted file mode 100644 index 8b0e50ea..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventNotificationGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.fasterxml.jackson.databind.JsonNode; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; - -import java.util.List; - -/** - * Interface for event notification generation. For custom class extensions the class name - * is to be referred from the event_notification_generator in deployment.toml - */ -public interface EventNotificationGenerator { - - /** - * This method is to generate event notification body. To generate custom values - * for the body this method should be extended. - * @param notificationDTO Notification details DTO - * @param notificationEventList List of notification events - * - * @return Event Notification Body - * @throws OBEventNotificationException Exception when generating event notification body - */ - Notification generateEventNotificationBody(NotificationDTO notificationDTO, List - notificationEventList) throws OBEventNotificationException; - - String generateEventNotification(JsonNode jsonNode) throws OBEventNotificationException; -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventPollingService.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventPollingService.java deleted file mode 100644 index 8490a9f8..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventPollingService.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.nimbusds.jose.JOSEException; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventPollingDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.AggregatedPollingResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPollingStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This is the event polling service. - */ -public class EventPollingService { - - private static Log log = LogFactory.getLog(EventPollingService.class); - - /** - * The pollEvents methods will return the Aggregated Polling Response for - * event polling request. - * @param eventPollingDTO Event polling request DTO - * @return AggregatedPollingResponse Aggregated Polling Response - * @throws OBEventNotificationException Exception when polling events - */ - public AggregatedPollingResponse pollEvents(EventPollingDTO eventPollingDTO) - throws OBEventNotificationException { - - AggregatedPollingResponse aggregatedPollingResponse = new AggregatedPollingResponse(); - AggregatedPollingDAO aggregatedPollingDAO = EventPollingStoreInitializer.getAggregatedPollingDAO(); - - EventNotificationGenerator eventNotificationGenerator = EventNotificationServiceUtil. - getEventNotificationGenerator(); - - Map sets = new HashMap<>(); - - //Short polling - if (eventPollingDTO.getReturnImmediately()) { - - //Update notifications with ack - for (String notificationId : eventPollingDTO.getAck()) { - aggregatedPollingDAO.updateNotificationStatusById(notificationId, EventNotificationConstants.ACK); - } - - //Update notifications with err - for (Map.Entry entry: eventPollingDTO.getErrors().entrySet()) { - //Check if the notification is in OPEN status - if (aggregatedPollingDAO.getNotificationStatus(entry.getKey())) { - aggregatedPollingDAO.updateNotificationStatusById( - entry.getKey(), EventNotificationConstants.ERROR); - aggregatedPollingDAO.storeErrorNotification(entry.getValue()); - } - } - - //Retrieve notifications - int maxEvents = eventPollingDTO.getMaxEvents(); - - if (maxEvents == 0) { - aggregatedPollingResponse.setSets(sets); - aggregatedPollingResponse.setStatus(EventNotificationConstants.OK); - } else { - - int setsToReturn = OpenBankingConfigParser.getInstance().getNumberOfSetsToReturn(); - - List notificationList; - - if (maxEvents < setsToReturn) { - notificationList = aggregatedPollingDAO.getNotificationsByClientIdAndStatus( - eventPollingDTO.getClientId(), EventNotificationConstants.OPEN, maxEvents); - - } else { - notificationList = aggregatedPollingDAO.getNotificationsByClientIdAndStatus( - eventPollingDTO.getClientId(), EventNotificationConstants.OPEN, setsToReturn); - } - - if (notificationList.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug(String.format("No OB Event Notifications available for for the client " + - "with ID : '%s'.", eventPollingDTO.getClientId().replaceAll("[\r\n]", ""))); - } - aggregatedPollingResponse.setStatus(EventNotificationConstants.NOT_FOUND); - } else { - if (log.isDebugEnabled()) { - log.debug(String.format("OB Event Notifications available for the client " + - "with ID : '%s'.", eventPollingDTO.getClientId().replaceAll("[\r\n]", ""))); - } - aggregatedPollingResponse.setStatus(EventNotificationConstants.OK); - - for (NotificationDTO notificationDTO : notificationList) { - - try { - //Get events by notificationId - List notificationEvents = aggregatedPollingDAO. - getEventsByNotificationID(notificationDTO.getNotificationId()); - - Notification responseNotification = eventNotificationGenerator. - generateEventNotificationBody(notificationDTO, notificationEvents); - sets.put(notificationDTO.getNotificationId(), - eventNotificationGenerator.generateEventNotification(Notification.getJsonNode( - responseNotification))); - log.info("Retrieved OB event notifications"); - } catch (OBEventNotificationException | - IOException | JOSEException | IdentityOAuth2Exception e) { - log.debug("Error when retrieving OB event notifications.", e); - throw new OBEventNotificationException("Error when retrieving OB event notifications.", e); - } - } - aggregatedPollingResponse.setSets(sets); - } - } - - int count = aggregatedPollingDAO.getNotificationCountByClientIdAndStatus(eventPollingDTO.getClientId(), - EventNotificationConstants.OPEN) - aggregatedPollingResponse.getSets().size(); - - aggregatedPollingResponse.setCount(count); - - return aggregatedPollingResponse; - } - - return null; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventSubscriptionService.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventSubscriptionService.java deleted file mode 100644 index 1d561c01..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventSubscriptionService.java +++ /dev/null @@ -1,241 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventSubscriptionDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventSubscriptionStoreInitializer; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.util.List; - -/** - * This is the event subscription service class. - */ -public class EventSubscriptionService { - private static Log log = LogFactory.getLog(EventSubscriptionService.class); - - /** - * This method will call the dao layer to persist the event subscription. - * - * @param eventSubscription event subscription object that needs to be persisted - * @return event subscription object that is persisted - * @throws OBEventNotificationException if an error occurred while persisting the event subscription - */ - public EventSubscription createEventSubscription(EventSubscription eventSubscription) - throws OBEventNotificationException { - - EventSubscriptionDAO eventSubscriptionDao = EventSubscriptionStoreInitializer.getEventSubscriptionDao(); - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - //store event subscription data in the database - EventSubscription storeEventSubscriptionResult = eventSubscriptionDao. - storeEventSubscription(connection, eventSubscription); - //store subscribed event types in the database - if (eventSubscription.getEventTypes() != null && !eventSubscription.getEventTypes().isEmpty()) { - List storedEventTypes = eventSubscriptionDao.storeSubscribedEventTypes(connection, - storeEventSubscriptionResult.getSubscriptionId(), eventSubscription.getEventTypes()); - storeEventSubscriptionResult.setEventTypes(storedEventTypes); - } - log.debug("Event subscription created successfully."); - DatabaseUtil.commitTransaction(connection); - return storeEventSubscriptionResult; - } catch (OBEventNotificationException e) { - log.error("Error while creating event subscription.", e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBEventNotificationException(EventNotificationConstants.ERROR_STORING_EVENT_SUBSCRIPTION, e); - } finally { - DatabaseUtil.closeConnection(connection); - } - } - - /** - * This method will call the dao layer to retrieve a single event subscription. - * - * @param subscriptionId subscription id of the event subscription - * @return event subscription object that is retrieved - * @throws OBEventNotificationException if an error occurred while retrieving the event subscription - */ - public EventSubscription getEventSubscriptionBySubscriptionId(String subscriptionId) - throws OBEventNotificationException { - - EventSubscriptionDAO eventSubscriptionDao = EventSubscriptionStoreInitializer.getEventSubscriptionDao(); - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - return eventSubscriptionDao.getEventSubscriptionBySubscriptionId(connection, subscriptionId); - } catch (OBEventNotificationException e) { - log.error("Error while retrieving event subscription.", e); - throw new OBEventNotificationException(e.getMessage(), e); - } finally { - DatabaseUtil.closeConnection(connection); - } - } - - /** - * This method will call the dao layer to retrieve all event subscriptions of a client. - * - * @param clientId client id of the event subscription - * @return list of event subscriptions that are retrieved - * @throws OBEventNotificationException if an error occurred while retrieving the event subscriptions - */ - public List getEventSubscriptionsByClientId(String clientId) - throws OBEventNotificationException { - - Connection connection = DatabaseUtil.getDBConnection(); - try { - EventSubscriptionDAO eventSubscriptionDao = EventSubscriptionStoreInitializer.getEventSubscriptionDao(); - return eventSubscriptionDao.getEventSubscriptionsByClientId(connection, clientId); - } catch (OBEventNotificationException e) { - log.error("Error while retrieving event subscriptions.", e); - throw new OBEventNotificationException(e.getMessage(), e); - } finally { - DatabaseUtil.closeConnection(connection); - } - } - - /** - * This method will call the dao layer to retrieve all event subscriptions by event type. - * - * @param eventType event type that needs to be subscribed by the retrieving event subscriptions. - * @return list of event subscriptions that are retrieved - * @throws OBEventNotificationException if an error occurred while retrieving the event subscriptions - */ - public List getEventSubscriptionsByClientIdAndEventType(String eventType) - throws OBEventNotificationException { - - - Connection connection = DatabaseUtil.getDBConnection(); - try { - EventSubscriptionDAO eventSubscriptionDao = EventSubscriptionStoreInitializer.getEventSubscriptionDao(); - return eventSubscriptionDao.getEventSubscriptionsByEventType(connection, eventType); - } catch (OBEventNotificationException e) { - log.error("Error while retrieving event subscriptions.", e); - throw new OBEventNotificationException(e.getMessage(), e); - } finally { - DatabaseUtil.closeConnection(connection); - } - } - - /** - * This method will call the dao layer to update an event subscription. - * - * @param eventSubscription event subscription object that needs to be updated - * @return true if the event subscription is updated successfully - * @throws OBEventNotificationException if an error occurred while updating the event subscription - */ - public Boolean updateEventSubscription(EventSubscription eventSubscription) - throws OBEventNotificationException { - - Connection connection = DatabaseUtil.getDBConnection(); - - EventSubscriptionDAO eventSubscriptionDao = EventSubscriptionStoreInitializer.getEventSubscriptionDao(); - - //get the stored event subscription - EventSubscription retrievedEventSubscription = eventSubscriptionDao. - getEventSubscriptionBySubscriptionId(connection, eventSubscription.getSubscriptionId()); - - //update request data column - try { - JSONParser parser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); - JSONObject storedRequestData = (JSONObject) parser.parse(retrievedEventSubscription.getRequestData()); - JSONObject receivedRequestData = (JSONObject) parser.parse(eventSubscription.getRequestData()); - for (String key : storedRequestData.keySet()) { - if (receivedRequestData.containsKey(key)) { - storedRequestData.put(key, receivedRequestData.get(key)); - } - } - eventSubscription.setRequestData(storedRequestData.toJSONString()); - } catch (ParseException e) { - log.error("Error while Parsing the stored request Object", e); - throw new OBEventNotificationException("Error while Parsing the stored request Object", e); - } - - //update event subscription - try { - boolean isUpdated = eventSubscriptionDao.updateEventSubscription(connection, eventSubscription); - - //update subscribed event types - if (isUpdated && eventSubscription.getEventTypes() != null && - !eventSubscription.getEventTypes().isEmpty()) { - //delete the existing subscribed event types - eventSubscriptionDao.deleteSubscribedEventTypes(connection, eventSubscription.getSubscriptionId()); - //store the updated subscribed event types - List storedEventTypes = eventSubscriptionDao.storeSubscribedEventTypes(connection, - eventSubscription.getSubscriptionId(), eventSubscription.getEventTypes()); - eventSubscription.setEventTypes(storedEventTypes); - } else if (!isUpdated) { - log.debug("Event subscription update failed."); - DatabaseUtil.rollbackTransaction(connection); - } - log.debug("Event subscription updated successfully."); - DatabaseUtil.commitTransaction(connection); - return isUpdated; - } catch (OBEventNotificationException e) { - log.error("Error while updating event subscription.", e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBEventNotificationException(e.getMessage(), e); - } finally { - DatabaseUtil.closeConnection(connection); - } - } - - /** - * This method will call the dao layer to delete an event subscription. - * - * @param subscriptionId subscription id of the event subscription - * @return true if the event subscription is deleted successfully - * @throws OBEventNotificationException if an error occurred while deleting the event subscription - */ - public Boolean deleteEventSubscription(String subscriptionId) throws OBEventNotificationException { - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - EventSubscriptionDAO eventSubscriptionDao = EventSubscriptionStoreInitializer.getEventSubscriptionDao(); - boolean isDeleted = eventSubscriptionDao.deleteEventSubscription(connection, subscriptionId); - if (isDeleted) { - log.debug("Event subscription deleted successfully."); - DatabaseUtil.commitTransaction(connection); - } else { - log.debug("Event subscription deletion failed."); - DatabaseUtil.rollbackTransaction(connection); - } - return isDeleted; - } catch (OBEventNotificationException e) { - log.error("Error while deleting event subscription.", e); - throw new OBEventNotificationException(e.getMessage(), e); - } finally { - DatabaseUtil.closeConnection(connection); - } - } - - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/ExtendedEventNotificationGenerator.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/ExtendedEventNotificationGenerator.java deleted file mode 100644 index 5dff1cb9..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/service/ExtendedEventNotificationGenerator.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.fasterxml.jackson.databind.JsonNode; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; - -import java.util.List; - -/** - * Custom Event Polling Generator Class. - */ -@Generated(message = "Extended Implementation excluded from tests") -public class ExtendedEventNotificationGenerator implements EventNotificationGenerator { - - @Override - public Notification generateEventNotificationBody(NotificationDTO notificationDAO, - List notificationEventList) throws OBEventNotificationException { - return null; - } - - @Override - public String generateEventNotification(JsonNode jsonNode) { - return null; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/util/EventNotificationServiceUtil.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/util/EventNotificationServiceUtil.java deleted file mode 100644 index a83a9cc7..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/java/com/wso2/openbanking/accelerator/event/notifications/service/util/EventNotificationServiceUtil.java +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.util; - -import com.fasterxml.jackson.databind.JsonNode; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventNotificationErrorDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.DefaultEventCreationServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.service.RealtimeEventNotificationRequestGenerator; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventNotificationGenerator; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; - -import java.util.Optional; - -/** - * Default event notification validations. - */ -public class EventNotificationServiceUtil { - - private static final Log log = LogFactory.getLog(EventNotificationServiceUtil.class); - private static volatile ConsentCoreServiceImpl consentCoreService; - - /** - * This method is used to send the polling generator as per config. - * - * @return EventNotificationGenerator - */ - public static EventNotificationGenerator getEventNotificationGenerator() { - - EventNotificationGenerator eventNotificationGenerator = (EventNotificationGenerator) - OpenBankingUtils.getClassInstanceFromFQN(OpenBankingConfigParser.getInstance() - .getEventNotificationGenerator()); - return eventNotificationGenerator; - } - - /** - * This method is used to send the default realtime event notification request generator. - * - * @return RealtimeEventNotificationRequestGenerator - */ - public static RealtimeEventNotificationRequestGenerator getRealtimeEventNotificationRequestGenerator() { - - RealtimeEventNotificationRequestGenerator realtimeEventNotificationRequestGenerator = - (RealtimeEventNotificationRequestGenerator) OpenBankingUtils - .getClassInstanceFromFQN(OpenBankingConfigParser.getInstance(). - getRealtimeEventNotificationRequestGenerator()); - return realtimeEventNotificationRequestGenerator; - } - - /** - * Method to modify event notification payload with custom eventValues. - * - * @param jsonNode Json Node to convert - * @return String eventNotificationPayload - */ - public static String getCustomNotificationPayload(JsonNode jsonNode) { - - String payload = jsonNode.toString(); - return payload; - } - - /** - * Method to get event JSON from eventInformation payload string. - * @param eventInformation String event Information - * @return JSONObject converted event json - * @throws ParseException Exception when parsing event information - */ - public static JSONObject getEventJSONFromString(String eventInformation) throws ParseException { - - JSONParser parser = new JSONParser(); - return (JSONObject) parser.parse(eventInformation); - } - - /** - * Validate if the client ID is existing. - * @param clientId client ID of the TPP - * @throws OBEventNotificationException Exception when validating client ID - */ - @Generated(message = "Excluded since this needs OAuth2Util service provider") - public static void validateClientId(String clientId) throws OBEventNotificationException { - - if (StringUtils.isNotEmpty(clientId)) { - Optional serviceProvider; - try { - serviceProvider = Optional.ofNullable(OAuth2Util.getServiceProvider(clientId)); - if (!serviceProvider.isPresent()) { - log.error(EventNotificationConstants.INVALID_CLIENT_ID); - throw new OBEventNotificationException(EventNotificationConstants.INVALID_CLIENT_ID); - } - } catch (IdentityOAuth2Exception e) { - log.error(EventNotificationConstants.INVALID_CLIENT_ID, e); - throw new OBEventNotificationException(EventNotificationConstants.INVALID_CLIENT_ID); - } - } - } - - @Generated(message = "Creating a single instance for ConsentCoreService") - public static synchronized ConsentCoreServiceImpl getConsentCoreServiceImpl() { - if (consentCoreService == null) { - synchronized (ConsentCoreServiceImpl.class) { - if (consentCoreService == null) { - consentCoreService = new ConsentCoreServiceImpl(); - } - } - } - return consentCoreService; - } - - /** - * Get the callback URL of the TPP from the Subscription Object. - * - * @param clientID client ID of the TPP - * @return callback URL of the TPP - */ - public static String getCallbackURL(String clientID) { - - return "http://localhost:8080/sample-tpp-server"; - } - - /** - * Get the default event creation service handler. - * - * @return DefaultEventCreationServiceHandler - */ - public static DefaultEventCreationServiceHandler getDefaultEventCreationServiceHandler() { - return new DefaultEventCreationServiceHandler(); - } - - /** - * Method to map Event subscription Service error to API response. - * - * @param error Error code - * @param errorDescription Error description - * @return EventNotificationErrorDTO - */ - public static EventNotificationErrorDTO getErrorDTO(String error, String errorDescription) { - EventNotificationErrorDTO eventNotificationErrorDTO = new EventNotificationErrorDTO(); - eventNotificationErrorDTO.setError(error); - eventNotificationErrorDTO.setErrorDescription(errorDescription); - return eventNotificationErrorDTO; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index 1ea4c491..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/constants/EventNotificationTestConstants.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/constants/EventNotificationTestConstants.java deleted file mode 100644 index 236d744b..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/constants/EventNotificationTestConstants.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.constants; - -import java.util.Arrays; -import java.util.List; - -/** - * Test constant class for EventNotification Tests. - */ -public class EventNotificationTestConstants { - - public static final String SAMPLE_CLIENT_ID = "19_FTbAvbZm9YC9QRBYw8E0hVnAa"; - public static final String SAMPLE_CLIENT_ID_2 = "19_FTbAvbZm9YC9QRBYw8E0hVnAb"; - public static final String SAMPLE_RESOURCE_ID = "85d81bdb-111e-4553-8c0c-0cd2dd780515"; - public static final String SAMPLE_NOTIFICATION_ID = "c2fcb77a-274d-4851-b392-a2c0af312fd7"; - public static final String SAMPLE_NOTIFICATION_ID_2 = "c2fcb77a-274d-4851-b392-a2c0af312fb7"; - - public static final String SAMPLE_ERROR_NOTIFICATION_ID = "d3fcb77a-274d-4851-b392-a2c0af312fd8"; - public static final Long UPDATED_TIME = 1646389384L; - public static final String SAMPLE_NOTIFICATION_EVENT_TYPE_1 = "urn_uk_org_openbanking_events_resource-update"; - public static final String SAMPLE_NOTIFICATION_EVENT_TYPE_2 = - "urn_uk_org_openbanking_events_consent-authorization-revoked"; - public static final Boolean SAMPLE_RETURN_IMMEDIATETLY = true; - public static final int SAMPLE_MAX_EVENTS = 5; - - public static final String ERROR_CODE = "authentication_failed"; - - public static final String ERROR_DESCRIPTION = "The SET could not be authenticated"; - - public static final String SAMPLE_SET = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ4MEpFRzM5VGJ6dmMyRXhvbG1TaWZaR1Np" + - "TzhhIiwiYXVkIjoieDBKRUczOVRienZjMkV4b2xtU2lmWkdTaU84YSIsImlzcyI6Ind3dy53c28yLmNvbSIsInR4biI6ImUwY2Y2NG" + - "RlLTlkMGUtNDBmYy04ZWUyLTFhNTNmYzNiOWY4ZiIsInRvZSI6MTY2NDI3MDYzNzAwMCwiaWF0IjoxNjY0Mjc2NzA5LCJqdGkiOi" + - "I0ZjMxMjAwNy00ZDNmLTQwZTQtYTUyNS0wZjZlZThiYjU0ZDkiLCJldmVudHMiOnsidXJuX3VrX29yZ19vcGVuYmFua2luZ19ldm" + - "VudHNfcmVzb3VyY2UtdXBkYXRlIjp7ImtleTIiOiJ2YWx1ZSIsInJlc291cmNlSUQiOiJmNmRlMWE3NC0xMmY1LTQ5NWQtYWRjNC0" + - "xNzI4YWQwMDAyZTAnIiwia2V5MyI6InZhbHVlIn0sInVybl91a19vcmdfb3BlbmJhbmtpbmdfZXZlbnRzX2NvbnNlbnQtYXV0aG9y" + - "aXphdGlvbi1yZXZva2VkIjp7ImtleTIiOiJ2YWx1ZSIsInJlc291cmNlSUQiOiJmNmRlMWE3NC0xMmY1LTQ5NWQtYWRjNC0xNzI4Y" + - "WQwMDAyZTAnIiwia2V5MyI6InZhbHVlIn19fQ.VrkFxa2fyRhf4rP1plhedKIXNTjsrbvVveDLLHZotll2GIbxm0lCCElGUXNh463" + - "R9_HXIjfyi61b0yN2gRZKiwhPftIe9AUdFj2e2hheiE_UTiVDo9RiEvo2drvE_-ri4MN0mKHPx2GdIGKx3WTo84Ike3VZitpi8WTL7" + - "Ap1mIK1RITOd9QGO2iAwXj5NQPy9iXDV9ynQTmblLeiessUAmI3WyoYEw82P-7M0yHWCf_ztFfg6w_s9uyrak8HFmsmHeQb86frLI" + - "i4UKGiGvAVM-dBF8BAEq5eFZ2TBYWDrugk4HrSdFz7AblReTzL8vF7XFlEocFQSQ1Y_k1hXQCn4g"; - - public static final String INVALID_CLIENT_ERROR = "\"A client was not\" +\n" + - " \" found for the client id : '19_FTbAvbZm9YC9QRBYw8E0hVnAa' in the database.\""; - - public static final String SAMPLE_CALLBACK_URL = "https://localhost:8080/callback"; - - public static final String SAMPLE_NOTIFICATION_PAYLOAD = - "{\"notificationId\": " + SAMPLE_NOTIFICATION_ID + ", \"SET\": " + SAMPLE_SET + "}"; - - public static final String SAMPLE_SPEC_VERSION = "3.1"; - public static final List SAMPLE_NOTIFICATION_EVENT_TYPES = Arrays.asList(SAMPLE_NOTIFICATION_EVENT_TYPE_1, - SAMPLE_NOTIFICATION_EVENT_TYPE_2); - public static final String SAMPLE_SUBSCRIPTION_ID_1 = "550e8400-e29b-41d4-a716-446655440000"; - public static final String SAMPLE_SUBSCRIPTION_ID_2 = "9e65ebe4-2251-4a89-ba74-54060e76f51d"; -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAOImplTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAOImplTests.java deleted file mode 100644 index b3435533..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/AggregatedPollingDAOImplTests.java +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.List; -import java.util.Map; - -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.when; -/** - * Test class for AggregatedPollingDAOImpl. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest(DatabaseUtil.class) -public class AggregatedPollingDAOImplTests extends PowerMockTestCase { - - private static Connection mockedConnection; - private static Connection mockedExceptionConnection; - private PreparedStatement mockedPreparedStatement; - - - AggregatedPollingDAOImpl aggregatedPollingDAOImpl = new AggregatedPollingDAOImpl( - new NotificationPollingSqlStatements()); - - @BeforeClass - public void initTest() throws Exception { - - mockedConnection = Mockito.mock(Connection.class); - mockedExceptionConnection = Mockito.mock(Connection.class); - mockedPreparedStatement = Mockito.mock(PreparedStatement.class); - } - - @BeforeMethod - public void mock() throws ConsentManagementException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - } - - @Test - public void testGetNotificationsByStatus() throws OBEventNotificationException, SQLException { - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.getString(EventNotificationConstants.NOTIFICATION_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - when(mockedResultSet.getString(EventNotificationConstants.CLIENT_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_CLIENT_ID); - when(mockedResultSet.getString(EventNotificationConstants.RESOURCE_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_RESOURCE_ID); - when(mockedResultSet.getString(EventNotificationConstants.STATUS)).thenReturn("OPEN"); - when(mockedResultSet.getTimestamp(EventNotificationConstants.UPDATED_TIMESTAMP)).thenReturn( - new Timestamp(System.currentTimeMillis())); - - List eventsList = aggregatedPollingDAOImpl.getNotificationsByStatus("OPEN"); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, - eventsList.get(0).getNotificationId()); - } - - @Test - public void testGetEventsByNotificationID() throws OBEventNotificationException, SQLException, IOException { - - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.getString(EventNotificationConstants.NOTIFICATION_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)).thenReturn( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_INFO)).thenReturn( - EventNotificationTestUtils.getSampleEventInformation().toString()); - - List eventsList = aggregatedPollingDAOImpl.getEventsByNotificationID( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, - eventsList.get(0).getNotificationId()); - - } - - @Test - public void testGetNotificationsByClientIdAndStatus() throws SQLException, OBEventNotificationException { - - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.getString(EventNotificationConstants.NOTIFICATION_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - when(mockedResultSet.getString(EventNotificationConstants.CLIENT_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_CLIENT_ID); - when(mockedResultSet.getString(EventNotificationConstants.RESOURCE_ID)).thenReturn( - EventNotificationTestConstants.SAMPLE_RESOURCE_ID); - when(mockedResultSet.getString(EventNotificationConstants.STATUS)).thenReturn("OPEN"); - when(mockedResultSet.getTimestamp(EventNotificationConstants.UPDATED_TIMESTAMP)).thenReturn( - new Timestamp(System.currentTimeMillis())); - - List eventsList = aggregatedPollingDAOImpl.getNotificationsByClientIdAndStatus( - EventNotificationTestConstants.SAMPLE_CLIENT_ID, "OPEN", 5); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, - eventsList.get(0).getNotificationId()); - } - - @Test - public void testGetEventsStatus() throws SQLException, IOException, OBEventNotificationException { - - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedResultSet.next()).thenReturn(true); - when(mockedResultSet.getString("STATUS")).thenReturn(EventNotificationConstants.OPEN); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - - boolean status = aggregatedPollingDAOImpl.getNotificationStatus(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_ID); - - Assert.assertTrue(status); - - } - - @Test - public void testStoreErrorNotifications() throws SQLException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - Map errors = aggregatedPollingDAOImpl. - storeErrorNotification(EventNotificationTestUtils.getNotificationError()); - - Assert.assertTrue(errors.containsKey(EventNotificationTestConstants.SAMPLE_ERROR_NOTIFICATION_ID)); - } - - @Test - public void testGetEventsStatusACK() throws SQLException, IOException, OBEventNotificationException { - - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedResultSet.next()).thenReturn(true); - when(mockedResultSet.getString("STATUS")).thenReturn(EventNotificationConstants.ACK); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - - boolean status = aggregatedPollingDAOImpl.getNotificationStatus(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_ID); - - Assert.assertFalse(status); - - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testGetEventsStatusDBError() throws SQLException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedExceptionConnection); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedExceptionConnection.prepareStatement(anyString())).thenThrow(new SQLException()); - - boolean status = aggregatedPollingDAOImpl.getNotificationStatus(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_ID); - } - - @Test - public void testGetNotificationCount() throws SQLException, OBEventNotificationException { - - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedResultSet.next()).thenReturn(true); - when(mockedResultSet.getInt("NOTIFICATION_COUNT")).thenReturn(4); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - - int eventCount = aggregatedPollingDAOImpl.getNotificationCountByClientIdAndStatus( - EventNotificationTestConstants.SAMPLE_CLIENT_ID, EventNotificationConstants.OPEN); - - Assert.assertEquals(eventCount, 4); - } - - @Test - public void testGetNotificationCountNoEvents() throws SQLException, OBEventNotificationException { - - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - - int eventCount = aggregatedPollingDAOImpl.getNotificationCountByClientIdAndStatus( - EventNotificationTestConstants.SAMPLE_CLIENT_ID, EventNotificationConstants.OPEN); - - Assert.assertEquals(eventCount, 0); - } - - @Test - public void testUpdateNotificationStatusById() throws SQLException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - Boolean updatedStatus = aggregatedPollingDAOImpl.updateNotificationStatusById( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, "ACK"); - - Assert.assertTrue(updatedStatus); - } - - @Test - public void testUpdateNotificationStatusByIdError() throws SQLException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - Boolean updatedStatus = aggregatedPollingDAOImpl.updateNotificationStatusById( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, "ACK"); - - Assert.assertFalse(updatedStatus); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAOImplTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAOImplTests.java deleted file mode 100644 index c5413a2e..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventPublisherDAOImplTests.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import net.minidev.json.parser.ParseException; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.when; -/** - * Test class for EventPublisherDAOImpl. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest(DatabaseUtil.class) -public class EventPublisherDAOImplTests extends PowerMockTestCase { - - private static Connection mockedConnection; - private static Connection mockedExceptionConnection; - private PreparedStatement mockedPreparedStatement; - - EventPublisherDAOImpl eventPublisherDAOImpl = new EventPublisherDAOImpl(new NotificationPublisherSqlStatements()); - - @BeforeClass - public void initTest() throws Exception { - - mockedConnection = Mockito.mock(Connection.class); - mockedExceptionConnection = Mockito.mock(Connection.class); - mockedPreparedStatement = Mockito.mock(PreparedStatement.class); - } - - @Test - public void testPersistEventNotification() throws SQLException, ParseException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - int[] noOfRows = new int[5]; - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - when(mockedPreparedStatement.executeBatch()).thenReturn(noOfRows); - - String notificationId = eventPublisherDAOImpl.persistEventNotification(mockedConnection, - EventNotificationTestUtils.getSampleNotificationDTO(), - EventNotificationTestUtils.getSampleEventList()); - - Assert.assertEquals(notificationId, EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testPersistEventNotificationDBError() throws SQLException, - ParseException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - int[] noOfRows = new int[5]; - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedExceptionConnection); - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - //when(mockedPreparedStatement.executeBatch()).thenReturn(noOfRows); - - String notificationId = eventPublisherDAOImpl.persistEventNotification(mockedConnection, - EventNotificationTestUtils.getSampleNotificationDTO(), - EventNotificationTestUtils.getSampleEventList()); - - Assert.assertEquals(notificationId, EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAOImplTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAOImplTests.java deleted file mode 100644 index 5579e440..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/EventSubscriptionDAOImplTests.java +++ /dev/null @@ -1,390 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test class for EventSubscriptionDAOImpl. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest(DatabaseUtil.class) -public class EventSubscriptionDAOImplTests extends PowerMockTestCase { - private static Connection mockedConnection; - private PreparedStatement mockedPreparedStatement; - - EventSubscriptionDAOImpl eventSubscriptionDAOImpl = new EventSubscriptionDAOImpl( - new EventSubscriptionSqlStatements()); - - @BeforeMethod - public void mock() throws OBEventNotificationException { - mockedConnection = Mockito.mock(Connection.class); - mockedPreparedStatement = Mockito.mock(PreparedStatement.class); - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - } - - @Test - public void testStoreEventSubscription() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - EventSubscription sampleEventSubscription = EventNotificationTestUtils.getSampleEventSubscription(); - - EventSubscription result = eventSubscriptionDAOImpl.storeEventSubscription(mockedConnection, - sampleEventSubscription); - - Assert.assertNotNull(sampleEventSubscription.getSubscriptionId()); - Assert.assertNotNull(sampleEventSubscription.getTimeStamp()); - Assert.assertEquals("CREATED", result.getStatus()); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testStoreEventSubscriptionDBError() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - eventSubscriptionDAOImpl.storeEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscription()); - } - - @Test - public void testStoreSubscribedEventTypes() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeBatch()).thenReturn(new int[]{1, 1, 1}); - List sampleEventTypes = EventNotificationTestUtils.getSampleStoredEventTypes(); - - List result = eventSubscriptionDAOImpl.storeSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, sampleEventTypes); - - Assert.assertEquals(sampleEventTypes, result); - } - - @Test - public void testStoreSubscribedEventTypesFailure() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeBatch()).thenReturn(new int[]{0, 1, 1}); - List sampleEventTypes = EventNotificationTestUtils.getSampleStoredEventTypes(); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - storeSubscribedEventTypes(mockedConnection, EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - sampleEventTypes)); - } - - @Test - public void testStoreSubscribedEventTypesDBError() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeBatch()).thenThrow(new SQLException()); - List sampleEventTypes = EventNotificationTestUtils.getSampleStoredEventTypes(); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - storeSubscribedEventTypes(mockedConnection, EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - sampleEventTypes)); - } - - @Test - public void testGetEventSubscriptionBySubscriptionId() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.next()).thenReturn(true, true, true, false); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2); - - EventSubscription result = eventSubscriptionDAOImpl.getEventSubscriptionBySubscriptionId( - mockedConnection, EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - List eventTypes = result.getEventTypes(); - Assert.assertTrue(eventTypes.contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - } - - @Test - public void testGetEventSubscriptionBySubscriptionIdNotFound() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.next()).thenReturn(false); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - getEventSubscriptionBySubscriptionId(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1)); - } - - @Test - public void testGetEventSubscriptionBySubscriptionIdDBError() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeQuery()).thenThrow(new SQLException()); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - getEventSubscriptionBySubscriptionId(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1)); - } - - @Test - public void testGetEventSubscriptionsByClientId() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedResultSet.next()).thenReturn(true, true, true, true, true, true, true, false); - when(mockedResultSet.getString(EventNotificationConstants.SUBSCRIPTION_ID)). - thenReturn(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2); - - List eventSubscriptions = eventSubscriptionDAOImpl.getEventSubscriptionsByClientId( - mockedConnection, EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertNotNull(eventSubscriptions); - Assert.assertEquals(2, eventSubscriptions.size()); // We expect one EventSubscription object - - EventSubscription subscription = eventSubscriptions.get(0); - Assert.assertNotNull(subscription.getEventTypes()); - Assert.assertEquals(subscription.getEventTypes().size(), 2); - Assert.assertTrue(subscription.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - Assert.assertTrue(subscription.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_2)); - - EventSubscription subscription2 = eventSubscriptions.get(1); - Assert.assertNotNull(subscription2.getEventTypes()); - Assert.assertEquals(subscription2.getEventTypes().size(), 2); - Assert.assertTrue(subscription2.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - Assert.assertTrue(subscription2.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_2)); - } - - @Test - public void testGetEventSubscriptionsByClientIdNoSubscriptions() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(false); - - List eventSubscriptions = eventSubscriptionDAOImpl.getEventSubscriptionsByClientId( - mockedConnection, EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertNotNull(eventSubscriptions); - Assert.assertTrue(eventSubscriptions.isEmpty()); // We expect an empty list since no data was found - } - - @Test - public void testGetEventSubscriptionsByEventType() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedResultSet.next()).thenReturn(true, true, true, true, true, true, true, false); - when(mockedResultSet.getString(EventNotificationConstants.SUBSCRIPTION_ID)). - thenReturn(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2); - - List eventSubscriptions = eventSubscriptionDAOImpl. - getEventSubscriptionsByEventType(mockedConnection, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(2, eventSubscriptions.size()); - - EventSubscription subscription1 = eventSubscriptions.get(0); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, subscription1.getSubscriptionId()); - Assert.assertEquals(subscription1.getEventTypes().size(), 2); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - subscription1.getEventTypes().get(0)); - - EventSubscription subscription2 = eventSubscriptions.get(1); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, subscription2.getSubscriptionId()); - Assert.assertEquals(subscription2.getEventTypes().size(), 2); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - subscription2.getEventTypes().get(0)); - } - - @Test - public void testGetEventSubscriptionsByEventTypeNoSubscriptions() throws OBEventNotificationException, - SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(false); - - List eventSubscriptions = eventSubscriptionDAOImpl. - getEventSubscriptionsByEventType(mockedConnection, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(0, eventSubscriptions.size()); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testGetEventSubscriptionsByEventType_SQLException() throws OBEventNotificationException, - SQLException { - // Mock the behavior of the PreparedStatement and ResultSet - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenThrow(new SQLException()); - - // Call the method under test (expecting an exception to be thrown) - eventSubscriptionDAOImpl.getEventSubscriptionsByEventType(mockedConnection, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - } - - @Test - public void testUpdateEventSubscription() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - Boolean isUpdated = eventSubscriptionDAOImpl.updateEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated()); - Assert.assertTrue(isUpdated); - } - - @Test - public void testUpdateEventSubscriptionFailed() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - Boolean isUpdated = eventSubscriptionDAOImpl.updateEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated()); - Assert.assertFalse(isUpdated); - } - - @Test - public void testUpdateEventSubscriptionDBError() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - Assert.assertThrows(OBEventNotificationException.class, - () -> eventSubscriptionDAOImpl.updateEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated())); - } - - @Test - public void testDeleteEventSubscription() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - Boolean isDeleted = eventSubscriptionDAOImpl.deleteEventSubscription(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertTrue(isDeleted); - } - - @Test - public void testDeleteEventSubscriptionFails() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - Boolean isDeleted = eventSubscriptionDAOImpl.deleteEventSubscription(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertFalse(isDeleted); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testDeleteEventSubscriptionDBError() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - eventSubscriptionDAOImpl.deleteEventSubscription(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - } - - @Test - public void testDeleteSubscribedEventTypes() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - boolean isDeleted = eventSubscriptionDAOImpl.deleteSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertTrue(isDeleted); - } - - @Test - public void testDeleteSubscribedEventTypesFails() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - boolean isDeleted = eventSubscriptionDAOImpl.deleteSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertFalse(isDeleted); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testDeleteSubscribedEventTypesDBError() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - eventSubscriptionDAOImpl.deleteSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - } -} - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlEventSubscriptionDAOImplTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlEventSubscriptionDAOImplTests.java deleted file mode 100644 index e2aa9aa1..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/dao/PostgreSqlEventSubscriptionDAOImplTests.java +++ /dev/null @@ -1,382 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. - * - * This software is the property of WSO2 LLC. and its suppliers, if any. - * Dissemination of any information or reproduction of any material contained - * herein in any form is strictly forbidden, unless permitted by WSO2 expressly. - * You may not alter or remove any copyright or other notice from copies of this content. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.dao; - -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Test class for EventSubscriptionDAOImpl. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest(DatabaseUtil.class) -public class PostgreSqlEventSubscriptionDAOImplTests extends PowerMockTestCase { - private static Connection mockedConnection; - private PreparedStatement mockedPreparedStatement; - - PostgreSqlEventSubscriptionDAOImpl eventSubscriptionDAOImpl = new PostgreSqlEventSubscriptionDAOImpl( - new EventSubscriptionSqlStatements()); - - @BeforeMethod - public void mock() throws OBEventNotificationException { - mockedConnection = Mockito.mock(Connection.class); - mockedPreparedStatement = Mockito.mock(PreparedStatement.class); - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - } - - @Test - public void testStoreEventSubscription() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - EventSubscription sampleEventSubscription = EventNotificationTestUtils.getSampleEventSubscription(); - - EventSubscription result = eventSubscriptionDAOImpl.storeEventSubscription(mockedConnection, - sampleEventSubscription); - - Assert.assertNotNull(sampleEventSubscription.getSubscriptionId()); - Assert.assertNotNull(sampleEventSubscription.getTimeStamp()); - Assert.assertEquals("CREATED", result.getStatus()); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testStoreEventSubscriptionDBError() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - eventSubscriptionDAOImpl.storeEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscription()); - } - - @Test - public void testStoreSubscribedEventTypes() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeBatch()).thenReturn(new int[]{1, 1, 1}); - List sampleEventTypes = EventNotificationTestUtils.getSampleStoredEventTypes(); - - List result = eventSubscriptionDAOImpl.storeSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, sampleEventTypes); - - Assert.assertEquals(sampleEventTypes, result); - } - - @Test - public void testStoreSubscribedEventTypesFailure() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeBatch()).thenReturn(new int[]{0, 1, 1}); - List sampleEventTypes = EventNotificationTestUtils.getSampleStoredEventTypes(); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - storeSubscribedEventTypes(mockedConnection, EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - sampleEventTypes)); - } - - @Test - public void testStoreSubscribedEventTypesDBError() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeBatch()).thenThrow(new SQLException()); - List sampleEventTypes = EventNotificationTestUtils.getSampleStoredEventTypes(); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - storeSubscribedEventTypes(mockedConnection, EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - sampleEventTypes)); - } - - @Test - public void testGetEventSubscriptionBySubscriptionId() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString(), anyInt(), anyInt())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.next()).thenReturn(true, true, true, false); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2); - - EventSubscription result = eventSubscriptionDAOImpl.getEventSubscriptionBySubscriptionId( - mockedConnection, EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - List eventTypes = result.getEventTypes(); - Assert.assertTrue(eventTypes.contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - } - - @Test - public void testGetEventSubscriptionBySubscriptionIdNotFound() throws SQLException { - when(mockedConnection.prepareStatement(anyString(), anyInt(), anyInt())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.next()).thenReturn(false); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - getEventSubscriptionBySubscriptionId(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1)); - } - - @Test - public void testGetEventSubscriptionBySubscriptionIdDBError() throws SQLException { - when(mockedConnection.prepareStatement(anyString(), anyInt(), anyInt())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeQuery()).thenThrow(new SQLException()); - - Assert.assertThrows(OBEventNotificationException.class, () -> eventSubscriptionDAOImpl. - getEventSubscriptionBySubscriptionId(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1)); - } - - @Test - public void testGetEventSubscriptionsByClientId() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString(), anyInt(), anyInt())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedResultSet.next()).thenReturn(true, true, true, true, true, true, true, false); - when(mockedResultSet.getString(EventNotificationConstants.SUBSCRIPTION_ID)). - thenReturn(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2); - - List eventSubscriptions = eventSubscriptionDAOImpl.getEventSubscriptionsByClientId( - mockedConnection, EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertNotNull(eventSubscriptions); - Assert.assertEquals(2, eventSubscriptions.size()); // We expect one EventSubscription object - - EventSubscription subscription = eventSubscriptions.get(0); - Assert.assertNotNull(subscription.getEventTypes()); - Assert.assertEquals(subscription.getEventTypes().size(), 2); - Assert.assertTrue(subscription.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - Assert.assertTrue(subscription.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_2)); - - EventSubscription subscription2 = eventSubscriptions.get(1); - Assert.assertNotNull(subscription2.getEventTypes()); - Assert.assertEquals(subscription2.getEventTypes().size(), 2); - Assert.assertTrue(subscription2.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - Assert.assertTrue(subscription2.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_2)); - } - - @Test - public void testGetEventSubscriptionsByClientIdNoSubscriptions() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString(), anyInt(), anyInt())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(false); - - List eventSubscriptions = eventSubscriptionDAOImpl.getEventSubscriptionsByClientId( - mockedConnection, EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertNotNull(eventSubscriptions); - Assert.assertTrue(eventSubscriptions.isEmpty()); // We expect an empty list since no data was found - } - - @Test - public void testGetEventSubscriptionsByEventType() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(true); - when(mockedResultSet.next()).thenReturn(true, true, true, true, true, true, true, false); - when(mockedResultSet.getString(EventNotificationConstants.SUBSCRIPTION_ID)). - thenReturn(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2); - when(mockedResultSet.getString(EventNotificationConstants.EVENT_TYPE)). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_2); - - List eventSubscriptions = eventSubscriptionDAOImpl. - getEventSubscriptionsByEventType(mockedConnection, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(2, eventSubscriptions.size()); - - EventSubscription subscription1 = eventSubscriptions.get(0); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1, subscription1.getSubscriptionId()); - Assert.assertEquals(subscription1.getEventTypes().size(), 2); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - subscription1.getEventTypes().get(0)); - - EventSubscription subscription2 = eventSubscriptions.get(1); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2, subscription2.getSubscriptionId()); - Assert.assertEquals(subscription2.getEventTypes().size(), 2); - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - subscription2.getEventTypes().get(0)); - } - - @Test - public void testGetEventSubscriptionsByEventTypeNoSubscriptions() throws OBEventNotificationException, - SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenReturn(false); - - List eventSubscriptions = eventSubscriptionDAOImpl. - getEventSubscriptionsByEventType(mockedConnection, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(0, eventSubscriptions.size()); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testGetEventSubscriptionsByEventType_SQLException() throws OBEventNotificationException, - SQLException { - // Mock the behavior of the PreparedStatement and ResultSet - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - ResultSet mockedResultSet = Mockito.mock(ResultSet.class); - when(mockedPreparedStatement.executeQuery()).thenReturn(mockedResultSet); - when(mockedResultSet.isBeforeFirst()).thenThrow(new SQLException()); - - // Call the method under test (expecting an exception to be thrown) - eventSubscriptionDAOImpl.getEventSubscriptionsByEventType(mockedConnection, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - } - - @Test - public void testUpdateEventSubscription() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - Boolean isUpdated = eventSubscriptionDAOImpl.updateEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated()); - Assert.assertTrue(isUpdated); - } - - @Test - public void testUpdateEventSubscriptionFailed() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - Boolean isUpdated = eventSubscriptionDAOImpl.updateEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated()); - Assert.assertFalse(isUpdated); - } - - @Test - public void testUpdateEventSubscriptionDBError() throws SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - Assert.assertThrows(OBEventNotificationException.class, - () -> eventSubscriptionDAOImpl.updateEventSubscription(mockedConnection, - EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated())); - } - - @Test - public void testDeleteEventSubscription() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - Boolean isDeleted = eventSubscriptionDAOImpl.deleteEventSubscription(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertTrue(isDeleted); - } - - @Test - public void testDeleteEventSubscriptionFails() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - Boolean isDeleted = eventSubscriptionDAOImpl.deleteEventSubscription(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertFalse(isDeleted); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testDeleteEventSubscriptionDBError() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - eventSubscriptionDAOImpl.deleteEventSubscription(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - } - - @Test - public void testDeleteSubscribedEventTypes() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(1); - - boolean isDeleted = eventSubscriptionDAOImpl.deleteSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertTrue(isDeleted); - } - - @Test - public void testDeleteSubscribedEventTypesFails() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenReturn(0); - - boolean isDeleted = eventSubscriptionDAOImpl.deleteSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertFalse(isDeleted); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testDeleteSubscribedEventTypesDBError() throws OBEventNotificationException, SQLException { - when(mockedConnection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(mockedPreparedStatement.executeUpdate()).thenThrow(new SQLException()); - - eventSubscriptionDAOImpl.deleteSubscribedEventTypes(mockedConnection, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - } -} - diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventCreationServiceHandlerTest.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventCreationServiceHandlerTest.java deleted file mode 100644 index 5137e1b5..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventCreationServiceHandlerTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventCreationService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.junit.Before; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.sql.SQLException; - -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -/** - * Test class for DefaultEventCreationServiceHandler. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({EventNotificationServiceUtil.class, ConsentCoreServiceImpl.class}) -public class DefaultEventCreationServiceHandlerTest extends PowerMockTestCase { - - @Mock - ConsentCoreServiceImpl consentCoreServiceImpl; - - @Before - public void setUp() throws SQLException, ConsentManagementException { - - ConsentResource consentResource = new ConsentResource(); - when(consentCoreServiceImpl.getConsent(anyString(), false)).thenReturn(consentResource); - - } - - DefaultEventCreationServiceHandler defaultEventCreationServiceHandler = new DefaultEventCreationServiceHandler(); - - @Test - public void testPublishOBEvents() throws Exception { - - EventCreationService eventCreationService = Mockito.mock(EventCreationService.class); - Mockito.when(eventCreationService.publishOBEventNotification(Mockito.anyObject())). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - defaultEventCreationServiceHandler.setEventCreationService(eventCreationService); - ConsentResource consentResource = new ConsentResource(); - consentResource.setConsentID("0ba972a9-08cd-4cad-b7e2-20655bcbd9e0"); - when(consentCoreServiceImpl.getConsent(anyString(), anyBoolean())).thenReturn(consentResource); - - mockStatic(EventNotificationServiceUtil.class); - PowerMockito.doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - PowerMockito.when(EventNotificationServiceUtil.getConsentCoreServiceImpl()).thenReturn(consentCoreServiceImpl); - - EventCreationResponse eventCreationResponse = - defaultEventCreationServiceHandler.publishOBEvent( - EventNotificationTestUtils.getNotificationCreationDTO()); - - Assert.assertEquals(eventCreationResponse.getStatus(), EventNotificationConstants.CREATED); - Assert.assertEquals(eventCreationResponse.getResponseBody().get(EventNotificationConstants.NOTIFICATIONS_ID), - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - } - - @Test - public void testPublishOBEventConsentException() throws Exception { - - EventCreationService eventCreationService = Mockito.mock(EventCreationService.class); - Mockito.when(eventCreationService.publishOBEventNotification(Mockito.anyObject())). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - defaultEventCreationServiceHandler.setEventCreationService(eventCreationService); - when(consentCoreServiceImpl.getConsent(anyString(), anyBoolean())).thenThrow(new ConsentManagementException( - "Consent resource doesn't exist")); - - mockStatic(EventNotificationServiceUtil.class); - PowerMockito.doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - PowerMockito.when(EventNotificationServiceUtil.getConsentCoreServiceImpl()).thenReturn(consentCoreServiceImpl); - - EventCreationResponse eventCreationResponse = - defaultEventCreationServiceHandler.publishOBEvent(EventNotificationTestUtils. - getNotificationCreationDTO()); - - Assert.assertEquals(eventCreationResponse.getStatus(), EventNotificationConstants.BAD_REQUEST); - } - - @Test - public void testPublishOBEventInvalidClient() throws Exception { - - EventCreationService eventCreationService = Mockito.mock(EventCreationService.class); - Mockito.when(eventCreationService.publishOBEventNotification(Mockito.anyObject())). - thenReturn(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - defaultEventCreationServiceHandler.setEventCreationService(eventCreationService); - ConsentResource consentResource = new ConsentResource(); - consentResource.setConsentID("0ba972a9-08cd-4cad-b7e2-20655bcbd9e0"); - when(consentCoreServiceImpl.getConsent(anyString(), anyBoolean())).thenReturn(consentResource); - - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.doThrow(new OBEventNotificationException("Invalid client ID")). - when(EventNotificationServiceUtil.class); - EventNotificationServiceUtil.validateClientId(anyString()); - PowerMockito.when(EventNotificationServiceUtil.getConsentCoreServiceImpl()).thenReturn(consentCoreServiceImpl); - - EventCreationResponse eventCreationResponse = - defaultEventCreationServiceHandler.publishOBEvent( - EventNotificationTestUtils.getNotificationCreationDTO()); - - Assert.assertEquals(eventCreationResponse.getStatus(), EventNotificationConstants.BAD_REQUEST); - } - - @Test - public void testPublishOBEventsServiceException() throws Exception { - - EventCreationService eventCreationService = Mockito.mock(EventCreationService.class); - Mockito.when(eventCreationService.publishOBEventNotification(Mockito.anyObject())).thenThrow(new - OBEventNotificationException("Error when persisting events")); - - defaultEventCreationServiceHandler.setEventCreationService(eventCreationService); - ConsentResource consentResource = new ConsentResource(); - consentResource.setConsentID("0ba972a9-08cd-4cad-b7e2-20655bcbd9e0"); - when(consentCoreServiceImpl.getConsent(anyString(), anyBoolean())).thenReturn(consentResource); - - mockStatic(EventNotificationServiceUtil.class); - PowerMockito.doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - PowerMockito.when(EventNotificationServiceUtil.getConsentCoreServiceImpl()).thenReturn(consentCoreServiceImpl); - - EventCreationResponse eventCreationResponse = - defaultEventCreationServiceHandler.publishOBEvent( - EventNotificationTestUtils.getNotificationCreationDTO()); - - Assert.assertEquals(eventCreationResponse.getStatus(), EventNotificationConstants.BAD_REQUEST); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventPollingServiceHandlerTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventPollingServiceHandlerTests.java deleted file mode 100644 index 3700bc50..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventPollingServiceHandlerTests.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventPollingDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventPollingResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventPollingService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import net.minidev.json.JSONObject; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -/** - * Test class for DefaultEventPollingServiceHandler. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class, EventNotificationServiceUtil.class}) -public class DefaultEventPollingServiceHandlerTests extends PowerMockTestCase { - - @BeforeMethod - public void mock() { - - EventNotificationTestUtils.mockConfigParser(); - - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - DefaultEventPollingServiceHandler defaultEventPollingServiceHandler = new DefaultEventPollingServiceHandler(); - - - @Test - public void testMapPollingRequest() { - - EventPollingDTO eventPollingDTO = defaultEventPollingServiceHandler.mapPollingRequest( - EventNotificationTestUtils.getEventRequest()); - - Assert.assertEquals(eventPollingDTO.getReturnImmediately(), - EventNotificationTestConstants.SAMPLE_RETURN_IMMEDIATETLY); - Assert.assertEquals(eventPollingDTO.getMaxEvents(), EventNotificationTestConstants.SAMPLE_MAX_EVENTS); - } - -// @Test -// public void mapPollingForEmptyRequest() { -// JSONObject eventPollingRequest = new JSONObject(); -// eventPollingRequest.put(EventNotificationConstants.X_WSO2_CLIENT_ID, -// EventNotificationTestConstants.SAMPLE_CLIENT_ID); -// EventPollingDTO eventPollingDTO = defaultEventPollingServiceHandler.mapPollingRequest(eventPollingRequest); -// -// Assert.assertEquals(eventPollingDTO., 0); -// } - - @Test - public void testMapPollingRequestWithError() { - - JSONObject eventRequest = EventNotificationTestUtils.getEventRequest(); - eventRequest.put(EventNotificationConstants.SET_ERRORS, EventNotificationTestUtils.getPollingError()); - - EventPollingDTO eventPollingDTO = defaultEventPollingServiceHandler.mapPollingRequest(eventRequest); - - Assert.assertEquals(eventPollingDTO.getMaxEvents(), EventNotificationTestConstants.SAMPLE_MAX_EVENTS); - } - - - @Test - public void testPollEvents() throws Exception { - - JSONObject eventPollingRequest = new JSONObject(); - eventPollingRequest.put(EventNotificationConstants.X_WSO2_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventPollingRequest.put(EventNotificationConstants.MAX_EVENTS, 5); - - EventPollingService eventPollingService = Mockito.mock(EventPollingService.class); - Mockito.when(eventPollingService.pollEvents(Mockito.anyObject())).thenReturn(EventNotificationTestUtils. - getAggregatedPollingResponse()); - - defaultEventPollingServiceHandler.setEventPollingService(eventPollingService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventPollingResponse eventPollingResponse = - defaultEventPollingServiceHandler.pollEvents(eventPollingRequest); - - Assert.assertEquals(eventPollingResponse.getStatus(), "OK"); - Assert.assertTrue(eventPollingResponse.getResponseBody().containsKey("moreAvailable")); - Assert.assertTrue(eventPollingResponse.getResponseBody().containsKey("sets")); - } - - @Test - public void testPollEventsInvalidClient() throws Exception { - JSONObject eventPollingRequest = new JSONObject(); - eventPollingRequest.put(EventNotificationConstants.X_WSO2_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventPollingRequest.put(EventNotificationConstants.MAX_EVENTS, 5); - - EventPollingService eventPollingService = Mockito.mock(EventPollingService.class); - Mockito.when(eventPollingService.pollEvents(Mockito.anyObject())).thenReturn(EventNotificationTestUtils. - getAggregatedPollingResponse()); - - defaultEventPollingServiceHandler.setEventPollingService(eventPollingService); - - mockStatic(EventNotificationServiceUtil.class); - PowerMockito.doThrow(new OBEventNotificationException("Invalid client ID")).when( - EventNotificationServiceUtil.class); - EventNotificationServiceUtil.validateClientId(anyString()); - - EventPollingResponse eventPollingResponse = - defaultEventPollingServiceHandler.pollEvents(eventPollingRequest); - - Assert.assertEquals(eventPollingResponse.getStatus(), EventNotificationConstants.BAD_REQUEST); - } - - @Test - public void testPollEventsServiceError() throws Exception { - - JSONObject eventPollingRequest = new JSONObject(); - eventPollingRequest.put(EventNotificationConstants.X_WSO2_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventPollingRequest.put(EventNotificationConstants.MAX_EVENTS, 5); - - EventPollingService eventPollingService = Mockito.mock(EventPollingService.class); - Mockito.when(eventPollingService.pollEvents(Mockito.anyObject())).thenThrow(new - OBEventNotificationException("Error when polling events")); - - defaultEventPollingServiceHandler.setEventPollingService(eventPollingService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventPollingResponse eventPollingResponse = - defaultEventPollingServiceHandler.pollEvents(eventPollingRequest); - - Assert.assertEquals(eventPollingResponse.getStatus(), EventNotificationConstants.BAD_REQUEST); - - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventSubscriptionServiceHandlerTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventSubscriptionServiceHandlerTests.java deleted file mode 100644 index f8cd9f2f..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/DefaultEventSubscriptionServiceHandlerTests.java +++ /dev/null @@ -1,298 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventSubscriptionResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.service.EventSubscriptionService; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import net.minidev.json.JSONObject; -import org.eclipse.jetty.http.HttpStatus; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -/** - * Test class for DefaultEventSubscriptionServiceHandler. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class, EventNotificationServiceUtil.class}) -public class DefaultEventSubscriptionServiceHandlerTests extends PowerMockTestCase { - @BeforeMethod - public void mock() { - EventNotificationTestUtils.mockConfigParser(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - DefaultEventSubscriptionServiceHandler defaultEventSubscriptionServiceHandler = - new DefaultEventSubscriptionServiceHandler(); - - @Test - public void testCreateEventSubscription() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.createEventSubscription(Mockito.anyObject())) - .thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscription()); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionCreationResponse = defaultEventSubscriptionServiceHandler - .createEventSubscription(EventNotificationTestUtils.getSampleEventSubscriptionDTO()); - - Assert.assertEquals(eventSubscriptionCreationResponse.getStatus(), HttpStatus.CREATED_201); - } - - @Test - public void testCreateEventSubscriptionServiceError() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.createEventSubscription(Mockito.anyObject())) - .thenThrow(new OBEventNotificationException(EventNotificationConstants. - ERROR_STORING_EVENT_SUBSCRIPTION)); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionCreationResponse = defaultEventSubscriptionServiceHandler - .createEventSubscription(EventNotificationTestUtils.getSampleEventSubscriptionDTO()); - - Assert.assertEquals(eventSubscriptionCreationResponse.getStatus(), - HttpStatus.INTERNAL_SERVER_ERROR_500); - } - - @Test - public void testGetEventSubscription() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.getEventSubscriptionBySubscriptionId(Mockito.anyObject())) - .thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscription()); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionRetrieveResponse = defaultEventSubscriptionServiceHandler - .getEventSubscription(EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertEquals(eventSubscriptionRetrieveResponse.getStatus(), HttpStatus.OK_200); - } - - @Test - public void testGetEventSubscriptionServiceError() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.getEventSubscriptionBySubscriptionId(Mockito.anyObject())) - .thenThrow(new OBEventNotificationException(EventNotificationConstants. - ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS)); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionRetrieveResponse = defaultEventSubscriptionServiceHandler - .getEventSubscription(EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertEquals(eventSubscriptionRetrieveResponse.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR_500); - } - - @Test - public void testGetAllEventSubscriptions() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.getEventSubscriptionsByClientId(Mockito.anyObject())) - .thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscriptions()); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionRetrieveResponse = defaultEventSubscriptionServiceHandler - .getAllEventSubscriptions(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertEquals(eventSubscriptionRetrieveResponse.getStatus(), HttpStatus.OK_200); - } - - @Test - public void testGetAllEventSubscriptionsServiceError() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.getEventSubscriptionsByClientId(Mockito.anyObject())) - .thenThrow(new OBEventNotificationException(EventNotificationConstants. - ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS)); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionRetrieveResponse = defaultEventSubscriptionServiceHandler - .getAllEventSubscriptions(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertEquals(eventSubscriptionRetrieveResponse.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR_500); - } - - @Test - public void testGetEventSubscriptionsByEventType() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.getEventSubscriptionsByClientIdAndEventType(Mockito.anyString())) - .thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscriptions()); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionRetrieveResponse = defaultEventSubscriptionServiceHandler - .getEventSubscriptionsByEventType(EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(eventSubscriptionRetrieveResponse.getStatus(), HttpStatus.OK_200); - } - - @Test - public void testGetEventSubscriptionsByEventTypeServiceError() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.getEventSubscriptionsByClientIdAndEventType(Mockito.anyString())) - .thenThrow(new OBEventNotificationException(EventNotificationConstants. - ERROR_RETRIEVING_EVENT_SUBSCRIPTIONS)); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionRetrieveResponse = defaultEventSubscriptionServiceHandler - .getEventSubscriptionsByEventType(EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(eventSubscriptionRetrieveResponse.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR_500); - } - - @Test - public void testUpdateEventSubscription() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.updateEventSubscription(Mockito.anyObject())) - .thenReturn(true); - Mockito.when(eventSubscriptionService.getEventSubscriptionBySubscriptionId(Mockito.anyObject())) - .thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscription()); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionUpdateResponse = defaultEventSubscriptionServiceHandler - .updateEventSubscription(EventNotificationTestUtils.getSampleEventSubscriptionUpdateDTO()); - - Assert.assertEquals(eventSubscriptionUpdateResponse.getStatus(), HttpStatus.OK_200); - } - - @Test - public void testUpdateEventSubscriptionServiceError() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.updateEventSubscription(Mockito.anyObject())) - .thenReturn(true); - Mockito.when(eventSubscriptionService.getEventSubscriptionBySubscriptionId(Mockito.anyObject())) - .thenThrow(new OBEventNotificationException(EventNotificationConstants. - ERROR_UPDATING_EVENT_SUBSCRIPTION)); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionUpdateResponse = defaultEventSubscriptionServiceHandler - .updateEventSubscription(EventNotificationTestUtils.getSampleEventSubscriptionUpdateDTO()); - - Assert.assertEquals(eventSubscriptionUpdateResponse.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR_500); - } - - @Test - public void testDeleteEventSubscription() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.deleteEventSubscription(Mockito.anyObject())) - .thenReturn(true); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionDeletionResponse = defaultEventSubscriptionServiceHandler - .deleteEventSubscription(EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertEquals(eventSubscriptionDeletionResponse.getStatus(), HttpStatus.NO_CONTENT_204); - } - - @Test - public void testDeleteEventSubscriptionServiceError() throws Exception { - EventSubscriptionService eventSubscriptionService = Mockito.mock(EventSubscriptionService.class); - Mockito.when(eventSubscriptionService.deleteEventSubscription(Mockito.anyObject())) - .thenThrow(new OBEventNotificationException(EventNotificationConstants. - ERROR_DELETING_EVENT_SUBSCRIPTION)); - - defaultEventSubscriptionServiceHandler.setEventSubscriptionService(eventSubscriptionService); - - mockStatic(EventNotificationServiceUtil.class); - doNothing().when(EventNotificationServiceUtil.class, "validateClientId", anyString()); - - EventSubscriptionResponse eventSubscriptionDeletionResponse = defaultEventSubscriptionServiceHandler - .deleteEventSubscription(EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertEquals(eventSubscriptionDeletionResponse.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR_500); - } - - @Test - public void testMapSubscriptionModelToResponseJson() { - - JSONObject eventSubscriptionCreationResponse = defaultEventSubscriptionServiceHandler - .mapSubscriptionModelToResponseJson(EventNotificationTestUtils.getSampleStoredEventSubscription()); - - Assert.assertEquals(eventSubscriptionCreationResponse.get(EventNotificationConstants.SUBSCRIPTION_ID_PARAM), - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - Assert.assertEquals(eventSubscriptionCreationResponse.get(EventNotificationConstants.CALLBACK_URL_PARAM), - EventNotificationTestConstants.SAMPLE_CALLBACK_URL); - Assert.assertEquals(eventSubscriptionCreationResponse.get(EventNotificationConstants.VERSION_PARAM), - EventNotificationTestConstants.SAMPLE_SPEC_VERSION); - Assert.assertNotNull(eventSubscriptionCreationResponse.get(EventNotificationConstants.EVENT_TYPE_PARAM)); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventNotificationPersistenceServiceHandlerTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventNotificationPersistenceServiceHandlerTests.java deleted file mode 100644 index 82a2ea0f..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/handler/EventNotificationPersistenceServiceHandlerTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.handler; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.annotations.Test; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; - -/** - * Test class for EventNotificationPersistenceServiceHandler. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({EventNotificationServiceUtil.class, DefaultEventCreationServiceHandler.class}) -public class EventNotificationPersistenceServiceHandlerTests { - - @Test - public void testPersistRevokeEvent() { - DefaultEventCreationServiceHandler defaultEventCreationServiceHandlerMock = - Mockito.mock(DefaultEventCreationServiceHandler.class); - - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getDefaultEventCreationServiceHandler()) - .thenReturn(defaultEventCreationServiceHandlerMock); - - EventCreationResponse eventCreationResponse = new EventCreationResponse(); - eventCreationResponse.setStatus(EventNotificationConstants.OK); - doReturn(eventCreationResponse).when(defaultEventCreationServiceHandlerMock).publishOBEvent(any()); - - - - EventNotificationPersistenceServiceHandler revokeEventPersistenceServiceHandler = - EventNotificationPersistenceServiceHandler.getInstance(); - - EventCreationResponse response = - revokeEventPersistenceServiceHandler.persistRevokeEvent( - EventNotificationTestConstants.SAMPLE_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, any()); - - Assert.assertEquals(response.getStatus(), EventNotificationConstants.OK); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/DefaultRealtimeEventNotificationPayloadGeneratorTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/DefaultRealtimeEventNotificationPayloadGeneratorTests.java deleted file mode 100644 index af4ac605..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/DefaultRealtimeEventNotificationPayloadGeneratorTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.HashMap; - -/** - * This class defines unit tests for DefaultRealtimeEventNotificationPayloadGenerator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -public class DefaultRealtimeEventNotificationPayloadGeneratorTests { - - @Test - public void testGetRealtimeEventNotificationPayload() { - NotificationDTO notificationDTO = new NotificationDTO(); - notificationDTO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - notificationDTO.setNotificationId(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - - RealtimeEventNotificationRequestGenerator defaultRealtimeEventNotificationRequestGenerator - = new DefaultRealtimeEventNotificationRequestGenerator(); - String result = defaultRealtimeEventNotificationRequestGenerator - .getRealtimeEventNotificationPayload(notificationDTO, - EventNotificationTestConstants.SAMPLE_SET); - - Assert.assertEquals(result, EventNotificationTestConstants.SAMPLE_NOTIFICATION_PAYLOAD); - } - - @Test - public void testGetAdditionalHeaders() { - RealtimeEventNotificationRequestGenerator defaultRealtimeEventNotificationRequestGenerator - = new DefaultRealtimeEventNotificationRequestGenerator(); - HashMap result = (HashMap) - defaultRealtimeEventNotificationRequestGenerator.getAdditionalHeaders(); - - Assert.assertEquals(0, result.size()); - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/EventNotificationProducerServiceTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/EventNotificationProducerServiceTests.java deleted file mode 100644 index 7f58cdf0..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/EventNotificationProducerServiceTests.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationDataHolder; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.model.RealtimeEventNotification; -import com.wso2.openbanking.accelerator.event.notifications.service.service.DefaultEventNotificationGenerator; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import net.minidev.json.parser.ParseException; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.concurrent.LinkedBlockingQueue; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; - -/** - * Test class for EventNotificationProducerService. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({EventNotificationDataHolder.class, DefaultEventNotificationGenerator.class, - EventNotificationServiceUtil.class, DefaultRealtimeEventNotificationRequestGenerator.class}) -public class EventNotificationProducerServiceTests extends PowerMockTestCase { - @Test - public void testRun() throws OBEventNotificationException, ParseException, InterruptedException { - LinkedBlockingQueue eventQueue = new LinkedBlockingQueue<>(); - String callbackUrl = EventNotificationTestConstants.SAMPLE_CALLBACK_URL; - - DefaultEventNotificationGenerator mockedEventNotificationGenerator = - Mockito.mock(DefaultEventNotificationGenerator.class); - DefaultRealtimeEventNotificationRequestGenerator mockedRealtimeEventNotificationRequestGenerator = - Mockito.mock(DefaultRealtimeEventNotificationRequestGenerator.class); - - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getEventNotificationGenerator()).thenReturn( - mockedEventNotificationGenerator); - PowerMockito.when(EventNotificationServiceUtil.getRealtimeEventNotificationRequestGenerator()) - .thenReturn(mockedRealtimeEventNotificationRequestGenerator); - PowerMockito.when(EventNotificationServiceUtil.getCallbackURL(Mockito.any())).thenReturn(callbackUrl); - - EventNotificationDataHolder eventNotificationDataHolderMock = Mockito.mock(EventNotificationDataHolder.class); - Mockito.when(eventNotificationDataHolderMock.getRealtimeEventNotificationQueue()).thenReturn(eventQueue); - PowerMockito.mockStatic(EventNotificationDataHolder.class); - PowerMockito.when(EventNotificationDataHolder.getInstance()).thenReturn(eventNotificationDataHolderMock); - - NotificationDTO notificationDTO = new NotificationDTO(); - notificationDTO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - notificationDTO.setNotificationId(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - Notification testNotification = new Notification(); - String testEventSET = EventNotificationTestConstants.SAMPLE_SET; - String testPayload = EventNotificationTestConstants.SAMPLE_NOTIFICATION_PAYLOAD; - - doReturn(testNotification).when(mockedEventNotificationGenerator).generateEventNotificationBody(any(), any()); - doReturn(testEventSET).when(mockedEventNotificationGenerator).generateEventNotification(any()); - doReturn(testPayload).when(mockedRealtimeEventNotificationRequestGenerator) - .getRealtimeEventNotificationPayload(any(), any()); - - EventNotificationProducerService eventNotificationProducerService = - new EventNotificationProducerService(notificationDTO, - EventNotificationTestUtils.getSampleNotificationsList()); - - new Thread(eventNotificationProducerService).start(); - - Thread.sleep(5000); - RealtimeEventNotification notification = eventQueue.take(); - - Assert.assertEquals(notification.getJsonPayload(), testPayload); - Assert.assertEquals(notification.getNotificationId(), EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - Assert.assertEquals(notification.getCallbackUrl(), callbackUrl); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationLoaderServiceTest.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationLoaderServiceTest.java deleted file mode 100644 index b0a2595e..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationLoaderServiceTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.internal.EventNotificationDataHolder; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPollingStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.realtime.model.RealtimeEventNotification; -import com.wso2.openbanking.accelerator.event.notifications.service.service.DefaultEventNotificationGenerator; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.LinkedBlockingQueue; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; - -/** - * Test class for RealtimeEventNotificationLoaderService. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({EventNotificationDataHolder.class, DefaultEventNotificationGenerator.class, - EventNotificationServiceUtil.class, EventPollingStoreInitializer.class, AggregatedPollingDAOImpl.class, - DefaultRealtimeEventNotificationRequestGenerator.class}) -public class RealtimeEventNotificationLoaderServiceTest extends PowerMockTestCase { - @Test - public void testRun() throws OBEventNotificationException, InterruptedException { - LinkedBlockingQueue eventQueue = new LinkedBlockingQueue<>(); - - DefaultEventNotificationGenerator mockedEventNotificationGenerator = - Mockito.mock(DefaultEventNotificationGenerator.class); - DefaultRealtimeEventNotificationRequestGenerator mockedRealtimeEventNotificationRequestGenerator = - Mockito.mock(DefaultRealtimeEventNotificationRequestGenerator.class); - - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getEventNotificationGenerator()).thenReturn( - mockedEventNotificationGenerator); - PowerMockito.when(EventNotificationServiceUtil.getRealtimeEventNotificationRequestGenerator()).thenReturn( - mockedRealtimeEventNotificationRequestGenerator); - - EventNotificationDataHolder eventNotificationDataHolderMock = Mockito.mock(EventNotificationDataHolder.class); - Mockito.when(eventNotificationDataHolderMock.getRealtimeEventNotificationQueue()).thenReturn(eventQueue); - PowerMockito.mockStatic(EventNotificationDataHolder.class); - PowerMockito.when(EventNotificationDataHolder.getInstance()).thenReturn(eventNotificationDataHolderMock); - - NotificationDTO notificationDTO1 = new NotificationDTO(); - notificationDTO1.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - notificationDTO1.setNotificationId(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - NotificationDTO notificationDTO2 = new NotificationDTO(); - notificationDTO2.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID_2); - notificationDTO2.setNotificationId(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID_2); - - List notifications = new ArrayList<>(); - notifications.add(notificationDTO1); - notifications.add(notificationDTO2); - - AggregatedPollingDAOImpl mockAggregatedPollingDAOImpl = Mockito.mock(AggregatedPollingDAOImpl.class); - doReturn(notifications).when(mockAggregatedPollingDAOImpl).getNotificationsByStatus( - EventNotificationConstants.OPEN); - PowerMockito.mockStatic(EventPollingStoreInitializer.class); - PowerMockito.when(EventPollingStoreInitializer.getAggregatedPollingDAO()) - .thenReturn(mockAggregatedPollingDAOImpl); - - - Notification testNotification = new Notification(); - String testEventSET = EventNotificationTestConstants.SAMPLE_SET; - String testPayload = - "{\"notificationId\": " + notificationDTO1.getNotificationId() + ", \"SET\": " + testEventSET + "}"; - - doReturn(testNotification).when(mockedEventNotificationGenerator).generateEventNotificationBody(any(), any()); - doReturn(testEventSET).when(mockedEventNotificationGenerator).generateEventNotification(any()); - doReturn(testPayload).when(mockedRealtimeEventNotificationRequestGenerator) - .getRealtimeEventNotificationPayload(any(), any()); - - new Thread(new RealtimeEventNotificationLoaderService()).start(); - - Thread.sleep(5000); - RealtimeEventNotification notification1 = eventQueue.take(); - RealtimeEventNotification notification2 = eventQueue.take(); - - Assert.assertEquals(notification1.getNotificationId(), EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - Assert.assertEquals(notification2.getNotificationId(), EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID_2); - Assert.assertEquals(notification1.getJsonPayload(), testPayload); - Assert.assertEquals(notification2.getJsonPayload(), testPayload); - } - -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationSenderServiceTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationSenderServiceTests.java deleted file mode 100644 index 3c312ad7..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/realtime/service/RealtimeEventNotificationSenderServiceTests.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.realtime.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.HTTPClientUtils; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAOImpl; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPollingStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; - -/** - * Test class for RealtimeEventNotificationSenderService. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class, HTTPClientUtils.class, CloseableHttpClient.class, HttpPost.class, - AggregatedPollingDAOImpl.class, EventPollingStoreInitializer.class, CloseableHttpResponse.class, - StatusLine.class, EventNotificationServiceUtil.class, DefaultRealtimeEventNotificationRequestGenerator.class}) -public class RealtimeEventNotificationSenderServiceTests extends PowerMockTestCase { - private static final int MAX_RETRIES = 1; - private static final int INITIAL_BACKOFF_TIME_IN_SECONDS = 1; - private static final String BACKOFF_FUNCTION = "EX"; - private static final int CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS = 30; - private static final int TIMEOUT_IN_SECONDS = 1; - - @BeforeClass - public void initTest() { - OpenBankingConfigParser configParser = Mockito.mock(OpenBankingConfigParser.class); - Mockito.when(configParser.getRealtimeEventNotificationMaxRetries()).thenReturn(MAX_RETRIES); - Mockito.when(configParser.getRealtimeEventNotificationInitialBackoffTimeInSeconds()) - .thenReturn(INITIAL_BACKOFF_TIME_IN_SECONDS); - Mockito.when(configParser.getRealtimeEventNotificationBackoffFunction()).thenReturn(BACKOFF_FUNCTION); - Mockito.when(configParser.getRealtimeEventNotificationCircuitBreakerOpenTimeoutInSeconds()) - .thenReturn(CIRCUIT_BREAKER_OPEN_TIMEOUT_IN_SECONDS); - Mockito.when(configParser.getRealtimeEventNotificationTimeoutInSeconds()).thenReturn(TIMEOUT_IN_SECONDS); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(configParser); - } - - @Test - public void testRunBad() throws OpenBankingException, IOException { - AggregatedPollingDAOImpl aggregatedPollingDAOMock = Mockito.mock(AggregatedPollingDAOImpl.class); - Mockito.when(aggregatedPollingDAOMock.updateNotificationStatusById(EventNotificationTestConstants - .SAMPLE_NOTIFICATION_ID, EventNotificationConstants.ACK)).thenReturn(true); - PowerMockito.mockStatic(EventPollingStoreInitializer.class); - PowerMockito.when(EventPollingStoreInitializer.getAggregatedPollingDAO()).thenReturn(aggregatedPollingDAOMock); - - RealtimeEventNotificationRequestGenerator mockRequestGenerator = - Mockito.mock(DefaultRealtimeEventNotificationRequestGenerator.class); - Map mockHeaders = new HashMap<>(); - Mockito.when(mockRequestGenerator.getAdditionalHeaders()).thenReturn(mockHeaders); - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getRealtimeEventNotificationRequestGenerator()) - .thenReturn(mockRequestGenerator); - - CloseableHttpResponse mockResponse = Mockito.mock(CloseableHttpResponse.class); - StatusLine mockSL = Mockito.mock(StatusLine.class); - Mockito.when(mockResponse.getStatusLine()).thenReturn(mockSL); - Mockito.when(mockSL.getStatusCode()).thenReturn(HttpStatus.SC_BAD_REQUEST); - - CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class); - doReturn(mockResponse).when(httpClientMock).execute(any()); - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getRealtimeEventNotificationHttpsClient()).thenReturn(httpClientMock); - - new Thread(new RealtimeEventNotificationSenderService(EventNotificationTestConstants.SAMPLE_CALLBACK_URL, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_PAYLOAD, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID)).start(); - } - - @Test - public void testRun() throws OpenBankingException, IOException { - AggregatedPollingDAOImpl aggregatedPollingDAOMock = Mockito.mock(AggregatedPollingDAOImpl.class); - Mockito.when(aggregatedPollingDAOMock.updateNotificationStatusById(EventNotificationTestConstants - .SAMPLE_NOTIFICATION_ID, EventNotificationConstants.ACK)).thenReturn(true); - PowerMockito.mockStatic(EventPollingStoreInitializer.class); - PowerMockito.when(EventPollingStoreInitializer.getAggregatedPollingDAO()).thenReturn(aggregatedPollingDAOMock); - - RealtimeEventNotificationRequestGenerator mockRequestGenerator = - Mockito.mock(DefaultRealtimeEventNotificationRequestGenerator.class); - Map mockHeaders = new HashMap<>(); - Mockito.when(mockRequestGenerator.getAdditionalHeaders()).thenReturn(mockHeaders); - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getRealtimeEventNotificationRequestGenerator()) - .thenReturn(mockRequestGenerator); - - CloseableHttpResponse mockResponse = Mockito.mock(CloseableHttpResponse.class); - StatusLine mockSL = Mockito.mock(StatusLine.class); - Mockito.when(mockResponse.getStatusLine()).thenReturn(mockSL); - Mockito.when(mockSL.getStatusCode()).thenReturn(HttpStatus.SC_OK); - - CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class); - doReturn(mockResponse).when(httpClientMock).execute(any()); - PowerMockito.mockStatic(HTTPClientUtils.class); - PowerMockito.when(HTTPClientUtils.getRealtimeEventNotificationHttpsClient()).thenReturn(httpClientMock); - - new Thread(new RealtimeEventNotificationSenderService(EventNotificationTestConstants.SAMPLE_CALLBACK_URL, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_PAYLOAD, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID)).start(); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/DefaultEventNotificationGeneratorTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/DefaultEventNotificationGeneratorTests.java deleted file mode 100644 index ace067c6..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/DefaultEventNotificationGeneratorTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.Notification; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import net.minidev.json.parser.ParseException; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -/** - * Test class for DefaultEventNotificationGenerator. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({OpenBankingConfigParser.class}) -public class DefaultEventNotificationGeneratorTests { - - @BeforeMethod - public void mock() { - - EventNotificationTestUtils.mockConfigParser(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void testGenerateEventNotificationBody() throws ParseException, OBEventNotificationException { - - NotificationDTO notificationDAO = new NotificationDTO(); - notificationDAO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - notificationDAO.setNotificationId(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - DefaultEventNotificationGenerator defaultEventNotificationGenerator = new DefaultEventNotificationGenerator(); - - Notification notification = defaultEventNotificationGenerator.generateEventNotificationBody(notificationDAO, - EventNotificationTestUtils.getSampleNotificationsList()); - - Assert.assertEquals(notification.getAud(), EventNotificationTestConstants.SAMPLE_CLIENT_ID); - Assert.assertEquals(notification.getJti(), EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - Assert.assertNotNull(notification.getEvents().get(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventCreationServiceTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventCreationServiceTests.java deleted file mode 100644 index 0b36d156..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventCreationServiceTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventPublisherDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPublisherStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.sql.Connection; - -import static org.mockito.Matchers.anyObject; -import static org.powermock.api.mockito.PowerMockito.when; -/** - * Tests for Default event notification validations. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({DatabaseUtil.class, EventPublisherStoreInitializer.class, OpenBankingConfigParser.class}) -public class EventCreationServiceTests extends PowerMockTestCase { - - private static Connection mockedConnection; - - private static EventPublisherDAO mockedEventPublisherDAO; - - @BeforeClass - public void initTest() throws Exception { - - mockedConnection = Mockito.mock(Connection.class); - } - - @BeforeMethod - public void mock() throws ConsentManagementException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - } - - @Test - public void testPublishOBEventNotification() throws OBEventNotificationException { - - mockedEventPublisherDAO = Mockito.mock(EventPublisherDAO.class); - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Mockito.when(openBankingConfigParserMock.isRealtimeEventNotificationEnabled()).thenReturn(false); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - PowerMockito.mockStatic(EventPublisherStoreInitializer.class); - PowerMockito.when(EventPublisherStoreInitializer.getEventCreationDao()).thenReturn( - mockedEventPublisherDAO); - when(mockedEventPublisherDAO.persistEventNotification(anyObject(), anyObject(), anyObject())).thenReturn( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - EventCreationService eventCreationService = new EventCreationService(); - String notificationId = eventCreationService.publishOBEventNotification( - EventNotificationTestUtils.getNotificationCreationDTO()); - - Assert.assertEquals(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID, notificationId); - } - - @Test(expectedExceptions = OBEventNotificationException.class) - public void testEventPublisherException() throws OBEventNotificationException { - - mockedEventPublisherDAO = Mockito.mock(EventPublisherDAO.class); - PowerMockito.mockStatic(EventPublisherStoreInitializer.class); - PowerMockito.when(EventPublisherStoreInitializer.getEventCreationDao()).thenReturn( - mockedEventPublisherDAO); - when(mockedEventPublisherDAO.persistEventNotification(anyObject(), anyObject(), anyObject())).thenThrow( - OBEventNotificationException.class); - - EventCreationService eventCreationService = new EventCreationService(); - String notificationId = eventCreationService.publishOBEventNotification( - EventNotificationTestUtils.getNotificationCreationDTO()); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventPollingServiceTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventPollingServiceTests.java deleted file mode 100644 index 0dc4f394..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventPollingServiceTests.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.AggregatedPollingDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.AggregatedPollingResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventPollingStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.sql.Connection; -/** - * Test class for EventPollingService. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({DatabaseUtil.class, EventPollingStoreInitializer.class, EventNotificationServiceUtil.class, - OpenBankingConfigParser.class}) -public class EventPollingServiceTests extends PowerMockTestCase { - private static Connection mockedConnection; - private static AggregatedPollingDAO mockedAggregatedPollingDAO; - private static EventNotificationGenerator mockedEventNotificationGenerator; - - @BeforeClass - public void initTest() throws Exception { - - mockedConnection = Mockito.mock(Connection.class); - } - - @BeforeMethod - public void mock() throws ConsentManagementException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - EventNotificationTestUtils.mockConfigParser(); - } - - @Test - public void testPollEventsNoNotifications() throws OBEventNotificationException { - - mockedAggregatedPollingDAO = Mockito.mock(AggregatedPollingDAO.class); - mockedEventNotificationGenerator = Mockito.mock(EventNotificationGenerator.class); - - PowerMockito.mockStatic(EventPollingStoreInitializer.class); - PowerMockito.when(EventPollingStoreInitializer.getAggregatedPollingDAO()).thenReturn( - mockedAggregatedPollingDAO); - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getEventNotificationGenerator()).thenReturn( - mockedEventNotificationGenerator); - PowerMockito.when(mockedAggregatedPollingDAO.getNotificationStatus(Mockito.anyString())).thenReturn(true); - - EventPollingService eventPollingService = new EventPollingService(); - - AggregatedPollingResponse aggregatedPollingResponse = eventPollingService.pollEvents( - EventNotificationTestUtils.getEventPollingDTO()); - - Assert.assertEquals(aggregatedPollingResponse.getStatus(), EventNotificationConstants.NOT_FOUND); - } - - @Test - public void testPollNotifications() throws OBEventNotificationException { - - mockedAggregatedPollingDAO = Mockito.mock(AggregatedPollingDAO.class); - mockedEventNotificationGenerator = Mockito.mock(EventNotificationGenerator.class); - - PowerMockito.mockStatic(EventPollingStoreInitializer.class); - PowerMockito.when(EventPollingStoreInitializer.getAggregatedPollingDAO()).thenReturn( - mockedAggregatedPollingDAO); - PowerMockito.mockStatic(EventNotificationServiceUtil.class); - PowerMockito.when(EventNotificationServiceUtil.getEventNotificationGenerator()).thenReturn( - mockedEventNotificationGenerator); - PowerMockito.when(mockedAggregatedPollingDAO.getNotificationsByClientIdAndStatus(Mockito.anyString(), - Mockito.anyString(), Mockito.anyInt())).thenReturn( - EventNotificationTestUtils.getSampleSavedTestNotification()); - PowerMockito.when(mockedAggregatedPollingDAO.getNotificationStatus(Mockito.anyString())).thenReturn(true); - - EventPollingService eventPollingService = new EventPollingService(); - - AggregatedPollingResponse aggregatedPollingResponse = eventPollingService.pollEvents( - EventNotificationTestUtils.getEventPollingDTO()); - - Assert.assertEquals(aggregatedPollingResponse.getStatus(), EventNotificationConstants.OK); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventSubscriptionServiceTests.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventSubscriptionServiceTests.java deleted file mode 100644 index d8f906df..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/service/EventSubscriptionServiceTests.java +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dao.EventSubscriptionDAO; -import com.wso2.openbanking.accelerator.event.notifications.service.exceptions.OBEventNotificationException; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.persistence.EventSubscriptionStoreInitializer; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import com.wso2.openbanking.accelerator.event.notifications.service.utils.EventNotificationTestUtils; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.util.List; - -/** - * This is to test the Event Subscription Service. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({DatabaseUtil.class, EventSubscriptionStoreInitializer.class, EventNotificationServiceUtil.class, - OpenBankingConfigParser.class}) -public class EventSubscriptionServiceTests extends PowerMockTestCase { - private static Connection mockedConnection; - private static EventSubscriptionDAO mockedEventSubscriptionDAO; - - @BeforeClass - public void initTest() { - - mockedConnection = Mockito.mock(Connection.class); - } - - @BeforeMethod - public void mock() throws ConsentManagementException, OBEventNotificationException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(mockedConnection); - EventNotificationTestUtils.mockConfigParser(); - - mockedEventSubscriptionDAO = Mockito.mock(EventSubscriptionDAO.class); - - PowerMockito.mockStatic(EventSubscriptionStoreInitializer.class); - PowerMockito.when(EventSubscriptionStoreInitializer.getEventSubscriptionDao()). - thenReturn(mockedEventSubscriptionDAO); - } - - @Test - public void testCreateEventSubscription() throws OBEventNotificationException { - PowerMockito.when(mockedEventSubscriptionDAO.storeEventSubscription(Mockito.anyObject(), Mockito.any())). - thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscription()); - PowerMockito.when(mockedEventSubscriptionDAO.storeSubscribedEventTypes(Mockito.anyObject(), Mockito.anyString(), - Mockito.any())).thenReturn(EventNotificationTestUtils.getSampleStoredEventTypes()); - - EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - EventSubscription sampleEventSubscription = EventNotificationTestUtils.getSampleStoredEventSubscription(); - - EventSubscription result = eventSubscriptionService.createEventSubscription( - EventNotificationTestUtils.getSampleEventSubscription()); - - Assert.assertNotNull(sampleEventSubscription.getSubscriptionId()); // Check that subscriptionId is not null - Assert.assertNotNull(sampleEventSubscription.getTimeStamp()); // Check that timeStamp is not null - Assert.assertEquals(EventNotificationConstants.CREATED, result.getStatus()); - Assert.assertNotNull(result.getEventTypes()); - Assert.assertTrue(result.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_1)); - Assert.assertTrue(result.getEventTypes().contains(EventNotificationTestConstants. - SAMPLE_NOTIFICATION_EVENT_TYPE_2)); - - } - - @Test - public void testGetEventSubscriptionBySubscriptionId() throws OBEventNotificationException { - PowerMockito.when(mockedEventSubscriptionDAO.getEventSubscriptionBySubscriptionId(Mockito.anyObject(), - Mockito.anyString())).thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscription()); - - EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - - EventSubscription result = eventSubscriptionService. - getEventSubscriptionBySubscriptionId(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertNotNull(result); - } - - @Test - public void testGetEventSubscriptionsByClientId() throws OBEventNotificationException { - PowerMockito.when(mockedEventSubscriptionDAO.getEventSubscriptionsByClientId(Mockito.anyObject(), - Mockito.anyString())).thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscriptions()); - - EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - - List result = eventSubscriptionService. - getEventSubscriptionsByClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - - Assert.assertEquals(result.size(), 2); - } - - @Test - public void testGetEventSubscriptionsByClientIdAndEventType() throws OBEventNotificationException { - PowerMockito.when(mockedEventSubscriptionDAO.getEventSubscriptionsByEventType(Mockito.anyObject(), - Mockito.anyString())). - thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscriptions()); - - EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - - List result = eventSubscriptionService. - getEventSubscriptionsByClientIdAndEventType( - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - - Assert.assertEquals(2, result.size()); - } - - @Test - public void testUpdateEventSubscription() throws OBEventNotificationException { - PowerMockito.when(mockedEventSubscriptionDAO.getEventSubscriptionBySubscriptionId(Mockito.anyObject(), - Mockito.anyString())).thenReturn(EventNotificationTestUtils.getSampleStoredEventSubscription()); - PowerMockito.when(mockedEventSubscriptionDAO.updateEventSubscription(Mockito.anyObject(), Mockito.any())). - thenReturn(true); - PowerMockito.when(mockedEventSubscriptionDAO.deleteSubscribedEventTypes(Mockito.anyObject(), - Mockito.anyString())).thenReturn(true); - PowerMockito.when(mockedEventSubscriptionDAO.storeSubscribedEventTypes(Mockito.anyObject(), Mockito.anyString(), - Mockito.any())).thenReturn(EventNotificationTestUtils.getSampleStoredEventTypes()); - - EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - - Boolean result = eventSubscriptionService. - updateEventSubscription(EventNotificationTestUtils.getSampleEventSubscriptionToBeUpdated()); - - Assert.assertTrue(result); - } - - @Test - public void testDeleteEventSubscription() throws OBEventNotificationException { - PowerMockito.when(mockedEventSubscriptionDAO.deleteEventSubscription(Mockito.anyObject(), Mockito.anyString())). - thenReturn(true); - - EventSubscriptionService eventSubscriptionService = new EventSubscriptionService(); - - Boolean result = eventSubscriptionService. - deleteEventSubscription(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - - Assert.assertTrue(result); - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/utils/EventNotificationTestUtils.java b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/utils/EventNotificationTestUtils.java deleted file mode 100644 index 2878f1a8..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/java/com/wso2/openbanking/accelerator/event/notifications/service/utils/EventNotificationTestUtils.java +++ /dev/null @@ -1,275 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.service.utils; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationTestConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventPollingDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventSubscriptionDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationCreationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.model.AggregatedPollingResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.model.EventSubscription; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationError; -import com.wso2.openbanking.accelerator.event.notifications.service.model.NotificationEvent; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.ParseException; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * EventNotification Test Utils class. - */ -public class EventNotificationTestUtils { - - public static List getSampleSavedTestNotification() { - - List notificationList = new ArrayList<>(); - notificationList.add(getSampleNotificationDTO()); - - return notificationList; - } - public static NotificationDTO getSampleNotificationDTO() { - - NotificationDTO notificationDTO = new NotificationDTO(); - notificationDTO.setResourceId(EventNotificationTestConstants.SAMPLE_RESOURCE_ID); - notificationDTO.setNotificationId(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - notificationDTO.setStatus(EventNotificationConstants.OPEN); - notificationDTO.setUpdatedTimeStamp(EventNotificationTestConstants.UPDATED_TIME); - - return notificationDTO; - } - public static List getSampleNotificationsList() throws ParseException { - List eventsList = new ArrayList(); - NotificationEvent notificationEvent = new NotificationEvent(); - notificationEvent.setEventType(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - notificationEvent.setEventInformation(getSampleEventInformation()); - eventsList.add(notificationEvent); - - return eventsList; - } - - public static JSONObject getEventRequest() { - - JSONObject sampleEventPollingRequest = new JSONObject(); - sampleEventPollingRequest.put(EventNotificationConstants.X_WSO2_CLIENT_ID, - EventNotificationTestConstants.SAMPLE_CLIENT_ID); - sampleEventPollingRequest.put(EventNotificationConstants.RETURN_IMMEDIATELY, true); - sampleEventPollingRequest.put(EventNotificationConstants.MAX_EVENTS, 5); - sampleEventPollingRequest.put(EventNotificationConstants.ACK, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - return sampleEventPollingRequest; - } - - public static JSONObject getSampleEventInformation() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("key1", "value1"); - jsonObject.put("key2", "value2"); - jsonObject.put("key3", "value3"); - - return jsonObject; - } - - public static void mockConfigParser() { - - OpenBankingConfigParser openBankingConfigParserMock = Mockito.mock(OpenBankingConfigParser.class); - Map configuration = new HashMap<>(); - configuration.put(OpenBankingConstants.TOKEN_ISSUER, "www.wso2.com"); - configuration.put(EventNotificationConstants.MAX_EVENTS, 5); - Mockito.when(openBankingConfigParserMock.getConfiguration()).thenReturn(configuration); - PowerMockito.mockStatic(OpenBankingConfigParser.class); - PowerMockito.when(OpenBankingConfigParser.getInstance()).thenReturn(openBankingConfigParserMock); - - } - - public static AggregatedPollingResponse getAggregatedPollingResponse() { - - Map sets = new HashMap<>(); - sets.put("4f312007-4d3f-40e4-a525-0f6ee8bb54d9", EventNotificationTestConstants.SAMPLE_SET); - AggregatedPollingResponse aggregatedPollingResponse = new AggregatedPollingResponse(); - aggregatedPollingResponse.setCount(0); - aggregatedPollingResponse.setStatus("OK"); - aggregatedPollingResponse.setSets(sets); - return aggregatedPollingResponse; - } - - public static JSONObject getPollingError() { - - JSONObject errorObj = new JSONObject(); - errorObj.put("65ac7453-13b0-4d2f-9946-dff6e6089a4f", errorInfo()); - errorObj.put("78ac7453-13b0-4d2f-9946-dff6e608345f", errorInfo()); - return errorObj; - } - - public static JSONObject errorInfo() { - - JSONObject errorInfo = new JSONObject(); - errorInfo.put("err", "authentication_failed"); - errorInfo.put("description", "The SET could not be authenticated"); - return errorInfo; - } - - public static NotificationCreationDTO getNotificationCreationDTO() { - - NotificationCreationDTO notificationCreationDTO = new NotificationCreationDTO(); - notificationCreationDTO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - notificationCreationDTO.setEventPayload(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1, - getSampleEventInformation()); - notificationCreationDTO.setResourceId(EventNotificationTestConstants.SAMPLE_RESOURCE_ID); - - return notificationCreationDTO; - } - - public static NotificationError getNotificationError() { - - NotificationError notificationError = new NotificationError(); - notificationError.setNotificationId("d3fcb77a-274d-4851-b392-a2c0af312fd8"); - notificationError.setErrorCode(EventNotificationTestConstants.ERROR_CODE); - notificationError.setErrorDescription(EventNotificationTestConstants.ERROR_DESCRIPTION); - - return notificationError; - } - - public static EventPollingDTO getEventPollingDTO() { - - EventPollingDTO eventPollingDTO = new EventPollingDTO(); - eventPollingDTO.setMaxEvents(3); - eventPollingDTO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventPollingDTO.setErrors("d3fcb77a-274d-4851-b392-a2c0af312fd8", getNotificationError()); - eventPollingDTO.setAck(EventNotificationTestConstants.SAMPLE_NOTIFICATION_ID); - - return eventPollingDTO; - } - - public static ArrayList getSampleEventList() throws ParseException { - ArrayList eventsList = new ArrayList(); - NotificationEvent notificationEvent = new NotificationEvent(); - notificationEvent.setEventType(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPE_1); - notificationEvent.setEventInformation(getSampleEventInformation()); - eventsList.add(notificationEvent); - - return eventsList; - } - - public static EventSubscription getSampleEventSubscription() { - - EventSubscription eventSubscription = new EventSubscription(); - eventSubscription.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventSubscription.setCallbackUrl(EventNotificationTestConstants.SAMPLE_CALLBACK_URL); - eventSubscription.setSpecVersion(EventNotificationTestConstants.SAMPLE_SPEC_VERSION); - eventSubscription.setEventTypes(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - return eventSubscription; - } - - public static EventSubscription getSampleStoredEventSubscription() { - EventSubscription eventSubscription = new EventSubscription(); - eventSubscription.setSubscriptionId(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - eventSubscription.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventSubscription.setCallbackUrl(EventNotificationTestConstants.SAMPLE_CALLBACK_URL); - eventSubscription.setSpecVersion(EventNotificationTestConstants.SAMPLE_SPEC_VERSION); - eventSubscription.setTimeStamp(1626480000L); - eventSubscription.setEventTypes(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - eventSubscription.setStatus("CREATED"); - - JSONObject requestData = new JSONObject(); - requestData.put(EventNotificationConstants.SUBSCRIPTION_ID_PARAM, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - requestData.put("clientId", EventNotificationTestConstants.SAMPLE_CLIENT_ID); - requestData.put(EventNotificationConstants.CALLBACK_URL_PARAM, - EventNotificationTestConstants.SAMPLE_CALLBACK_URL); - requestData.put(EventNotificationConstants.VERSION_PARAM, EventNotificationTestConstants.SAMPLE_SPEC_VERSION); - requestData.put(EventNotificationConstants.EVENT_TYPE_PARAM, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - requestData.put("timeStamp", 1626480000L); - requestData.put("status", "CREATED"); - eventSubscription.setRequestData(requestData.toString()); - return eventSubscription; - } - - public static EventSubscription getSampleStoredEventSubscription2() { - EventSubscription eventSubscription = new EventSubscription(); - eventSubscription.setSubscriptionId(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_2); - eventSubscription.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventSubscription.setCallbackUrl(EventNotificationTestConstants.SAMPLE_CALLBACK_URL); - eventSubscription.setSpecVersion(EventNotificationTestConstants.SAMPLE_SPEC_VERSION); - eventSubscription.setEventTypes(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - eventSubscription.setStatus("CREATED"); - return eventSubscription; - } - - public static List getSampleStoredEventSubscriptions() { - List eventSubscriptions = new ArrayList<>(); - eventSubscriptions.add(getSampleStoredEventSubscription()); - eventSubscriptions.add(getSampleStoredEventSubscription2()); - return eventSubscriptions; - } - - public static EventSubscription getSampleEventSubscriptionToBeUpdated() { - EventSubscription eventSubscription = new EventSubscription(); - eventSubscription.setSubscriptionId(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - eventSubscription.setCallbackUrl("test.com"); - eventSubscription.setEventTypes(EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - - JSONObject requestData = new JSONObject(); - requestData.put(EventNotificationConstants.SUBSCRIPTION_ID_PARAM, - EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - requestData.put(EventNotificationConstants.CALLBACK_URL_PARAM, "test.com"); - requestData.put(EventNotificationConstants.EVENT_TYPE_PARAM, - EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - eventSubscription.setRequestData(requestData.toString()); - return eventSubscription; - } - - public static List getSampleStoredEventTypes() { - return EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES; - } - - public static EventSubscriptionDTO getSampleEventSubscriptionDTO() { - EventSubscriptionDTO eventSubscriptionDTO = new EventSubscriptionDTO(); - JSONObject request = new JSONObject(); - request.put("callbackUrl", EventNotificationTestConstants.SAMPLE_CALLBACK_URL); - request.put("eventTypes", EventNotificationTestConstants.SAMPLE_NOTIFICATION_EVENT_TYPES); - request.put("version", EventNotificationTestConstants.SAMPLE_SPEC_VERSION); - eventSubscriptionDTO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventSubscriptionDTO.setSubscriptionId(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - eventSubscriptionDTO.setRequestData(request); - return eventSubscriptionDTO; - } - - public static EventSubscriptionDTO getSampleEventSubscriptionUpdateDTO() { - EventSubscriptionDTO eventSubscriptionDTO = new EventSubscriptionDTO(); - List eventTypes = Arrays.asList("event 1", "event 2"); - JSONObject request = new JSONObject(); - request.put("callbackUrl", "updated url"); - request.put("eventTypes", eventTypes); - eventSubscriptionDTO.setClientId(EventNotificationTestConstants.SAMPLE_CLIENT_ID); - eventSubscriptionDTO.setSubscriptionId(EventNotificationTestConstants.SAMPLE_SUBSCRIPTION_ID_1); - eventSubscriptionDTO.setRequestData(request); - return eventSubscriptionDTO; - } -} diff --git a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/resources/testng.xml b/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/resources/testng.xml deleted file mode 100644 index 783c7d6a..00000000 --- a/open-banking-accelerator/components/event-notifications/com.wso2.openbanking.accelerator.event.notifications.service/src/test/resources/testng.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/pom.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/pom.xml deleted file mode 100644 index 8d95e164..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/pom.xml +++ /dev/null @@ -1,189 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.throttler.dao - WSO2 Open Banking - Throttler DAO - WSO2 Open Banking - Throttler DAO Module - jar - - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.testng - testng - - - com.h2database - h2 - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - org.mockito - mockito-all - test - - - org.powermock - powermock-api-mockito - test - - - org.powermock - powermock-module-testng - test - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - target/jacoco.exec - - true - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - **/*Exception.class - **/*Constants.class - **/ThrottleDataModel.class - - **/DataStoreInitializerFactory.class - **/DataStoreInitializer.class - **/OBThrottlerSQLStatements.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.80 - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/OBThrottlerDAO.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/OBThrottlerDAO.java deleted file mode 100644 index e0fb95ed..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/OBThrottlerDAO.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao; - -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataDeletionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataInsertionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataRetrievalException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataUpdationException; -import com.wso2.openbanking.accelerator.throttler.dao.model.ThrottleDataModel; - -import java.sql.Connection; -import java.sql.Timestamp; - -/** - * DAO class for throttle data. - */ -public interface OBThrottlerDAO { - - /** - * Store throttle data. - * - * @param connection connection object - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @param currentTimestamp - current timestamp - * @param unlockTimestamp - unlock timestamp - * @return - ThrottleDataModel - * @throws OBThrottlerDataInsertionException - OBThrottlerDataInsertionException - */ - ThrottleDataModel storeThrottleData(Connection connection, String throttleGroup, String throttleParam, - Timestamp currentTimestamp, Timestamp unlockTimestamp) - throws OBThrottlerDataInsertionException; - - /** - * Update throttle data. - * - * @param connection connection object - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @param currentTimestamp - current timestamp - * @param unlockTimestamp - unlock timestamp - * @param occurrences - number of occurrences of the parameter - * @return - ThrottleDataModel - * @throws OBThrottlerDataUpdationException - OBThrottlerDataUpdationException - */ - ThrottleDataModel updateThrottleData(Connection connection, String throttleGroup, String throttleParam, - Timestamp currentTimestamp, Timestamp unlockTimestamp, int occurrences) - throws OBThrottlerDataUpdationException; - - /** - * Retrieve throttle data. - * - * @param connection connection object - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @return - ThrottleDataModel - * @throws OBThrottlerDataRetrievalException - OBThrottlerDataRetrievalException - */ - ThrottleDataModel getThrottleData(Connection connection, String throttleGroup, String throttleParam) - throws OBThrottlerDataRetrievalException; - - /** - * Remove throttle data from database. - * - * @param connection connection object - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @throws OBThrottlerDataDeletionException - OBThrottlerDataDeletionException - */ - void deleteThrottleData(Connection connection, String throttleGroup, String throttleParam) - throws OBThrottlerDataDeletionException; - - /** - * Check if throttle data exists in the database. - * - * @param connection connection object - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @return - boolean - * @throws OBThrottlerDataRetrievalException - OBThrottlerDataRetrievalException - */ - boolean isThrottleDataExists(Connection connection, String throttleGroup, String throttleParam) - throws OBThrottlerDataRetrievalException; -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/constants/OBThrottlerDAOConstants.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/constants/OBThrottlerDAOConstants.java deleted file mode 100644 index f57d3383..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/constants/OBThrottlerDAOConstants.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.constants; - -/** - * This class contains all the constants needed for the ob throttler DAO layer. - */ -public class OBThrottlerDAOConstants { - - public static final int FIRST_OCCURRENCE = 1; - public static final String LAST_UPDATE_TIMESTAMP = "LAST_UPDATE_TIMESTAMP"; - public static final String UNLOCK_TIMESTAMP = "UNLOCK_TIMESTAMP"; - public static final String OCCURRENCES = "OCCURRENCES"; - - public static final String THROTTLE_DATA_STORE_ERROR_MSG = "Error occurred while persisting throttle data in the " + - "database"; - public static final String THROTTLE_DATA_UPDATE_ERROR_MSG = "Error occurred while updating throttle data in the " + - "database"; - public static final String THROTTLE_DATA_RETRIEVE_ERROR_MSG = "Error occurred while retrieving throttle data " + - "from the database"; - public static final String THROTTLE_DATA_RESULT_SET_RETRIEVE_ERROR_MSG = "Error occurred while processing the " + - "throttle data result set retrieval"; - public static final String THROTTLE_DATA_DELETE_ERROR_MSG = "Error occurred while deleting throttle data " + - "from the database"; - public static final String NO_RECORDS_FOUND_ERROR_MSG = "No records are found for the given inputs"; -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataDeletionException.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataDeletionException.java deleted file mode 100644 index 7963f35e..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataDeletionException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OB Throttler data deletion exception class. - */ -public class OBThrottlerDataDeletionException extends OpenBankingException { - - public OBThrottlerDataDeletionException(String message) { - - super(message); - } - - public OBThrottlerDataDeletionException(String message, Throwable e) { - - super(message, e); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataInsertionException.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataInsertionException.java deleted file mode 100644 index 5c15f6b0..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataInsertionException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OB Throttler data insertion exception class. - */ -public class OBThrottlerDataInsertionException extends OpenBankingException { - - public OBThrottlerDataInsertionException(String message) { - - super(message); - } - - public OBThrottlerDataInsertionException(String message, Throwable e) { - - super(message, e); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataRetrievalException.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataRetrievalException.java deleted file mode 100644 index d4f253d2..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataRetrievalException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OB Throttler data retrieval exception class. - */ -public class OBThrottlerDataRetrievalException extends OpenBankingException { - - public OBThrottlerDataRetrievalException(String message) { - - super(message); - } - - public OBThrottlerDataRetrievalException(String message, Throwable e) { - - super(message, e); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataUpdationException.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataUpdationException.java deleted file mode 100644 index a75a41e6..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/exception/OBThrottlerDataUpdationException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * OB Throttler data updation exception class. - */ -public class OBThrottlerDataUpdationException extends OpenBankingException { - - public OBThrottlerDataUpdationException(String message) { - - super(message); - } - - public OBThrottlerDataUpdationException(String message, Throwable e) { - - super(message, e); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/impl/OBThrottlerDAOImpl.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/impl/OBThrottlerDAOImpl.java deleted file mode 100644 index f6782efe..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/impl/OBThrottlerDAOImpl.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.impl; - -import com.wso2.openbanking.accelerator.throttler.dao.OBThrottlerDAO; -import com.wso2.openbanking.accelerator.throttler.dao.constants.OBThrottlerDAOConstants; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataDeletionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataInsertionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataRetrievalException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataUpdationException; -import com.wso2.openbanking.accelerator.throttler.dao.model.ThrottleDataModel; -import com.wso2.openbanking.accelerator.throttler.dao.queries.OBThrottlerSQLStatements; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; - -/** - * Implementation of OBThrottlerDAO. - */ -public class OBThrottlerDAOImpl implements OBThrottlerDAO { - - private static final Log log = LogFactory.getLog(OBThrottlerDAOImpl.class); - private OBThrottlerSQLStatements sqlStatements; - - /** - * Load sql statements specific to database type. - * - * @param sqlStatements -sqlStatements specific to db type - */ - public OBThrottlerDAOImpl(OBThrottlerSQLStatements sqlStatements) { - - this.sqlStatements = sqlStatements; - } - - /** - * {@inheritDoc} - */ - @Override - public ThrottleDataModel storeThrottleData(Connection connection, String throttleGroup, String throttleParam, - Timestamp currentTimestamp, Timestamp unlockTimestamp) - throws OBThrottlerDataInsertionException { - - String storeThrottleDataSql = sqlStatements.storeThrottleData(); - int rowCount; - - //store data - try (PreparedStatement storePreparedStatement = connection.prepareStatement(storeThrottleDataSql)) { - //Set prepared statement parameters - storePreparedStatement.setString(1, throttleGroup); - storePreparedStatement.setString(2, throttleParam); - storePreparedStatement.setTimestamp(3, currentTimestamp); - storePreparedStatement.setTimestamp(4, unlockTimestamp); - storePreparedStatement.setInt(5, OBThrottlerDAOConstants.FIRST_OCCURRENCE); - - rowCount = storePreparedStatement.executeUpdate(); - } catch (SQLException e) { - log.error(OBThrottlerDAOConstants.THROTTLE_DATA_STORE_ERROR_MSG); - throw new OBThrottlerDataInsertionException(OBThrottlerDAOConstants.THROTTLE_DATA_STORE_ERROR_MSG, e); - } - - if (rowCount > 0) { - if (log.isDebugEnabled()) { - log.debug(String.format( - "Stored ThrottleGroup: '%s', ThrottleParam: '%s', CurrentTimestamp: '%s', " + - "UnlockTimestamp: '%s', Occurrences: 1", throttleGroup, throttleParam, - currentTimestamp, unlockTimestamp).replaceAll("[\r\n]", "")); - } - return new ThrottleDataModel(throttleGroup, throttleParam, currentTimestamp, unlockTimestamp, 1); - } else { - throw new OBThrottlerDataInsertionException("Failed to properly persist throttle data in database."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ThrottleDataModel updateThrottleData(Connection connection, String throttleGroup, String throttleParam, - Timestamp currentTimestamp, Timestamp unlockTimestamp, int occurrences) - throws OBThrottlerDataUpdationException { - - String updateThrottleDataSql = sqlStatements.updateThrottleData(); - int rowCount; - - //update database - try (PreparedStatement updatePreparedStatement = connection.prepareStatement(updateThrottleDataSql)) { - //Set prepared statement parameters - updatePreparedStatement.setTimestamp(1, currentTimestamp); - updatePreparedStatement.setTimestamp(2, unlockTimestamp); - updatePreparedStatement.setInt(3, occurrences); - updatePreparedStatement.setString(4, throttleGroup); - updatePreparedStatement.setString(5, throttleParam); - rowCount = updatePreparedStatement.executeUpdate(); - } catch (SQLException e) { - log.error(OBThrottlerDAOConstants.THROTTLE_DATA_UPDATE_ERROR_MSG); - throw new OBThrottlerDataUpdationException(OBThrottlerDAOConstants.THROTTLE_DATA_UPDATE_ERROR_MSG, e); - } - - if (rowCount > 0) { - if (log.isDebugEnabled()) { - log.debug(String.format( - "Updated ThrottleGroup: '%s', ThrottleParam: '%s', CurrentTimestamp: '%s', " + - "UnlockTimestamp: '%s', Occurrences: %d", throttleGroup, throttleParam, - currentTimestamp, unlockTimestamp, occurrences).replaceAll("[\r\n]", "")); - } - return new ThrottleDataModel(throttleGroup, throttleParam, currentTimestamp, unlockTimestamp, occurrences); - } else { - throw new OBThrottlerDataUpdationException("Failed to properly update throttle data in database."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ThrottleDataModel getThrottleData(Connection connection, String throttleGroup, String throttleParam) - throws OBThrottlerDataRetrievalException { - - ThrottleDataModel throttleDataModel; - String sql = sqlStatements.retrieveThrottleData(); - - //retrieve data from database - try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { - preparedStatement.setString(1, throttleGroup); - preparedStatement.setString(2, throttleParam); - try (ResultSet resultSet = preparedStatement.executeQuery()) { - if (resultSet.next()) { - Timestamp lastUpdateTimestamp = resultSet. - getTimestamp(OBThrottlerDAOConstants.LAST_UPDATE_TIMESTAMP); - Timestamp unlockTimestamp = resultSet.getTimestamp(OBThrottlerDAOConstants.UNLOCK_TIMESTAMP); - int occurrences = resultSet.getInt(OBThrottlerDAOConstants.OCCURRENCES); - throttleDataModel = new ThrottleDataModel(throttleGroup, throttleParam, - lastUpdateTimestamp, unlockTimestamp, occurrences); - } else { - log.error(OBThrottlerDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - throw new OBThrottlerDataRetrievalException(OBThrottlerDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - throw new OBThrottlerDataRetrievalException( - OBThrottlerDAOConstants.THROTTLE_DATA_RESULT_SET_RETRIEVE_ERROR_MSG, e); - } - } catch (SQLException e) { - log.error(OBThrottlerDAOConstants.THROTTLE_DATA_RETRIEVE_ERROR_MSG); - throw new OBThrottlerDataRetrievalException(OBThrottlerDAOConstants.THROTTLE_DATA_RETRIEVE_ERROR_MSG, e); - } - return throttleDataModel; - } - - /** - * {@inheritDoc} - */ - @Override - public void deleteThrottleData(Connection connection, String throttleGroup, String throttleParam) - throws OBThrottlerDataDeletionException { - - String removeThrottleDataSql = sqlStatements.removeThrottleData(); - int rowCount; - - //remove data from database - try (PreparedStatement removePreparedStatement = connection.prepareStatement(removeThrottleDataSql)) { - //Set prepared statement parameters - removePreparedStatement.setString(1, throttleGroup); - removePreparedStatement.setString(2, throttleParam); - rowCount = removePreparedStatement.executeUpdate(); - } catch (SQLException e) { - log.error(OBThrottlerDAOConstants.THROTTLE_DATA_DELETE_ERROR_MSG); - throw new OBThrottlerDataDeletionException(OBThrottlerDAOConstants.THROTTLE_DATA_DELETE_ERROR_MSG, e); - } - - if (rowCount > 0) { - if (log.isDebugEnabled()) { - log.debug(String.format("Removed ThrottleGroup: '%s', ThrottleParam: '%s'", - throttleGroup, throttleParam).replaceAll("[\r\n]", "")); - } - } else { - throw new OBThrottlerDataDeletionException(String.format("Throttle data for %s:%s does not exist in " + - "the database", throttleGroup, throttleParam)); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isThrottleDataExists(Connection connection, String throttleGroup, String throttleParam) - throws OBThrottlerDataRetrievalException { - - boolean throttleDataExists = false; - String sql = sqlStatements.isThrottleDataExists(); - - //retrieve data from database - try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { - preparedStatement.setString(1, throttleGroup); - preparedStatement.setString(2, throttleParam); - try (ResultSet resultSet = preparedStatement.executeQuery()) { - if (resultSet.next()) { - throttleDataExists = resultSet.getInt(1) > 0; - } else { - log.error(OBThrottlerDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - throw new OBThrottlerDataRetrievalException(OBThrottlerDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); - } - } catch (SQLException e) { - throw new OBThrottlerDataRetrievalException( - OBThrottlerDAOConstants.THROTTLE_DATA_RESULT_SET_RETRIEVE_ERROR_MSG, e); - } - } catch (SQLException e) { - log.error(OBThrottlerDAOConstants.THROTTLE_DATA_RETRIEVE_ERROR_MSG); - throw new OBThrottlerDataRetrievalException(OBThrottlerDAOConstants.THROTTLE_DATA_RETRIEVE_ERROR_MSG, e); - } - return throttleDataExists; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/model/ThrottleDataModel.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/model/ThrottleDataModel.java deleted file mode 100644 index bc5b810f..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/model/ThrottleDataModel.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.model; - -import java.sql.Timestamp; - -/** - * DTO class for throttle data. - */ -public class ThrottleDataModel { - - private String throttleGroup; - private String throttleParam; - private Timestamp lastUpdateTimestamp; - private Timestamp unlockTimestamp; - private int occurrences; - - /** - * Constructor. - * - * @param throttleGroup - Throttle group - * @param throttleParam - Throttle parameter - * @param lastUpdateTimestamp - Updated timestamp - * @param unlockTimestamp - Parameter unlocking timestamp - * @param occurrences - number of occurrences of the parameter - */ - public ThrottleDataModel(String throttleGroup, String throttleParam, Timestamp lastUpdateTimestamp, - Timestamp unlockTimestamp, int occurrences) { - - this.throttleGroup = throttleGroup; - this.throttleParam = throttleParam; - this.lastUpdateTimestamp = new Timestamp(lastUpdateTimestamp.getTime()); - this.unlockTimestamp = new Timestamp(unlockTimestamp.getTime()); - this.occurrences = occurrences; - } - - public String getThrottleGroup() { - - return throttleGroup; - } - - public void setThrottleGroup(String throttleGroup) { - - this.throttleGroup = throttleGroup; - } - - public String getThrottleParam() { - return throttleParam; - } - - public void setThrottleParam(String throttleParam) { - - this.throttleParam = throttleParam; - } - - public Timestamp getLastUpdateTimestamp() { - - return new Timestamp(lastUpdateTimestamp.getTime()); - } - - public void setLastUpdateTimestamp(Timestamp lastUpdateTimestamp) { - - this.lastUpdateTimestamp = new Timestamp(lastUpdateTimestamp.getTime()); - } - - public Timestamp getUnlockTimestamp() { - - return new Timestamp(unlockTimestamp.getTime()); - } - - public void setUnlockTimestamp(Timestamp unlockTimestamp) { - - this.unlockTimestamp = new Timestamp(unlockTimestamp.getTime()); - } - - public int getOccurrences() { - - return occurrences; - } - - public void setOccurrences(int occurrences) { - - this.occurrences = occurrences; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/persistence/DataStoreInitializer.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/persistence/DataStoreInitializer.java deleted file mode 100644 index ce4c2610..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/persistence/DataStoreInitializer.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.persistence; - -import com.wso2.openbanking.accelerator.common.exception.OBThrottlerException; -import com.wso2.openbanking.accelerator.throttler.dao.OBThrottlerDAO; - -/** - * This class handles throttler DAO layer initiation with the relevant SQL statements per database type. - */ -public class DataStoreInitializer { - - private static OBThrottlerDAO obThrottlerDAO = null; - - /** - * Initialize the DAO according to the database connection. - * - * @return OBThrottlerDAO - * @throws OBThrottlerException - OBThrottlerException - */ - public static synchronized OBThrottlerDAO initializeOBThrottlerDAO() throws OBThrottlerException { - - if (obThrottlerDAO == null) { - DataStoreInitializerFactory dataStoreInitializerFactory = new DataStoreInitializerFactory(); - obThrottlerDAO = dataStoreInitializerFactory.initializeDataStore(); - } - return obThrottlerDAO; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/persistence/DataStoreInitializerFactory.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/persistence/DataStoreInitializerFactory.java deleted file mode 100644 index b60702c3..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/persistence/DataStoreInitializerFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.persistence; - -import com.wso2.openbanking.accelerator.common.exception.OBThrottlerException; -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import com.wso2.openbanking.accelerator.throttler.dao.OBThrottlerDAO; -import com.wso2.openbanking.accelerator.throttler.dao.impl.OBThrottlerDAOImpl; -import com.wso2.openbanking.accelerator.throttler.dao.queries.OBThrottlerSQLStatements; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Data Store Initializer Factory class. - */ -public class DataStoreInitializerFactory { - - private static final Log log = LogFactory.getLog(DataStoreInitializerFactory.class); - - public OBThrottlerDAO initializeDataStore() throws OBThrottlerException { - - try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection()) { - String driverName = connection.getMetaData().getDriverName(); - - if (log.isDebugEnabled()) { - log.debug("Initiated OBThrottlerDAO with " + driverName.replaceAll("[\r\n]", "")); - } - // returning default queries for all database types - return new OBThrottlerDAOImpl(new OBThrottlerSQLStatements()); - - } catch (SQLException e) { - log.error(String.format("Error while getting the database connection. %s", e).replaceAll("[\r\n]", "")); - throw new OBThrottlerException("Error while getting the database connection : ", e); - } - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/queries/OBThrottlerSQLStatements.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/queries/OBThrottlerSQLStatements.java deleted file mode 100644 index 778c50cd..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/java/com/wso2/openbanking/accelerator/throttler/dao/queries/OBThrottlerSQLStatements.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.queries; - -/** - * SQL Statements required for OB Throttler. - */ -public class OBThrottlerSQLStatements { - - public String storeThrottleData() { - - return "INSERT INTO OB_THROTTLE_DATA (THROTTLE_GROUP, THROTTLE_PARAM, LAST_UPDATE_TIMESTAMP, " + - "UNLOCK_TIMESTAMP, OCCURRENCES) VALUES (?, ?, ?, ?, ?)"; - } - - public String updateThrottleData() { - - return "UPDATE OB_THROTTLE_DATA SET LAST_UPDATE_TIMESTAMP = ?, UNLOCK_TIMESTAMP = ?, OCCURRENCES = ? " + - "WHERE THROTTLE_GROUP = ? AND THROTTLE_PARAM = ?"; - } - - public String retrieveThrottleData() { - - return "SELECT * FROM OB_THROTTLE_DATA WHERE THROTTLE_GROUP = ? AND THROTTLE_PARAM = ?"; - } - - public String removeThrottleData() { - - return "DELETE FROM OB_THROTTLE_DATA WHERE THROTTLE_GROUP = ? AND THROTTLE_PARAM = ?"; - } - - public String isThrottleDataExists() { - - return "SELECT COUNT(1) FROM OB_THROTTLE_DATA WHERE THROTTLE_GROUP = ? AND THROTTLE_PARAM = ?"; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index c4f8e532..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/impl/OBThrottlerDAOTests.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/impl/OBThrottlerDAOTests.java deleted file mode 100644 index 802996d6..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/impl/OBThrottlerDAOTests.java +++ /dev/null @@ -1,275 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.impl; - -import com.wso2.openbanking.accelerator.throttler.dao.OBThrottlerDAO; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataDeletionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataInsertionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataRetrievalException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataUpdationException; -import com.wso2.openbanking.accelerator.throttler.dao.model.ThrottleDataModel; -import com.wso2.openbanking.accelerator.throttler.dao.queries.OBThrottlerSQLStatements; -import com.wso2.openbanking.accelerator.throttler.dao.util.OBThrottlerDAOTestData; -import com.wso2.openbanking.accelerator.throttler.dao.util.OBThrottlerDAOUtils; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; - -/** - * Test for Open Banking throttler DAO. - */ -public class OBThrottlerDAOTests { - - private static final String DB_NAME = "OB_THROTTLE_DB"; - - private OBThrottlerDAO obThrottlerDAO; - private Connection mockedConnection; - private PreparedStatement mockedPreparedStatement; - private ResultSet mockedResultSet; - private ThrottleDataModel storedThrottleDataModel; - - @BeforeClass - public void initTest() throws Exception { - - OBThrottlerDAOUtils.initializeDataSource(DB_NAME, OBThrottlerDAOUtils.getFilePath("dbScripts/h2.sql")); - obThrottlerDAO = new OBThrottlerDAOImpl(new OBThrottlerSQLStatements()); - mockedConnection = Mockito.mock(Connection.class); - mockedPreparedStatement = Mockito.mock(PreparedStatement.class); - mockedResultSet = Mockito.mock(ResultSet.class); - } - - @DataProvider(name = "sampleOBThrottleDataProvider") - public Object[][] provideOBThrottleData() { - - /* - * throttleGroup - * throttleParam - * currentTimestamp - * unlockTimestamp - * occurrences - */ - return OBThrottlerDAOTestData.DataProviders.OB_THROTTLER_DATA_HOLDER; - } - - // data insertion tests - @Test(dataProvider = "sampleOBThrottleDataProvider") - public void testStoreThrottleData(String throttleGroup, String throttleParam, Timestamp currentTimestamp, - Timestamp unlockTimestamp, int occurrences) throws Exception { - - try (Connection connection = OBThrottlerDAOUtils.getConnection(DB_NAME)) { - - storedThrottleDataModel = obThrottlerDAO.storeThrottleData(connection, throttleGroup, throttleParam, - currentTimestamp, unlockTimestamp); - } - Assert.assertNotNull(storedThrottleDataModel); - Assert.assertNotNull(storedThrottleDataModel.getThrottleGroup()); - Assert.assertNotNull(storedThrottleDataModel.getThrottleParam()); - Assert.assertNotNull(storedThrottleDataModel.getLastUpdateTimestamp()); - Assert.assertNotNull(storedThrottleDataModel.getUnlockTimestamp()); - } - - @Test(expectedExceptions = OBThrottlerDataInsertionException.class) - public void testStoreThrottleDataInsertionError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - - obThrottlerDAO.storeThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM, OBThrottlerDAOTestData.CURRENT_TIMESTAMP, - OBThrottlerDAOTestData.UNLOCK_TIMESTAMP); - } - - @Test(expectedExceptions = OBThrottlerDataInsertionException.class) - public void testStoreThrottleDataSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - obThrottlerDAO.storeThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM, OBThrottlerDAOTestData.CURRENT_TIMESTAMP, - OBThrottlerDAOTestData.UNLOCK_TIMESTAMP); - } - - //data updation tests - @Test(dataProvider = "sampleOBThrottleDataProvider", dependsOnMethods = "testStoreThrottleData") - public void testUpdateThrottleData(String throttleGroup, String throttleParam, Timestamp currentTimestamp, - Timestamp unlockTimestamp, int occurrences) throws Exception { - - ThrottleDataModel updatedThrottleDataModel; - - try (Connection connection = OBThrottlerDAOUtils.getConnection(DB_NAME)) { - - updatedThrottleDataModel = obThrottlerDAO.updateThrottleData(connection, - storedThrottleDataModel.getThrottleGroup(), storedThrottleDataModel.getThrottleParam(), - storedThrottleDataModel.getLastUpdateTimestamp(), storedThrottleDataModel.getUnlockTimestamp(), - occurrences + 1); - } - Assert.assertEquals(updatedThrottleDataModel.getOccurrences(), 2); - } - - @Test(expectedExceptions = OBThrottlerDataUpdationException.class) - public void testUpdateThrottleDataError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - - obThrottlerDAO.updateThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM, OBThrottlerDAOTestData.CURRENT_TIMESTAMP, - OBThrottlerDAOTestData.UNLOCK_TIMESTAMP, 1); - } - - @Test(expectedExceptions = OBThrottlerDataUpdationException.class) - public void testUpdateThrottleDataSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - obThrottlerDAO.updateThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM, OBThrottlerDAOTestData.CURRENT_TIMESTAMP, - OBThrottlerDAOTestData.UNLOCK_TIMESTAMP, 1); - } - - //data retrieval tests - @Test(dependsOnMethods = "testUpdateThrottleData") - public void testRetrieveThrottleData() throws Exception { - - ThrottleDataModel retrievedThrottleDataModel; - - try (Connection connection = OBThrottlerDAOUtils.getConnection(DB_NAME)) { - retrievedThrottleDataModel = obThrottlerDAO.getThrottleData(connection, - storedThrottleDataModel.getThrottleGroup(), storedThrottleDataModel.getThrottleParam()); - } - - Assert.assertNotNull(retrievedThrottleDataModel); - Assert.assertEquals(retrievedThrottleDataModel.getThrottleGroup(), storedThrottleDataModel.getThrottleGroup()); - Assert.assertNotNull(retrievedThrottleDataModel.getThrottleParam()); - Assert.assertEquals(retrievedThrottleDataModel.getThrottleParam(), storedThrottleDataModel.getThrottleParam()); - Assert.assertNotNull(retrievedThrottleDataModel.getUnlockTimestamp()); - Assert.assertNotNull(retrievedThrottleDataModel.getLastUpdateTimestamp()); - Assert.assertNotNull(retrievedThrottleDataModel.getOccurrences()); - } - - @Test(dependsOnMethods = "testUpdateThrottleData") - public void testRetrieveThrottleDataExists() throws Exception { - - Boolean isRetrieved; - - try (Connection connection = OBThrottlerDAOUtils.getConnection(DB_NAME)) { - isRetrieved = obThrottlerDAO.isThrottleDataExists(connection, - storedThrottleDataModel.getThrottleGroup(), storedThrottleDataModel.getThrottleParam()); - } - - Assert.assertTrue(isRetrieved); - } - - @Test(expectedExceptions = OBThrottlerDataRetrievalException.class) - public void testRetrieveThrottleDataError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - obThrottlerDAO.getThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - @Test (expectedExceptions = OBThrottlerDataRetrievalException.class) - public void testRetrieveThrottleDataResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).next(); - obThrottlerDAO.getThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - @Test(expectedExceptions = OBThrottlerDataRetrievalException.class) - public void testRetrieveThrottleDataExistsError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); - obThrottlerDAO.isThrottleDataExists(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - @Test (expectedExceptions = OBThrottlerDataRetrievalException.class) - public void testRetrieveThrottleDataExistsResultSetError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); - Mockito.doReturn(false).when(mockedResultSet).next(); - obThrottlerDAO.isThrottleDataExists(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - @Test(expectedExceptions = OBThrottlerDataRetrievalException.class) - public void testRetrieveThrottleDataSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - obThrottlerDAO.getThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - @Test(expectedExceptions = OBThrottlerDataRetrievalException.class) - public void testRetrieveThrottleDataExistsSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - obThrottlerDAO.isThrottleDataExists(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - //data deletion tests - @Test(dependsOnMethods = "testRetrieveThrottleData") - public void testDeleteConsentAttribute() throws Exception { - - try (Connection connection = OBThrottlerDAOUtils.getConnection(DB_NAME)) { - - obThrottlerDAO.deleteThrottleData(connection, storedThrottleDataModel.getThrottleGroup(), - storedThrottleDataModel.getThrottleParam()); - } - } - - @Test(expectedExceptions = OBThrottlerDataDeletionException.class) - public void testDeleteThrottleDataError() throws Exception { - - Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) - .prepareStatement(Mockito.anyString()); - Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); - - obThrottlerDAO.deleteThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } - - @Test(expectedExceptions = OBThrottlerDataDeletionException.class) - public void testDeleteThrottleDataSQLError() throws Exception { - - Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); - obThrottlerDAO.deleteThrottleData(mockedConnection, OBThrottlerDAOTestData.THROTTLE_GROUP, - OBThrottlerDAOTestData.THROTTLE_PARAM); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/util/OBThrottlerDAOTestData.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/util/OBThrottlerDAOTestData.java deleted file mode 100644 index ae425b30..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/util/OBThrottlerDAOTestData.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.util; - -import java.sql.Timestamp; -import java.util.Date; - -/** - * Test data for Open Banking throttler DAO. - */ -public class OBThrottlerDAOTestData { - - public static final String THROTTLE_GROUP = "OBIdentifierAuthenticator"; - - public static final String THROTTLE_PARAM = "user-ip-192.168.1.1"; - - public static final Timestamp CURRENT_TIMESTAMP = new Timestamp(new Date().getTime()); - - public static final Timestamp UNLOCK_TIMESTAMP = new Timestamp(CURRENT_TIMESTAMP.getTime() + (1000L * 180)); - - public static final int OCCURRENCES = 1; - - /** - * Data provider. - */ - public static final class DataProviders { - - /* - * throttleGroup - * throttleParam - * currentTimestamp - * unlockTimestamp - * occurrences - */ - public static final Object[][] OB_THROTTLER_DATA_HOLDER = new Object[][]{ - - { - THROTTLE_GROUP, - THROTTLE_PARAM, - CURRENT_TIMESTAMP, - UNLOCK_TIMESTAMP, - OCCURRENCES - } - }; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/util/OBThrottlerDAOUtils.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/util/OBThrottlerDAOUtils.java deleted file mode 100644 index 63a3e914..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/java/com/wso2/openbanking/accelerator/throttler/dao/util/OBThrottlerDAOUtils.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.dao.util; - -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.commons.lang3.StringUtils; - -import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - -/** - * Test for Open Banking throttler DAO utils. - */ -public class OBThrottlerDAOUtils { - - private static Map dataSourceMap = new HashMap<>(); - - public static void initializeDataSource(String databaseName, String scriptPath) throws Exception { - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName("org.h2.Driver"); - dataSource.setUsername("username"); - dataSource.setPassword("password"); - dataSource.setUrl("jdbc:h2:mem:" + databaseName); - - try (Connection connection = dataSource.getConnection()) { - connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'"); - } - dataSourceMap.put(databaseName, dataSource); - } - - public static Connection getConnection(String database) throws SQLException { - if (dataSourceMap.get(database) != null) { - return dataSourceMap.get(database).getConnection(); - } - throw new RuntimeException("Invalid datasource."); - } - - public static String getFilePath(String fileName) { - if (StringUtils.isNotBlank(fileName)) { - return Paths.get(System.getProperty("user.dir"), "src", "test", "resources", fileName) - .toString(); - } - return null; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/resources/dbScripts/h2.sql b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/resources/dbScripts/h2.sql deleted file mode 100644 index 3bcb12cf..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/resources/dbScripts/h2.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE TABLE IF NOT EXISTS OB_THROTTLE_DATA ( - THROTTLE_GROUP VARCHAR(100) NOT NULL, - THROTTLE_PARAM VARCHAR(100) NOT NULL, - LAST_UPDATE_TIMESTAMP DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - UNLOCK_TIMESTAMP DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - OCCURRENCES INTEGER NOT NULL, - PRIMARY KEY (THROTTLE_GROUP,THROTTLE_PARAM) -); diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/resources/testng.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/resources/testng.xml deleted file mode 100644 index 7d5a867e..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.dao/src/test/resources/testng.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/pom.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/pom.xml deleted file mode 100644 index 4dce7220..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/pom.xml +++ /dev/null @@ -1,213 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.throttler.service - WSO2 Open Banking - Throttler Service - WSO2 Open Banking - Throttler Service Module - bundle - - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.throttler.dao - provided - - - org.testng - testng - - - com.h2database - h2 - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - org.mockito - mockito-all - test - - - org.powermock - powermock-api-mockito - test - - - org.powermock - powermock-module-testng - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - **/*Constants.class - **/*Component.class - **/*DataHolder.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.80 - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - org.apache.felix - maven-bundle-plugin - true - - - - ${project.artifactId} - - - com.wso2.openbanking.accelerator.throttler.service.internal - - - org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", - org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", - com.wso2.openbanking.accelerator.common.*;version="${project.version}", - org.apache.commons.lang3;version="${commons-lang.version}" - - - !com.wso2.openbanking.accelerator.throttler.service.internal, - com.wso2.openbanking.accelerator.throttler.service.*;version="${project.version}", - - * - <_dsannotations>* - - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/OBThrottleService.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/OBThrottleService.java deleted file mode 100644 index 03641744..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/OBThrottleService.java +++ /dev/null @@ -1,245 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.service; - -import com.wso2.openbanking.accelerator.common.exception.OBThrottlerException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.throttler.dao.OBThrottlerDAO; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataDeletionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataInsertionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataRetrievalException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataUpdationException; -import com.wso2.openbanking.accelerator.throttler.dao.model.ThrottleDataModel; -import com.wso2.openbanking.accelerator.throttler.dao.persistence.DataStoreInitializer; -import com.wso2.openbanking.accelerator.throttler.service.constants.OBThrottlerServiceConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.Timestamp; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * Service class for OB Throttler. - *

- * Contains methods required to throttle the occurrence of a given parameter. - * The parameters can be separated into groups by 'throttleGroup' attribute, which will - * allow throttling same parameter values in different groups. - */ -public class OBThrottleService { - - private static Log log = LogFactory.getLog(OBThrottleService.class); - protected Map> throttleDataMap = new HashMap<>(); - private static OBThrottleService instance = null; - - // private constructor - private OBThrottleService() { - } - - /** - * @return OBThrottleService instance - */ - public static synchronized OBThrottleService getInstance() { - - if (instance == null) { - instance = new OBThrottleService(); - } - return instance; - } - - /** - * Update throttle database and throttleDataMap. - * - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @param throttleLimit - allowed number of occurrences - * @param throttleTimePeriod - time period that the parameter is throttled (seconds) - * @throws OBThrottlerException - OBThrottlerException - */ - public void updateThrottleData(String throttleGroup, String throttleParam, int throttleLimit, - int throttleTimePeriod) throws OBThrottlerException { - - ThrottleDataModel throttleDataModel; - ThrottleDataModel existingThrottleDataModel; - OBThrottlerDAO obThrottlerDAO = DataStoreInitializer.initializeOBThrottlerDAO(); - Timestamp currentTimestamp = new Timestamp(new Date().getTime()); - Timestamp unlockTimestamp = new Timestamp(currentTimestamp.getTime() + (1000L * throttleTimePeriod)); - - Connection connection = DatabaseUtil.getDBConnection(); - - try { - //remove expired data from database by checking throttle status - getThrottleStatus(connection, throttleGroup, throttleParam, obThrottlerDAO); - //check if throttle group and parameter exists. Add new record if not. - - if (obThrottlerDAO.isThrottleDataExists(connection, throttleGroup, throttleParam)) { - existingThrottleDataModel = obThrottlerDAO.getThrottleData(connection, throttleGroup, throttleParam); - //increment Occurrences - int updatedOccurrences = existingThrottleDataModel.getOccurrences() + 1; - throttleDataModel = obThrottlerDAO.updateThrottleData(connection, throttleGroup, throttleParam, - currentTimestamp, unlockTimestamp, updatedOccurrences); - } else { - throttleDataModel = obThrottlerDAO.storeThrottleData(connection, throttleGroup, throttleParam, - currentTimestamp, unlockTimestamp); - } - DatabaseUtil.commitTransaction(connection); - log.debug(OBThrottlerServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - if (throttleDataModel.getOccurrences() > throttleLimit) { - updateThrottleDataMap(throttleGroup, throttleParam, throttleDataModel.getUnlockTimestamp()); - } - } catch (OBThrottlerDataInsertionException e) { - log.error(OBThrottlerServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); - } catch (OBThrottlerDataUpdationException e) { - log.error(OBThrottlerServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); - } catch (OBThrottlerDataRetrievalException e) { - log.error(OBThrottlerServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBThrottlerDataDeletionException e) { - log.error(OBThrottlerServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - } finally { - log.debug(OBThrottlerServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - /** - * Check if the given parameter is throttled. - * - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @return - boolean - * @throws OBThrottlerException - OBThrottlerDataDeletionException - */ - public boolean isThrottled(String throttleGroup, String throttleParam) throws OBThrottlerException { - - Connection connection = DatabaseUtil.getDBConnection(); - OBThrottlerDAO obThrottlerDAO = DataStoreInitializer.initializeOBThrottlerDAO(); - - try { - boolean throttleStatus = getThrottleStatus(connection, throttleGroup, throttleParam, obThrottlerDAO); - DatabaseUtil.commitTransaction(connection); - log.debug(OBThrottlerServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); - return throttleStatus; - } catch (OBThrottlerDataDeletionException e) { - log.error(OBThrottlerServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - } finally { - log.debug(OBThrottlerServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - /** - * Delete the throttle data record from DB on a successful attempt. - * - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @throws OBThrottlerException - OBThrottlerDataDeletionException, OBThrottlerDataRetrievalException - */ - public void deleteRecordOnSuccessAttempt(String throttleGroup, String throttleParam) throws OBThrottlerException { - - Connection connection = DatabaseUtil.getDBConnection(); - OBThrottlerDAO obThrottlerDAO = DataStoreInitializer.initializeOBThrottlerDAO(); - - try { - if (obThrottlerDAO.isThrottleDataExists(connection, throttleGroup, throttleParam)) { - obThrottlerDAO.deleteThrottleData(connection, throttleGroup, throttleParam); - DatabaseUtil.commitTransaction(connection); - } - } catch (OBThrottlerDataRetrievalException e) { - log.error(OBThrottlerServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); - } catch (OBThrottlerDataDeletionException e) { - log.error(OBThrottlerServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - DatabaseUtil.rollbackTransaction(connection); - throw new OBThrottlerException(OBThrottlerServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); - } finally { - log.debug(OBThrottlerServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); - DatabaseUtil.closeConnection(connection); - } - } - - /** - * Check if the given parameter is throttled. This method is overloaded. - * - * @param connection connection object - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @return - boolean - * @throws OBThrottlerDataDeletionException - OBThrottlerDataDeletionException - */ - private boolean getThrottleStatus(Connection connection, String throttleGroup, String throttleParam, - OBThrottlerDAO obThrottlerDAO) throws OBThrottlerDataDeletionException { - - Map throttleParamMap; - if (throttleDataMap.containsKey(throttleGroup)) { - throttleParamMap = throttleDataMap.get(throttleGroup); - if (throttleParamMap.containsKey(throttleParam)) { - //check if the parameter is still locked - Timestamp currentTimestamp = new Timestamp(new Date().getTime()); - Timestamp unlockTimestamp = throttleParamMap.get(throttleParam); - if (unlockTimestamp.after(currentTimestamp)) { - return true; - } else { - //remove throttle parameter from throttle data map if expired - throttleParamMap.remove(throttleParam); - throttleDataMap.put(throttleGroup, throttleParamMap); - //remove from database - obThrottlerDAO.deleteThrottleData(connection, throttleGroup, throttleParam); - return false; - } - } else { - return false; - } - } else { - return false; - } - } - - /** - * Update throttle data map. - * - * @param throttleGroup - throttle group - * @param throttleParam - throttle parameter - * @param unlockTimestamp - timestamp that the parameter will be unlocked. - */ - protected void updateThrottleDataMap(String throttleGroup, String throttleParam, Timestamp unlockTimestamp) { - - Map throttleParamMap; - //check if throttle group already exists - if (throttleDataMap.containsKey(throttleGroup)) { - throttleParamMap = throttleDataMap.get(throttleGroup); - } else { - throttleParamMap = new HashMap<>(); - } - //put parameter and unlockTimestamp to the throttle data map - throttleParamMap.put(throttleParam, unlockTimestamp); - throttleDataMap.put(throttleGroup, throttleParamMap); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/constants/OBThrottlerServiceConstants.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/constants/OBThrottlerServiceConstants.java deleted file mode 100644 index 7cfae883..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/constants/OBThrottlerServiceConstants.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.service.constants; - -/** - * OB Throttler Service Constants. - */ -public class OBThrottlerServiceConstants { - - public static final String TRANSACTION_COMMITTED_LOG_MSG = "Transaction committed"; - public static final String DATABASE_CONNECTION_CLOSE_LOG_MSG = "Closing database connection"; - - public static final String DATA_INSERTION_ROLLBACK_ERROR_MSG = "Error occurred while inserting data. Rolling " + - "back the transaction"; - public static final String DATA_UPDATE_ROLLBACK_ERROR_MSG = "Error occurred while updating data. Rolling " + - "back the transaction"; - public static final String DATA_RETRIEVE_ERROR_MSG = "Error occurred while retrieving data"; - public static final String DATA_DELETE_ROLLBACK_ERROR_MSG = "Error occurred while deleting data. Rolling " + - "back the transaction"; -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/internal/OBThrottlerDataHolder.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/internal/OBThrottlerDataHolder.java deleted file mode 100644 index e8f49f8c..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/internal/OBThrottlerDataHolder.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.service.internal; - -import org.wso2.carbon.user.core.service.RealmService; - -/** - * OBThrottler Data Holder. - */ -public class OBThrottlerDataHolder { - - private static OBThrottlerDataHolder instance = new OBThrottlerDataHolder(); - - private RealmService realmService; - - private OBThrottlerDataHolder() { - - } - - public static OBThrottlerDataHolder getInstance() { - - return instance; - } - - public RealmService getRealmService() { - - if (realmService == null) { - throw new RuntimeException("Realm Service is not available. Component did not start correctly."); - } - return realmService; - } - - void setRealmService(RealmService realmService) { - - this.realmService = realmService; - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/internal/OBThrottlerServiceComponent.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/internal/OBThrottlerServiceComponent.java deleted file mode 100644 index 052acacf..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/java/com/wso2/openbanking/accelerator/throttler/service/internal/OBThrottlerServiceComponent.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.service.internal; - -import com.wso2.openbanking.accelerator.throttler.service.OBThrottleService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.user.core.service.RealmService; - -/** - * OBThrottler component. - */ -@Component( - name = "open.banking.throttler.component", - immediate = true -) -public class OBThrottlerServiceComponent { - - private static final Log log = LogFactory.getLog(OBThrottlerServiceComponent.class); - - public static RealmService getRealmService() { - return (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(RealmService.class); - } - - @Reference( - name = "realm.service", - service = RealmService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRealmService" - ) - protected void setRealmService(RealmService realmService) { - - log.debug("Setting the Realm Service"); - OBThrottlerDataHolder.getInstance().setRealmService(realmService); - } - - @Activate - protected void activate(ComponentContext ctxt) { - - try { - OBThrottleService obThrottleService = OBThrottleService.getInstance(); - ctxt.getBundleContext().registerService(OBThrottleService.class.getName(), - obThrottleService, null); - log.debug("OBThrottleService bundle is activated"); - - } catch (Throwable e) { - log.error("OBThrottleService bundle activation Failed", e); - } - } - - @Deactivate - protected void deactivate(ComponentContext ctxt) { - - log.debug("OBThrottleService bundle is deactivated"); - } - - protected void unsetRealmService(RealmService realmService) { - - log.debug("UnSetting the Realm Service"); - OBThrottlerDataHolder.getInstance().setRealmService(null); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/resources/findbugs-include.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/java/com/wso2/openbanking/accelerator/throttler/service/OBThrottleServiceTests.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/java/com/wso2/openbanking/accelerator/throttler/service/OBThrottleServiceTests.java deleted file mode 100644 index a6b23b7e..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/java/com/wso2/openbanking/accelerator/throttler/service/OBThrottleServiceTests.java +++ /dev/null @@ -1,303 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.service; - -import com.wso2.openbanking.accelerator.common.exception.OBThrottlerException; -import com.wso2.openbanking.accelerator.common.util.DatabaseUtil; -import com.wso2.openbanking.accelerator.throttler.dao.OBThrottlerDAO; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataDeletionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataInsertionException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataRetrievalException; -import com.wso2.openbanking.accelerator.throttler.dao.exception.OBThrottlerDataUpdationException; -import com.wso2.openbanking.accelerator.throttler.dao.model.ThrottleDataModel; -import com.wso2.openbanking.accelerator.throttler.dao.persistence.DataStoreInitializer; -import com.wso2.openbanking.accelerator.throttler.service.util.OBThrottleServiceTestData; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; - -import java.sql.Connection; -import java.sql.Timestamp; -import java.util.HashMap; - -/** - * Test for Open banking throttle service. - */ -@PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({DatabaseUtil.class, DataStoreInitializer.class}) -public class OBThrottleServiceTests { - - private OBThrottleService obThrottleService; - private OBThrottlerDAO mockedOBThrottlerDAO; - private Connection mockedConnection; - private ThrottleDataModel throttleDataModel; - - @BeforeClass - public void initTest() { - - obThrottleService = OBThrottleService.getInstance(); - mockedOBThrottlerDAO = Mockito.mock(OBThrottlerDAO.class); - mockedConnection = Mockito.mock(Connection.class); - throttleDataModel = Mockito.mock(ThrottleDataModel.class); - } - - @BeforeMethod - public void mock() throws OBThrottlerException { - - mockStaticClasses(); - } - - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - - @Test - public void testThrottledOutScenario() throws Exception { - - Mockito.doNothing().when(mockedOBThrottlerDAO).deleteThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - obThrottleService.throttleDataMap.put(OBThrottleServiceTestData.THROTTLE_GROUP, - new HashMap() { - { - put(OBThrottleServiceTestData.THROTTLE_PARAM, - OBThrottleServiceTestData.UNLOCK_TIMESTAMP_GREATER_THAN_CURRENT_TIMESTAMP); - } - }); - - Boolean isThrottled = obThrottleService.isThrottled(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_PARAM); - - Assert.assertTrue(isThrottled); - } - - @Test - public void testNotThrottledOutScenario() throws Exception { - - Mockito.doNothing().when(mockedOBThrottlerDAO).deleteThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - obThrottleService.throttleDataMap.put(OBThrottleServiceTestData.THROTTLE_SECOND_GROUP, - new HashMap() { - { - put(OBThrottleServiceTestData.THROTTLE_PARAM, - OBThrottleServiceTestData.UNLOCK_TIMESTAMP_LESS_THAN_CURRENT_TIMESTAMP); - } - }); - - Boolean isThrottled = obThrottleService.isThrottled( - OBThrottleServiceTestData.THROTTLE_SECOND_GROUP, OBThrottleServiceTestData.THROTTLE_PARAM); - - Assert.assertFalse(isThrottled); - } - - @Test(priority = 1) - public void testThrottleGroupNotInThrottleDataMap() throws Exception { - - Mockito.doNothing().when(mockedOBThrottlerDAO).deleteThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - Boolean isThrottled = obThrottleService.isThrottled( - OBThrottleServiceTestData.THROTTLE_GROUP_BASIC_AUTH, OBThrottleServiceTestData.THROTTLE_PARAM); - - Assert.assertFalse(isThrottled); - } - - @Test(priority = 1) - public void testThrottleParamNotInThrottleDataMap() throws Exception { - - Mockito.doNothing().when(mockedOBThrottlerDAO).deleteThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - Boolean isThrottled = obThrottleService.isThrottled( - OBThrottleServiceTestData.THROTTLE_SECOND_GROUP, OBThrottleServiceTestData.THROTTLE_SECOND_PARAM); - - Assert.assertFalse(isThrottled); - } - - @Test(priority = 2) - public void testThrottleGroupInUpdateThrottleDataMap() { - - obThrottleService.updateThrottleDataMap(OBThrottleServiceTestData.THROTTLE_SECOND_GROUP, - OBThrottleServiceTestData.THROTTLE_PARAM, - OBThrottleServiceTestData.UNLOCK_TIMESTAMP_GREATER_THAN_CURRENT_TIMESTAMP); - - Assert.assertTrue(obThrottleService.throttleDataMap - .containsKey(OBThrottleServiceTestData.THROTTLE_SECOND_GROUP)); - } - - @Test(priority = 2) - public void testThrottleGroupNotInUpdateThrottleDataMap() { - - obThrottleService.updateThrottleDataMap(OBThrottleServiceTestData.THROTTLE_GROUP_BASIC_AUTH, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM, - OBThrottleServiceTestData.UNLOCK_TIMESTAMP_GREATER_THAN_CURRENT_TIMESTAMP); - - Assert.assertTrue(obThrottleService.throttleDataMap - .containsKey(OBThrottleServiceTestData.THROTTLE_GROUP_BASIC_AUTH)); - } - - @Test - public void testUpdateThrottleData() throws Exception { - - Mockito.doReturn(true).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleTestThrottleData()).when(mockedOBThrottlerDAO) - .getThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData()).when(mockedOBThrottlerDAO) - .updateThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyObject(), - Mockito.anyObject(), Mockito.anyInt()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData().getOccurrences()) - .when(throttleDataModel).getOccurrences(); - - obThrottleService.updateThrottleData(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM, 3, 180); - - } - - @Test - public void testStoreThrottleData() throws Exception { - - Mockito.doReturn(false).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData()).when(mockedOBThrottlerDAO) - .storeThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyObject(), - Mockito.anyObject()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData().getOccurrences()) - .when(throttleDataModel).getOccurrences(); - - obThrottleService.updateThrottleData(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM, 3, 180); - - } - - @Test(expectedExceptions = OBThrottlerException.class) - public void testStoreThrottleDataError() throws Exception { - - Mockito.doReturn(false).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doThrow(OBThrottlerDataInsertionException.class).when(mockedOBThrottlerDAO) - .storeThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyObject(), - Mockito.anyObject()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData().getOccurrences()) - .when(throttleDataModel).getOccurrences(); - - obThrottleService.updateThrottleData(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM, 3, 180); - - } - - @Test(expectedExceptions = OBThrottlerException.class) - public void testUpdateThrottleDataError() throws Exception { - - Mockito.doReturn(true).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleTestThrottleData()).when(mockedOBThrottlerDAO) - .getThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doThrow(OBThrottlerDataUpdationException.class).when(mockedOBThrottlerDAO) - .updateThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyObject(), - Mockito.anyObject(), Mockito.anyInt()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData().getOccurrences()) - .when(throttleDataModel).getOccurrences(); - - obThrottleService.updateThrottleData(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM, 3, 180); - - } - - @Test(expectedExceptions = OBThrottlerException.class) - public void testRetrievalThrottleDataError() throws Exception { - - Mockito.doReturn(true).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doThrow(OBThrottlerDataRetrievalException.class).when(mockedOBThrottlerDAO) - .getThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData()).when(mockedOBThrottlerDAO) - .updateThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyObject(), - Mockito.anyObject(), Mockito.anyInt()); - Mockito.doReturn(OBThrottleServiceTestData.getSampleUpdateTestThrottleData().getOccurrences()) - .when(throttleDataModel).getOccurrences(); - - obThrottleService.updateThrottleData(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM, 3, 180); - - } - - @Test - public void testDeleteRecordOnSuccessAttempt() throws Exception { - - Mockito.doReturn(true).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - obThrottleService.deleteRecordOnSuccessAttempt(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM); - - } - - @Test(expectedExceptions = OBThrottlerException.class) - public void testRetrievalThrottleDataErrorWhenDeleteRecordOnSuccessAttempt() throws Exception { - - Mockito.doThrow(OBThrottlerDataRetrievalException.class).when(mockedOBThrottlerDAO) - .isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - obThrottleService.deleteRecordOnSuccessAttempt(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM); - - } - - @Test(expectedExceptions = OBThrottlerException.class) - public void testDeleteThrottleDataErrorWhenDeleteRecordOnSuccessAttempt() throws Exception { - - Mockito.doReturn(true).when(mockedOBThrottlerDAO).isThrottleDataExists(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - Mockito.doThrow(OBThrottlerDataDeletionException.class).when(mockedOBThrottlerDAO) - .deleteThrottleData(Mockito.anyObject(), - Mockito.anyString(), Mockito.anyString()); - - obThrottleService.deleteRecordOnSuccessAttempt(OBThrottleServiceTestData.THROTTLE_GROUP, - OBThrottleServiceTestData.THROTTLE_SECOND_PARAM); - - } - - private void mockStaticClasses() throws OBThrottlerException { - - PowerMockito.mockStatic(DatabaseUtil.class); - PowerMockito.when(DatabaseUtil.getDBConnection()).thenReturn(Mockito.mock(Connection.class)); - - PowerMockito.mockStatic(DataStoreInitializer.class); - PowerMockito.when(DataStoreInitializer.initializeOBThrottlerDAO()).thenReturn(mockedOBThrottlerDAO); - } -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/java/com/wso2/openbanking/accelerator/throttler/service/util/OBThrottleServiceTestData.java b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/java/com/wso2/openbanking/accelerator/throttler/service/util/OBThrottleServiceTestData.java deleted file mode 100644 index 93e2eaa9..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/java/com/wso2/openbanking/accelerator/throttler/service/util/OBThrottleServiceTestData.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.throttler.service.util; - -import com.wso2.openbanking.accelerator.throttler.dao.model.ThrottleDataModel; - -import java.sql.Timestamp; -import java.util.Date; - -/** - * Test data for Open Banking throttle service. - */ -public class OBThrottleServiceTestData { - - public static final Timestamp CURRENT_TIMESTAMP = new Timestamp(new Date().getTime()); - - public static final Timestamp UNLOCK_TIMESTAMP_GREATER_THAN_CURRENT_TIMESTAMP = - new Timestamp(CURRENT_TIMESTAMP.getTime() + (1000L * 180)); - - public static final Timestamp UNLOCK_TIMESTAMP_LESS_THAN_CURRENT_TIMESTAMP = - new Timestamp(CURRENT_TIMESTAMP.getTime() - (1000L * 180)); - - public static final String THROTTLE_GROUP = "OBIdentifierAuthenticator"; - - public static final String THROTTLE_SECOND_GROUP = "OBIdentifierAuthenticator-1"; - - public static final String THROTTLE_GROUP_BASIC_AUTH = "BasicAuth"; - - public static final String THROTTLE_PARAM = "user-ip-192.168.1.1"; - - public static final String THROTTLE_SECOND_PARAM = "user-ip-192.168.1.1"; - - public static ThrottleDataModel getSampleTestThrottleData() { - - ThrottleDataModel throttleDataModel = new ThrottleDataModel(THROTTLE_GROUP, THROTTLE_PARAM, CURRENT_TIMESTAMP, - UNLOCK_TIMESTAMP_GREATER_THAN_CURRENT_TIMESTAMP, 1); - return throttleDataModel; - } - - public static ThrottleDataModel getSampleUpdateTestThrottleData() { - - ThrottleDataModel throttleDataModel = new ThrottleDataModel(THROTTLE_GROUP, THROTTLE_PARAM, CURRENT_TIMESTAMP, - UNLOCK_TIMESTAMP_GREATER_THAN_CURRENT_TIMESTAMP, 5); - - return throttleDataModel; - } - -} diff --git a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/resources/testng.xml b/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/resources/testng.xml deleted file mode 100644 index d8692438..00000000 --- a/open-banking-accelerator/components/ob-throttler/com.wso2.openbanking.accelerator.throttler.service/src/test/resources/testng.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/.openapi-generator-ignore b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/.openapi-generator-ignore deleted file mode 100755 index 4886bc8b..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/.openapi-generator-ignore +++ /dev/null @@ -1,25 +0,0 @@ -# OpenAPI Generator Ignore -# Generated by openapi-generator https://github.com/openapitools/openapi-generator - -# Use this file to prevent files from being overwritten by the generator. -# The patterns follow closely to .gitignore or .dockerignore. - -# As an example, the C# client generator defines ApiClient.cs. -# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: -#ApiClient.cs - -# You can match any string of characters against a directory, file or extension with a single asterisk (*): -#foo/*/qux -# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux - -# You can recursively match patterns against a directory, file or extension with a double asterisk (**): -#foo/**/qux -# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux - -# You can also negate patterns with an exclamation (!). -# For example, you can ignore all files in a docs folder with the file extension .md: -#docs/*.md -# Then explicitly reverse the ignore rule for a single file: -#!docs/README.md - -**/impl/* \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/findbugs-exclude.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/findbugs-exclude.xml deleted file mode 100755 index 665c19b4..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/findbugs-exclude.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/pom.xml deleted file mode 100755 index 760f2e03..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - openbanking-application-info-endpoint - war - WSO2 Open Banking - Application Info Endpoint - - - - io.swagger - swagger-jaxrs - provided - - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.core - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.authentication.framework - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.mgt - provided - - - org.apache.commons - commons-lang3 - provided - - - org.testng - testng - test - - - - - - - org.openapitools - openapi-generator-maven-plugin - ${openapi.generator.plugin.version} - - - - generate - - - - true - ${project.basedir}/src/main/resources/application-info-130.yaml - jaxrs-cxf - - src/gen/java/ - true - - false - com.wso2.open.banking.application.info.endpoint.model - com.wso2.open.banking.application.info.endpoint.api - impl - DTO - ${project.basedir} - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#application - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/api/ApplicationInformationApi.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/api/ApplicationInformationApi.java deleted file mode 100755 index b1418b99..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/api/ApplicationInformationApi.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.api; - -import com.wso2.open.banking.application.info.endpoint.model.ApplicationBulkMetadataSuccessDTO; -import com.wso2.open.banking.application.info.endpoint.model.ApplicationInfoErrorDTO; -import com.wso2.open.banking.application.info.endpoint.model.ApplicationSingleMetadataSuccessDTO; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -import javax.validation.constraints.NotNull; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import java.util.List; - -/** - * ApplicationInfoAPI - * - *

This specifies a RESTful API for retriving OAuth Application Information - * - */ -@Path("/") -@Api(value = "/", description = "") -public interface ApplicationInformationApi { - - /** - * Retrieve Bulk Application Metadata - * - */ - @GET - @Path("/metadata/") - @Produces({ "application/json" }) - @ApiOperation(value = "Retrieve Bulk Application Metadata", tags={ "Application Information", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK", response = ApplicationBulkMetadataSuccessDTO.class), - @ApiResponse(code = 404, message = "Service Provider Data Not Found"), - @ApiResponse(code = 400, message = "Bad Request", response = ApplicationInfoErrorDTO.class), - @ApiResponse(code = 500, message = "Internal Server Error", response = ApplicationInfoErrorDTO.class) }) - public Response getBulkApplicationMetadata(@QueryParam("clientIds") @NotNull List clientIds); - - /** - * Retrieve All Application Metadata - * - */ - @GET - @Path("/all/metadata") - @Produces({ "application/json" }) - @ApiOperation(value = "Retrieve Bulk Application Metadata", tags={ "Application Information", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK", response = ApplicationBulkMetadataSuccessDTO.class), - @ApiResponse(code = 404, message = "Service Provider Data Not Found"), - @ApiResponse(code = 400, message = "Bad Request", response = ApplicationInfoErrorDTO.class), - @ApiResponse(code = 500, message = "Internal Server Error", response = ApplicationInfoErrorDTO.class) }) - public Response getAllApplicationMetadata(); - - /** - * Retrieve Single Application Metadata - * - */ - @GET - @Path("/metadata/{id}") - @Produces({ "application/json" }) - @ApiOperation(value = "Retrieve Single Application Metadata", tags={ "Application Information" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK", response = ApplicationSingleMetadataSuccessDTO.class), - @ApiResponse(code = 404, message = "Service Provider Data Not Found"), - @ApiResponse(code = 400, message = "Bad Request", response = ApplicationInfoErrorDTO.class), - @ApiResponse(code = 500, message = "Internal Server Error", response = ApplicationInfoErrorDTO.class) }) - public Response getSingleApplicationMetadata(@PathParam("id") String id); -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationBulkMetadataSuccessDTO.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationBulkMetadataSuccessDTO.java deleted file mode 100755 index 4d08f344..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationBulkMetadataSuccessDTO.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.model; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.HashMap; -import java.util.Map; - -/** - * defines metadata for requested applications - **/ -@ApiModel(description="defines metadata for requested applications") -public class ApplicationBulkMetadataSuccessDTO { - - @ApiModelProperty(required = true, value = "Key value pairs of clientId and attributes") - @Valid - /** - * Key value pairs of clientId and attributes - **/ - private Map data = new HashMap(); - /** - * Key value pairs of clientId and attributes - * @return data - **/ - @JsonProperty("data") - @NotNull - public Map getData() { - return data; - } - - public void setData(Map data) { - this.data = data; - } - - public ApplicationBulkMetadataSuccessDTO data(Map data) { - this.data = data; - return this; - } - - public ApplicationBulkMetadataSuccessDTO putDataItem(String key, ApplicationMetadataResourceDTO dataItem) { - this.data.put(key, dataItem); - return this; - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApplicationBulkMetadataSuccessDTO {\n"); - - sb.append(" data: ").append(toIndentedString(data)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private static String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationInfoErrorDTO.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationInfoErrorDTO.java deleted file mode 100755 index a51c7f89..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationInfoErrorDTO.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.model; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * defines error object for application infromation api - **/ -@ApiModel(description="defines error object for application infromation api") -public class ApplicationInfoErrorDTO { - - @ApiModelProperty(value = "HTTP error code as string") - /** - * HTTP error code as string - **/ - private String status; - - @ApiModelProperty(value = "error summmary") - /** - * error summmary - **/ - private String title; - - @ApiModelProperty(value = "human readable error description") - /** - * human readable error description - **/ - private String description; - /** - * HTTP error code as string - * @return status - **/ - @JsonProperty("status") - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public ApplicationInfoErrorDTO status(String status) { - this.status = status; - return this; - } - - /** - * error summmary - * @return title - **/ - @JsonProperty("title") - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public ApplicationInfoErrorDTO title(String title) { - this.title = title; - return this; - } - - /** - * human readable error description - * @return description - **/ - @JsonProperty("description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public ApplicationInfoErrorDTO description(String description) { - this.description = description; - return this; - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApplicationInfoErrorDTO {\n"); - - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" title: ").append(toIndentedString(title)).append("\n"); - sb.append(" description: ").append(toIndentedString(description)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private static String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationMetadataResourceDTO.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationMetadataResourceDTO.java deleted file mode 100755 index a4d13617..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationMetadataResourceDTO.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.model; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import java.util.Map; - -/** - * defines resource object for application - **/ -@ApiModel(description="defines resource object for application") -public class ApplicationMetadataResourceDTO { - - @ApiModelProperty(value = "type of object") - /** - * type of object - **/ - private String type; - - @ApiModelProperty(value = "OAuth Client id of the application") - /** - * OAuth Client id of the application - **/ - private String id; - - @ApiModelProperty(value = "Key-Value pairs of application metadata") - /** - * Key-Value pairs of application metadata - **/ - private Map metadata = null; - /** - * type of object - * @return type - **/ - @JsonProperty("type") - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public ApplicationMetadataResourceDTO type(String type) { - this.type = type; - return this; - } - - /** - * OAuth Client id of the application - * @return id - **/ - @JsonProperty("Id") - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public ApplicationMetadataResourceDTO id(String id) { - this.id = id; - return this; - } - - /** - * Key-Value pairs of application metadata - * @return metadata - **/ - @JsonProperty("metadata") - public Map getMetadata() { - return metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - public ApplicationMetadataResourceDTO metadata(Map metadata) { - this.metadata = metadata; - return this; - } - - public ApplicationMetadataResourceDTO putMetadataItem(String key, String metadataItem) { - this.metadata.put(key, metadataItem); - return this; - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApplicationMetadataResourceDTO {\n"); - - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private static String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationSingleMetadataSuccessDTO.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationSingleMetadataSuccessDTO.java deleted file mode 100755 index c10a7c99..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/gen/java/com/wso2/open/banking/application/info/endpoint/model/ApplicationSingleMetadataSuccessDTO.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.model; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - -/** - * defines metadata for requested applications - **/ -@ApiModel(description="defines metadata for requested applications") -public class ApplicationSingleMetadataSuccessDTO { - - @ApiModelProperty(required = true, value = "") - @Valid - private ApplicationMetadataResourceDTO data = null; - /** - * Get data - * @return data - **/ - @JsonProperty("data") - @NotNull - public ApplicationMetadataResourceDTO getData() { - return data; - } - - public void setData(ApplicationMetadataResourceDTO data) { - this.data = data; - } - - public ApplicationSingleMetadataSuccessDTO data(ApplicationMetadataResourceDTO data) { - this.data = data; - return this; - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApplicationSingleMetadataSuccessDTO {\n"); - - sb.append(" data: ").append(toIndentedString(data)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private static String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/constants/MetaDataSQLStatements.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/constants/MetaDataSQLStatements.java deleted file mode 100644 index e22e37a6..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/constants/MetaDataSQLStatements.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.api.constants; - -/** - * MetaDataSQLStatements. - * - *

This specifies SQL Statements for retrieving all consent id's for consent manager application - * - */ -public class MetaDataSQLStatements { - - /** - * SQL query to retrieve list of clientIds. - * @return - */ - public String getAllClientIds() { - - return "SELECT DISTINCT CLIENT_ID FROM OB_CONSENT"; - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/data/MetaDataDAOImpl.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/data/MetaDataDAOImpl.java deleted file mode 100644 index c5d2c1d0..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/data/MetaDataDAOImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.api.data; - -import com.google.common.collect.ImmutableMap; -import com.wso2.open.banking.application.info.endpoint.api.constants.MetaDataSQLStatements; -import com.wso2.openbanking.accelerator.common.persistence.JDBCPersistenceManager; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.core.Response; - -/** - * MetaDataDAOImpl. - * - *

This specifies a DAO Impl for retrieving all client id's for the consent manager application - */ -public class MetaDataDAOImpl { - - private static final Log log = LogFactory.getLog(MetaDataDAOImpl.class); - - /** - * Returns the List of distinct clientIds from the consent table. - * - * @return - */ - public List getAllDistinctClientIds() { - - MetaDataSQLStatements sqlStatements = new MetaDataSQLStatements(); - final String initialConsentRequest = sqlStatements.getAllClientIds(); - List clientIdList = new ArrayList<>(); - - try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(initialConsentRequest)) { - - try (ResultSet rs = preparedStatement.executeQuery()) { - while (rs.next()) { - clientIdList.add(rs.getString(1)); - } - } - if (log.isDebugEnabled()) { - log.debug(String.format("ClientIds %s provided for bulk retrieval", - Arrays.toString(clientIdList.toArray()))); - } - - return clientIdList; - } catch (SQLException e) { - log.error("Error occurred while retrieving ClientIds.", e); - Map error = ImmutableMap.of( - "error", "Error occurred while retrieving ClientIds"); - - throw new InternalServerErrorException(Response.status - (Response.Status.INTERNAL_SERVER_ERROR).entity(error).build()); - } - - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/impl/ApplicationInformationApiServiceImpl.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/impl/ApplicationInformationApiServiceImpl.java deleted file mode 100644 index 1cdb0806..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/impl/ApplicationInformationApiServiceImpl.java +++ /dev/null @@ -1,254 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.api.impl; - -import com.wso2.open.banking.application.info.endpoint.api.ApplicationInformationApi; -import com.wso2.open.banking.application.info.endpoint.api.data.MetaDataDAOImpl; -import com.wso2.open.banking.application.info.endpoint.api.utils.MappingUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -/** - * ApplicationInfoAPI. - * - *

This specifies a RESTful API for retriving OAuth Application Information - */ -public class ApplicationInformationApiServiceImpl implements ApplicationInformationApi { - - private static final String QUERY_PARAM_BULK_DELIMITER = ","; - private static final String ERROR_INVALID_REQUEST = "invalid clientIds given in request"; - private static final String ERROR_FETCHING_SP = "Unable to retrieve information," + - " please contact system administrator"; - private static final String APPLICATION_NOT_EXISTS = "Unavailable Application"; - - private static final Log log = LogFactory.getLog(ApplicationInformationApiServiceImpl.class); - - /** - * Retrieve Bulk Application Metadata. - * - * @param clientIds client ID sequences for retrieval. - * @return client response. - */ - public Response getBulkApplicationMetadata(List clientIds) { - - // Take List of query params for clientIds and split by delimiter and remove duplicates - List splitClientIds = clientIds.stream() - .map(str -> str.split(QUERY_PARAM_BULK_DELIMITER)) - .flatMap(Arrays::stream) - .distinct() - .filter(StringUtils::isNotEmpty) - .collect(Collectors.toList()); - - // Check if any IDs are set if not send error message - if (splitClientIds.isEmpty()) { - - return Response.status(Response.Status.BAD_REQUEST) - .entity(MappingUtil.buildErrorDTO( - String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()), - Response.Status.BAD_REQUEST.getReasonPhrase(), ERROR_INVALID_REQUEST)) - .build(); - } - - if (log.isDebugEnabled()) { - log.debug(String.format("ClientIds %s provided for bulk retrieval", - Arrays.toString(splitClientIds.toArray()))); - } - - // Retrieve Service Providers from list - List serviceProviderList = splitClientIds - .stream() - .map(this::getOAuthServiceProvider) - .collect(Collectors.toList()); - - return Response.ok() - .entity(MappingUtil.mapBulkMetadataResponseDTO(serviceProviderList)) - .build(); - } - - /** - * Retrieve All Bulk Application Metadata. - * - * @return client response. - */ - public Response getAllApplicationMetadata() { - - MetaDataDAOImpl metaDataDAOImpl = new MetaDataDAOImpl(); - - List clientIdList = metaDataDAOImpl.getAllDistinctClientIds(); - - return getBulkApplicationMetadata(clientIdList); - } - - - /** - * Retrieve Single Application Metadata. - * - * @param id clientId of application. - * @return client response. - */ - public Response getSingleApplicationMetadata(String id) { - - ServiceProvider selectedServiceProvider = getOAuthServiceProvider(id); - - // If Service provider is present map value and return - return Response.ok() - .entity(MappingUtil.mapSingleMetadataResponseDTO(selectedServiceProvider)) - .build(); - } - - /** - * Get Service provider from clientId. - * - * @param clientId of application. - * @return Service Provider. - * @throws WebApplicationException client error. - */ - private ServiceProvider getOAuthServiceProvider(String clientId) throws WebApplicationException { - - ApplicationManagementService managementService = this.getApplicationManagementService(); - Optional serviceProvider; - try { - serviceProvider = Optional.ofNullable(managementService.getServiceProviderByClientId(clientId, - IdentityApplicationConstants.OAuth2.NAME, getTenantDomain())); - } catch (IdentityApplicationManagementException e) { - - log.error(String.format("Unable to retrieve service provider information for clientId %s", clientId), e); - - // Throw Web Application exception - throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(MappingUtil.buildErrorDTO( - String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()), - Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), - ERROR_FETCHING_SP)) - .build()); - } - - // Handle empty or default service provider. - if (!serviceProvider.isPresent() || - serviceProvider.get().getApplicationName().equals(IdentityApplicationConstants.DEFAULT_SP_CONFIG)) { - - final String errorMessage = String.format("Unable to find application for clientId %s", clientId); - - if (log.isDebugEnabled()) { - log.debug(errorMessage); - } - - return handleSPForDefaultOrNull(clientId, serviceProvider); - } - - return serviceProvider.get(); - } - - /** - * Populate serviceProvider with APPLICATION_NOT_EXISTS based on default or empty. - * @param clientId - * @param serviceProvider - * @return - */ - private ServiceProvider handleSPForDefaultOrNull(String clientId, Optional serviceProvider) { - - ServiceProvider serviceProviderForErrorScenarios; - - // set new SP and inboundAuthenticationConfig for cases where serviceProvider is not present - if (!serviceProvider.isPresent()) { - serviceProviderForErrorScenarios = new ServiceProvider(); - - InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig(); - InboundAuthenticationRequestConfig[] configs = new InboundAuthenticationRequestConfig[1]; - configs[0] = new InboundAuthenticationRequestConfig(); - configs[0].setInboundAuthKey(clientId); - configs[0].setInboundAuthType(IdentityApplicationConstants.OAuth2.NAME); - inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(configs); - serviceProviderForErrorScenarios.setInboundAuthenticationConfig(inboundAuthenticationConfig); - serviceProvider = Optional.of(serviceProviderForErrorScenarios); - } - - // continue populating SP with properties - serviceProviderForErrorScenarios = serviceProvider.get(); - List serviceProviderPropertyList = new ArrayList<>(); - serviceProviderForErrorScenarios.setApplicationName(APPLICATION_NOT_EXISTS); - - ServiceProviderProperty displayName = new ServiceProviderProperty(); - displayName.setName("software_id"); - displayName.setValue(APPLICATION_NOT_EXISTS); - - ServiceProviderProperty clientName = new ServiceProviderProperty(); - clientName.setName("client_name"); - clientName.setValue(APPLICATION_NOT_EXISTS); - - serviceProviderPropertyList.add(displayName); - serviceProviderPropertyList.add(clientName); - ServiceProviderProperty[] serviceProviderProperties = - new ServiceProviderProperty[serviceProviderPropertyList.size()]; - - serviceProviderPropertyList.toArray(serviceProviderProperties); - serviceProviderForErrorScenarios.setSpProperties(serviceProviderProperties); - - InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = serviceProviderForErrorScenarios - .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs(); - if (inboundAuthenticationRequestConfigs.length != 0) { - inboundAuthenticationRequestConfigs[0].setInboundAuthKey(clientId); - inboundAuthenticationRequestConfigs[0].setInboundAuthType(IdentityApplicationConstants.OAuth2.NAME); - } - return serviceProviderForErrorScenarios; - } - - /** - * Get WSO2 IS Application Mgt Service from threadlocal carbon context. - * - * @return Application Management Service Implementation. - */ - private ApplicationManagementService getApplicationManagementService() { - - return (ApplicationManagementService) PrivilegedCarbonContext - .getThreadLocalCarbonContext() - .getOSGiService(ApplicationManagementService.class, null); - - } - - /** - * Get Tenant Domain String from carbon context. - * - * @return tenant domain of current context. - */ - private String getTenantDomain() { - - return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); - } - -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/utils/MappingUtil.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/utils/MappingUtil.java deleted file mode 100755 index b7eb2247..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/java/com/wso2/open/banking/application/info/endpoint/api/utils/MappingUtil.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.open.banking.application.info.endpoint.api.utils; - -import com.wso2.open.banking.application.info.endpoint.model.ApplicationBulkMetadataSuccessDTO; -import com.wso2.open.banking.application.info.endpoint.model.ApplicationInfoErrorDTO; -import com.wso2.open.banking.application.info.endpoint.model.ApplicationMetadataResourceDTO; -import com.wso2.open.banking.application.info.endpoint.model.ApplicationSingleMetadataSuccessDTO; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.identity.sp.metadata.extension.SPMetadataFilter; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * Map internal models to external API DTOs. - */ -public class MappingUtil { - - private static final Log log = LogFactory.getLog(MappingUtil.class); - private static final SPMetadataFilter metadataFilter = (SPMetadataFilter) OpenBankingUtils.getClassInstanceFromFQN( - OpenBankingConfigParser.getInstance().getSPMetadataFilterExtension()); - private static final String SOFTWARE_ID = "software_id"; - - /** - * Map Single Metadata API Response DTO from service provider. - * - * @param serviceProvider service provider to populate response with. - * @return - */ - public static ApplicationSingleMetadataSuccessDTO mapSingleMetadataResponseDTO(ServiceProvider serviceProvider) { - - // Create Target DTO - ApplicationSingleMetadataSuccessDTO successDTO = new ApplicationSingleMetadataSuccessDTO(); - - // Map single metadata resource to DTO - successDTO.setData(mapApplicationMetadataResourceDTO(serviceProvider)); - - return successDTO; - } - - /** - * Map bulk Metadata API Response DTO from list of service providers. - * - * @param serviceProviderList service provider list to populate response with. - * @return - */ - public static ApplicationBulkMetadataSuccessDTO mapBulkMetadataResponseDTO(List - serviceProviderList) { - - ApplicationBulkMetadataSuccessDTO successDTO = new ApplicationBulkMetadataSuccessDTO(); - - // Stream list of service providers and map to resource DTOs - successDTO.setData(serviceProviderList.stream() - .map(MappingUtil::mapApplicationMetadataResourceDTO) - .collect(Collectors.toMap(ApplicationMetadataResourceDTO::getId, obj -> obj))); - - return successDTO; - } - - /** - * Map Single Application Metadata Resource from service provider. - * - * @param serviceProvider service provider to populate response with. - * @return - */ - public static ApplicationMetadataResourceDTO mapApplicationMetadataResourceDTO(ServiceProvider serviceProvider) { - - ApplicationMetadataResourceDTO resourceDTO = new ApplicationMetadataResourceDTO(); - - // Filter out OAuth2 from array of InboundAuthenticationRequestConfig and get clientId - Optional clientId = Arrays.stream(serviceProvider.getInboundAuthenticationConfig() - .getInboundAuthenticationRequestConfigs()) - .filter(conf -> conf.getInboundAuthType().equals(IdentityApplicationConstants.OAuth2.NAME)) - .findFirst().map(InboundAuthenticationRequestConfig::getInboundAuthKey); - - // Set type of resource - resourceDTO.setType(IdentityApplicationConstants.OAuth2.NAME); - - // If clientId is present set to target DTO - clientId.ifPresent(resourceDTO::setId); - - // Stream through ServiceProvider property array and map to target attributes - Map metadata = Arrays.stream(serviceProvider.getSpProperties()) - .collect(Collectors.toMap(ServiceProviderProperty::getName, ServiceProviderProperty::getValue)); - - // Return default application name for software_id - if (StringUtils.isEmpty(metadata.get(SOFTWARE_ID))) { - metadata.put(SOFTWARE_ID, serviceProvider.getApplicationName()); - } - - // filter metadata map using the configured metadata filter logic. (default: DefaultSPMetadataFilter) - metadata = metadataFilter.filter(metadata); - - if (log.isDebugEnabled()) { - log.debug(String.format("Application metadata list for client_id %s : %s", - clientId.orElse(""), metadata)); - } - resourceDTO.setMetadata(metadata); - - return resourceDTO; - - } - - /** - * Build Client Error Reponse. - * - * @param status status code of the error. - * @param title summary of the error. - * @param description human readable descriptive error. - * @return Reponse object. - */ - public static ApplicationInfoErrorDTO buildErrorDTO(String status, String title, String description) { - - ApplicationInfoErrorDTO errorDTO = new ApplicationInfoErrorDTO(); - - errorDTO.setStatus(status); - errorDTO.setTitle(title); - errorDTO.setDescription(description); - return errorDTO; - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/application-info-300.yaml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/application-info-300.yaml deleted file mode 100755 index 1c72700a..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/application-info-300.yaml +++ /dev/null @@ -1,147 +0,0 @@ -openapi: 3.0.0 -info: - version: v3.0.0 - title: ApplicationInfoAPI - description: This specifies a RESTful API for retrieving OAuth Application Information - contact: - name: WSO2 - url: http://wso2.com/solutions/financial/open-banking/ - email: openbankingdemo@wso2.com - license: - name: WSO2 Commercial License - url: https://wso2.com -servers: - - url: https://{ob_km_host}:{ob_km_port}/api/openbanking/application/ - variables: - ob_km_host: - default: localhost - description: Host of the Open Banking Key Manager - ob_km_port: - default: "9446" - description: Port of the Open Banking Key Manager -paths: - /metadata/: - get: - summary: Retrieve Bulk Application Metadata - operationId: getBulkApplicationMetadata - tags: - - Application Information - parameters: - - in: query - name: clientIds - required: true - schema: - type: array - items: - type: string - style: form - explode: false - responses: - "200": - description: OK - content: - application/json: - schema: - $ref: "#/components/schemas/ApplicationBulkMetadataSuccess" - "404": - description: Service Provider Data Not Found - "400": - description: Bad Request - content: - application/json: - schema: - $ref: "#/components/schemas/ApplicationInfoError" - "500": - description: Internal Server Error - content: - application/json: - schema: - $ref: "#/components/schemas/ApplicationInfoError" - /metadata/{id}: - get: - summary: Retrieve Single Application Metadata - operationId: getSingleApplicationMetadata - tags: - - Application Information - parameters: - - name: id - in: path - description: The client id of the application - required: true - schema: - type: string - responses: - "200": - description: OK - content: - application/json: - schema: - $ref: "#/components/schemas/ApplicationSingleMetadataSuccess" - "404": - description: Service Provider Data Not Found - "400": - description: Bad Request - content: - application/json: - schema: - $ref: "#/components/schemas/ApplicationInfoError" - "500": - description: Internal Server Error - content: - application/json: - schema: - $ref: "#/components/schemas/ApplicationInfoError" -components: - schemas: - ApplicationBulkMetadataSuccess: - title: Application Bulk Metadata Success Response - description: Defines metadata for the requested applications - type: object - properties: - data: - type: object - description: Key value pairs of client ids and attributes - additionalProperties: - $ref: "#/components/schemas/ApplicationMetadataResource" - - required: - - data - ApplicationSingleMetadataSuccess: - title: Application Single Metadata Success Response - description: Defines metadata for a requested application - type: object - properties: - data: - $ref: "#/components/schemas/ApplicationMetadataResource" - required: - - data - ApplicationMetadataResource: - title: Application Metadata Resource - description: Defines a resource object for an application - type: object - properties: - type: - type: string - description: Object type - Id: - type: string - description: The OAuth client id of the application - metadata: - type: object - description: Key-Value pairs of application metadata - additionalProperties: - type: string - ApplicationInfoError: - title: Error Response - description: Defines an error object for the Application Information API - type: object - properties: - status: - type: string - description: The HTTP error code as a string - title: - type: string - description: Error summary - description: - type: string - description: Human readable error description diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index 6804ed0a..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100755 index dfc87b0b..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100755 index 3aed2904..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100755 index 16c696c8..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.application.info.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - WSO2 Open Banking - Application Info - WSO2 Open Banking - Application Info API - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/pom.xml deleted file mode 100644 index f90da6fb..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.ciba.authentication.endpoint - WSO2 Open Banking - CIBA Authentication Endpoint - WSO2 Open Banking - CIBA Authentication Endpoint - war - - - - org.testng - testng - test - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.extensions - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.ciba - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.authentication.framework - provided - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push.common - provided - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push.device.handler - provided - - - org.wso2.carbon.identity.outbound.auth.push - org.wso2.carbon.identity.application.authenticator.push - provided - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#ciba - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/api/CIBAAuthenticationEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/api/CIBAAuthenticationEndpoint.java deleted file mode 100644 index f158c269..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/api/CIBAAuthenticationEndpoint.java +++ /dev/null @@ -1,685 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.ciba.authentication.endpoint.impl.api; - -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.JWTParser; -import com.wso2.openbanking.accelerator.ciba.authentication.endpoint.impl.exception.CIBAAuthenticationEndpointException; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.CarbonUtils; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.builder.ConsentStepsBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.ciba.model.CIBAAuthenticationEndpointErrorResponse; -import com.wso2.openbanking.accelerator.consent.extensions.ciba.model.CIBAAuthenticationEndpointInterface; -import com.wso2.openbanking.accelerator.consent.extensions.common.AuthErrorCode; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentCache; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.identity.util.HTTPClientUtils; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; -import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; -import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.application.authenticator.push.common.PushAuthContextManager; -import org.wso2.carbon.identity.application.authenticator.push.common.PushJWTValidator; -import org.wso2.carbon.identity.application.authenticator.push.common.exception.PushAuthTokenValidationException; -import org.wso2.carbon.identity.application.authenticator.push.common.impl.PushAuthContextManagerImpl; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.DeviceHandler; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerClientException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.exception.PushDeviceHandlerServerException; -import org.wso2.carbon.identity.application.authenticator.push.device.handler.impl.DeviceHandlerImpl; -import org.wso2.carbon.identity.application.authenticator.push.dto.AuthDataDTO; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.ciba.common.AuthReqStatus; -import org.wso2.carbon.identity.oauth.ciba.dao.CibaDAOFactory; -import org.wso2.carbon.identity.oauth.ciba.exceptions.CibaCoreException; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.HttpURLConnection; -import java.text.ParseException; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import static com.wso2.openbanking.accelerator.consent.extensions.ciba.authenticator.CIBAPushAuthenticator.createErrorResponse; - -/** - * Implementation class for the CIBA authentication endpoint API. - */ -@Path("/") -public class CIBAAuthenticationEndpoint { - - private static final Log log = LogFactory.getLog(CIBAAuthenticationEndpoint.class); - private static CIBAAuthenticationEndpointInterface cibaAuthenticationEndpointInterfaceTK; - private static List consentPersistSteps = null; - private static List consentRetrievalSteps = null; - - public CIBAAuthenticationEndpoint() { - - initializeConsentSteps(); - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is secured with access control lists in the configuration - // Suppressed warning count - 1 - @POST - @Path("/push-auth/authenticate") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response handleCIBAAuthenticationRequest(@Context HttpServletRequest request, - @Context HttpServletResponse response, @Context UriInfo uriInfo) { - - try { - log.info("CIBA authentication call received"); - handleMobileResponse(request, response); - } catch (CIBAAuthenticationEndpointException e) { - // create error response - CIBAAuthenticationEndpointErrorResponse errorResponse = createErrorResponse(e.getHttpStatusCode(), - e.getErrorCode(), e.getErrorDescription()); - return Response.status(errorResponse.getHttpStatusCode() != 0 ? - errorResponse.getHttpStatusCode() : e.getHttpStatusCode()) - .entity(errorResponse.getPayload()).build(); - } - - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is secured with access control lists in the configuration - // Suppressed warning count - 1 - @GET - @Path("/push-auth/discovery-data") - @Produces({"application/json; charset=utf-8"}) - public Response handleDiscoveryRequest(@Context HttpServletRequest request, - @Context HttpServletResponse response, - @Context HttpHeaders headers) { - - try { - log.info("CIBA discovery call received"); - JSONObject deviceRegistrationData = handleDiscovery(request, response, headers); - return Response.status(HttpStatus.SC_ACCEPTED) - .entity(deviceRegistrationData).build(); - - } catch (CIBAAuthenticationEndpointException e) { - // create error response - CIBAAuthenticationEndpointErrorResponse errorResponse = createErrorResponse(e.getHttpStatusCode(), - e.getErrorCode(), e.getErrorDescription()); - return Response.status(errorResponse.getHttpStatusCode() != 0 ? - errorResponse.getHttpStatusCode() : e.getHttpStatusCode()) - .entity(errorResponse.getPayload()).build(); - } - } - - @SuppressFBWarnings("HTTP_PARAMETER_POLLUTION") - // Suppressed content - CIBAAuthenticationEndpointConstants.DEVICE_REGISTRATION_URL - // Suppression reason - False Positive : This is a hard coded, trusted path. It is not a user input - // Suppressed warning count - 1 - private JSONObject handleDiscovery(HttpServletRequest request, HttpServletResponse response, HttpHeaders headers) - throws CIBAAuthenticationEndpointException { - - List authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION); - String userToken = null; - // Make the API call with user's access token - if (authHeaders.size() != 0) { - userToken = authHeaders.get(0); - } - String registrationUrl = CarbonUtils.getCarbonServerUrl() + - CIBAAuthenticationEndpointConstants.DEVICE_REGISTRATION_URL; - HttpUriRequest deviceRegistrationRequest = new HttpGet(registrationUrl); - deviceRegistrationRequest.setHeader(CIBAAuthenticationEndpointConstants.AUTH_HEADER_NAME, userToken); - JSONObject deviceRegistrationData = sendRequest(deviceRegistrationRequest); - // Change authentication endpoint to OB CIBA webapp as it handles the CIBA authenticate call - deviceRegistrationData.put(CIBAAuthenticationEndpointConstants.AUTHENTICATION_ENDPOINT, - CIBAAuthenticationEndpointConstants.AUTHENTICATION_ENDPOINT_URL_PREFIX - + deviceRegistrationData.getAsString( - CIBAAuthenticationEndpointConstants.AUTHENTICATION_ENDPOINT)); - return deviceRegistrationData; - } - - public JSONObject sendRequest(HttpUriRequest request) - throws CIBAAuthenticationEndpointException { - - String responseStr = null; - try { - CloseableHttpClient client = HTTPClientUtils.getHttpsClient(); - HttpResponse response = client.execute(request); - responseStr = EntityUtils.toString(response.getEntity()); - - if ((response.getStatusLine().getStatusCode() / 100) != 2) { - if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { - log.debug("Received unauthorized(401) response. body: " + responseStr); - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_UNAUTHORIZED, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_UNAUTHORIZED.getMessage(), - "Received unauthorized Response: " + responseStr); - } - } else { - // received success (200 range) response - Object responseJSON; - try { - responseJSON = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(responseStr); - if (!(responseJSON instanceof JSONObject)) { - log.error("Discovery call response is not a JSON object"); - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST.getMessage(), - "Discovery call response is not a JSON object"); - } - } catch (net.minidev.json.parser.ParseException e) { - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_SERVER_ERROR.getMessage(), - "Unable to parse the response", e); - } - - JSONObject responseData = (JSONObject) responseJSON; - return responseData; - } - - } catch (IOException e) { - log.error("Exception occurred while reading request. Caused by, ", e); - } catch (OpenBankingException e) { - log.error("Exception occurred while generating http client. Caused by, ", e); - } - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_SERVER_ERROR.getMessage(), - "Unexpected response received for the request. path: " + - request.getURI() + " response:" + responseStr); - } - - /** - * Initialize consent builder. - */ - private static synchronized void initializeConsentSteps() { - - if (consentRetrievalSteps == null || consentPersistSteps == null) { - ConsentStepsBuilder consentStepsBuilder = ConsentExtensionExporter.getConsentStepsBuilder(); - - if (consentStepsBuilder != null) { - consentRetrievalSteps = consentStepsBuilder.getConsentRetrievalSteps(); - consentPersistSteps = consentStepsBuilder.getConsentPersistSteps(); - } - - if (consentRetrievalSteps != null && !consentRetrievalSteps.isEmpty()) { - log.info("Consent retrieval steps are not null or empty"); - } else { - log.warn("Consent retrieval steps are null or empty"); - } - if (consentPersistSteps != null && !consentPersistSteps.isEmpty()) { - log.info("Consent persist steps are not null or empty"); - } else { - log.warn("Consent persist steps are null or empty"); - } - } else { - log.debug("Retrieval and persist steps are available"); - } - } - - /** - * Persist user consent data. - * - * @param request HTTP request - * @param response HTTP response - * @param sessionDataKey Session Data Key - * @param payload Json payload - * @throws ConsentException - */ - private static void persistConsent(HttpServletRequest request, HttpServletResponse response, - String sessionDataKey, JSONObject payload) throws ConsentException { - - ConsentData consentData = ConsentCache.getConsentDataFromCache(sessionDataKey); - if (consentData == null) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - - if (payload == null) { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - "Payload unavailable", consentData.getState()); - } - - boolean approval; - if (payload.containsKey(CIBAAuthenticationEndpointConstants.APPROVAL)) { - try { - if (payload.get(CIBAAuthenticationEndpointConstants.APPROVAL) instanceof Boolean) { - approval = (Boolean) payload.get(CIBAAuthenticationEndpointConstants.APPROVAL); - } else { - approval = Boolean.parseBoolean((String) payload.get(CIBAAuthenticationEndpointConstants.APPROVAL)); - } - } catch (ClassCastException e) { - log.error("Error while processing consent persistence authorize", e); - throw new ConsentException(ResponseStatus.BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_PERSIST_INVALID_AUTHORIZE.getMessage()); - } - } else { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_PERSIST_APPROVAL_MANDATORY.getMessage(), - consentData.getState()); - } - - Map headers = ConsentExtensionUtils.getHeaders(request); - ConsentPersistData consentPersistData = new ConsentPersistData(payload, headers, approval, consentData); - - executePersistence(consentPersistData); - - if (!approval) { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.ACCESS_DENIED, - "User denied the consent", consentData.getState()); - } - - } - - /** - * Execute consent persistence. - * - * @param consentPersistData Consent Persistence data - * @throws ConsentException - */ - private static void executePersistence(ConsentPersistData consentPersistData) throws ConsentException { - - for (ConsentPersistStep step : consentPersistSteps) { - if (log.isDebugEnabled()) { - log.debug("Executing persistence step " + step.getClass().toString()); - } - step.execute(consentPersistData); - } - } - - /** - * Handles authentication request received from mobile app. - * - * @param request HTTP request - * @param response HTTP response - * @throws CIBAAuthenticationEndpointException - */ - public static void handleMobileResponse(HttpServletRequest request, HttpServletResponse response) - throws CIBAAuthenticationEndpointException { - - setCIBAExtension(); - - String responseJsonString; - try { - responseJsonString = IOUtils.toString(request.getInputStream()); - } catch (IOException e) { - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST.getMessage(), - "Error in reading the request", e); - } - - if (log.isDebugEnabled()) { - log.debug("CIBA authenticate call from mobile received: " + responseJsonString); - } - - Object responseDataJSON; - try { - responseDataJSON = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(responseJsonString); - if (!(responseDataJSON instanceof JSONObject)) { - log.error("response is not a JSON object"); - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST.getMessage(), - "response is not a JSON object"); - } - } catch (net.minidev.json.parser.ParseException e) { - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_SERVER_ERROR.getMessage(), - "Unable to parse the response", e); - } - - JSONObject responseData = (JSONObject) responseDataJSON; - String token = responseData.getAsString(CIBAAuthenticationEndpointConstants.AUTH_RESPONSE); - - if (StringUtils.isEmpty(token)) { - if (log.isDebugEnabled()) { - log.debug(CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_AUTH_RESPONSE_TOKEN_NOT_FOUND); - } - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_AUTH_RESPONSE_TOKEN_NOT_FOUND - .getCode(), - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_AUTH_RESPONSE_TOKEN_NOT_FOUND - .getMessage()); - } else { - String deviceId = getDeviceIdFromToken(token); - String sessionDataKey = getSessionDataKeyFromToken(token, deviceId); - - if (StringUtils.isEmpty(sessionDataKey)) { - String errorMessage = CIBAAuthenticationEndpointConstants.ErrorMessages - .ERROR_CODE_SESSION_DATA_KEY_NOT_FOUND + deviceId; - if (log.isDebugEnabled()) { - log.debug(errorMessage); - } - - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_SESSION_DATA_KEY_NOT_FOUND - .getCode(), - errorMessage); - } else { - addToContext(sessionDataKey, token); - - try { - processAuthenticationRequest(request, response, sessionDataKey); - } catch (AuthenticationFailedException e) { - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST.getMessage(), - "Authentication Failed", e); - } - - response.setStatus(HttpServletResponse.SC_ACCEPTED); - - log.info("Completed processing authentication request from mobile app for session data key " - + sessionDataKey); - - } - } - } - - /** - * Retrieve the config for CIBA consent persistence toolkit extension class for. - */ - private static void setCIBAExtension() { - - try { - cibaAuthenticationEndpointInterfaceTK = (CIBAAuthenticationEndpointInterface) - Class.forName(OpenBankingConfigParser.getInstance() - .getCibaServletExtension()).getDeclaredConstructor().newInstance(); - } catch (InstantiationException | IllegalAccessException | - InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { - log.error("CIBA Webapp extension not found", e); - } - } - - /** - * Process authentication request received from mobile app. - * - * @param sessionDataKey Session Data Key - * @throws CIBAAuthenticationEndpointException - */ - protected static void processAuthenticationRequest(HttpServletRequest request, - HttpServletResponse response, String sessionDataKey) throws - AuthenticationFailedException, CIBAAuthenticationEndpointException { - - SessionDataCacheEntry cacheEntry = ConsentCache.getCacheEntryFromSessionDataKey(sessionDataKey); - - AuthenticatedUser user = cacheEntry.getLoggedInUser(); - - PushAuthContextManager contextManager = new PushAuthContextManagerImpl(); - AuthenticationContext sessionContext = contextManager.getContext(sessionDataKey); - AuthDataDTO authDataDTO = (AuthDataDTO) sessionContext - .getProperty(CIBAAuthenticationEndpointConstants.CONTEXT_AUTH_DATA); - - String authResponseToken = authDataDTO.getAuthToken(); - String serverChallenge = authDataDTO.getChallenge(); - - String deviceId = getDeviceIdFromToken(authResponseToken); - String publicKey = getPublicKey(deviceId); - - PushJWTValidator validator = new PushJWTValidator(); - JWTClaimsSet claimsSet; - try { - claimsSet = validator.getValidatedClaimSet(authResponseToken, publicKey); - } catch (PushAuthTokenValidationException e) { - String errorMessage = String - .format("Error occurred when trying to validate the JWT signature from device: %s of user: %s.", - deviceId, user.toFullQualifiedUsername()); - throw new AuthenticationFailedException(errorMessage, e); - } - if (claimsSet != null) { - if (validator.validateChallenge(claimsSet, serverChallenge, deviceId)) { - String authStatus; - String metadataJsonString; - JSONArray accountIds; - try { - authStatus = - validator.getClaimFromClaimSet(claimsSet, - CIBAAuthenticationEndpointConstants.TOKEN_RESPONSE, deviceId); - metadataJsonString = (validator.getClaimFromClaimSet(claimsSet, - CIBAAuthenticationEndpointConstants.METADATA, deviceId)); - - Object metadataJSON = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(metadataJsonString); - if (!(metadataJSON instanceof JSONObject)) { - log.error("metadata is not a JSON object"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, - "metadata is not a JSON object"); - } - JSONObject metadata = (JSONObject) metadataJSON; - - accountIds = - (JSONArray) metadata.get(CIBAAuthenticationEndpointConstants.METADATA_ACCOUNT_IDS); - } catch (PushAuthTokenValidationException | net.minidev.json.parser.ParseException e) { - String errorMessage = "Error in getting claims from the auth response token received from device: " - + deviceId; - throw new AuthenticationFailedException(errorMessage, e); - } - - boolean approval; - if (authStatus.equals(CIBAAuthenticationEndpointConstants.AUTH_REQUEST_STATUS_SUCCESS)) { - approval = true; - } else if (authStatus.equals(CIBAAuthenticationEndpointConstants.AUTH_REQUEST_STATUS_DENIED)) { - approval = false; - } else { - log.error("Invalid authorization status :" + authStatus); - String errorMessage = "Authentication failed! Incorrect auth status " + authStatus + " for user " + - user.toFullQualifiedUsername(); - throw new AuthenticationFailedException(errorMessage); - } - - JSONObject payload = new JSONObject(); - payload.put(CIBAAuthenticationEndpointConstants.APPROVAL, approval); - // Authorize call is skipped in consent persist call in CIBA - payload.put(CIBAAuthenticationEndpointConstants.AUTHORIZE, false); - payload.put(CIBAAuthenticationEndpointConstants.ACCOUNT_IDS, accountIds); - - // add TK data - if (cibaAuthenticationEndpointInterfaceTK != null) { - payload = cibaAuthenticationEndpointInterfaceTK - .updateConsentData(payload); - } - - persistConsent(request, response, sessionDataKey, payload); - persistAuthorization(sessionDataKey, authStatus); - } else { - String errorMessage = String - .format("Authentication failed! JWT challenge validation for device: %s of user: %s.", - deviceId, user); - throw new AuthenticationFailedException(errorMessage); - } - - } else { - String errorMessage = String - .format("Authentication failed! JWT signature is not valid for device: %s of user: %s.", - deviceId, user); - throw new AuthenticationFailedException(errorMessage); - } - - try { - contextManager.clearContext(validator.getClaimFromClaimSet(claimsSet, - CIBAAuthenticationEndpointConstants.TOKEN_SESSION_DATA_KEY, deviceId)); - } catch (PushAuthTokenValidationException e) { - String errorMessage = "Error in getting claim " + - CIBAAuthenticationEndpointConstants.TOKEN_SESSION_DATA_KEY + " from the auth response token " + - "received from device: " + deviceId; - throw new AuthenticationFailedException(errorMessage, e); - } - } - - /** - * Persist authorization response. - * - * @param sessionDataKey Session Data Key - * @param authStatus User action for the authorization request - * @throws CIBAAuthenticationEndpointException - */ - public static void persistAuthorization(String sessionDataKey, String authStatus) - throws CIBAAuthenticationEndpointException { - - SessionDataCacheEntry cacheEntry = ConsentCache.getCacheEntryFromSessionDataKey(sessionDataKey); - - if (cacheEntry != null) { - AuthenticatedUser user = cacheEntry.getLoggedInUser(); - OAuth2Parameters oAuth2Parameters = cacheEntry.getoAuth2Parameters(); - String nonce = oAuth2Parameters.getNonce(); - - try { - if (CIBAAuthenticationEndpointConstants.AUTH_REQUEST_STATUS_SUCCESS.equals(authStatus)) { - String authCodeKey = CibaDAOFactory.getInstance().getCibaAuthMgtDAO().getCibaAuthCodeKey(nonce); - - // Update successful authentication. - CibaDAOFactory.getInstance().getCibaAuthMgtDAO() - .persistAuthenticationSuccess(authCodeKey, user); - } else if (CIBAAuthenticationEndpointConstants.AUTH_REQUEST_STATUS_DENIED.equals(authStatus)) { - String authCodeKey = CibaDAOFactory.getInstance().getCibaAuthMgtDAO().getCibaAuthCodeKey(nonce); - CibaDAOFactory.getInstance().getCibaAuthMgtDAO().updateStatus(authCodeKey, AuthReqStatus.FAILED); - } else { - String errorMessage = "Invalid authorization status: " + authStatus; - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_BAD_REQUEST, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST.getMessage(), - errorMessage); - } - } catch (CibaCoreException e) { - String errorMessage = "Error while persisting CIBA auth status for session data key " + sessionDataKey; - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_SERVER_ERROR.getMessage(), - errorMessage, e); - } - } - } - - /** - * Derive the Device ID from the auth response token header. - * - * @param token Auth response token - * @return Device ID - * @throws CIBAAuthenticationEndpointException if the token string fails to parse to JWT - */ - protected static String getDeviceIdFromToken(String token) throws CIBAAuthenticationEndpointException { - - try { - return String.valueOf(JWTParser.parse(token).getHeader().getCustomParam( - CIBAAuthenticationEndpointConstants.TOKEN_DEVICE_ID)); - } catch (ParseException e) { - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_GET_DEVICE_ID_FAILED.getCode(), - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_GET_DEVICE_ID_FAILED.getMessage(), - e); - } - } - - /** - * Derive the SessionDataKey from the auth response token. - * - * @param token Auth response token - * @param deviceId Unique ID of the device trying to authenticate - * @return SessionDataKey - * @throws CIBAAuthenticationEndpointException if the auth response token fails to parse to JWT or the public key - * for the device is not retrieved or if the token is not valid - */ - private static String getSessionDataKeyFromToken(String token, String deviceId) throws - CIBAAuthenticationEndpointException { - - DeviceHandler deviceHandler = new DeviceHandlerImpl(); - PushJWTValidator validator = new PushJWTValidator(); - - try { - String publicKey = deviceHandler.getPublicKey(deviceId); - JWTClaimsSet claimsSet = validator.getValidatedClaimSet(token, publicKey); - return claimsSet.getStringClaim(CIBAAuthenticationEndpointConstants.TOKEN_SESSION_DATA_KEY); - } catch (PushDeviceHandlerServerException | PushDeviceHandlerClientException e) { - String errorMessage = CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_GET_PUBLIC_KEY_FAILED - .toString() + deviceId; - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_GET_PUBLIC_KEY_FAILED.getCode(), - errorMessage, e); - } catch (PushAuthTokenValidationException e) { - String errorMessage = CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_TOKEN_VALIDATION_FAILED - .toString() + deviceId; - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_TOKEN_VALIDATION_FAILED.getCode(), - errorMessage, e); - } catch (ParseException e) { - throw new CIBAAuthenticationEndpointException(HttpStatus.SC_INTERNAL_SERVER_ERROR, - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_PARSE_JWT_FAILED.getCode(), - CIBAAuthenticationEndpointConstants.ErrorMessages.ERROR_CODE_PARSE_JWT_FAILED.getMessage(), e); - } - } - - /** - * Add the received auth response token to the authentication context. - * - * @param sessionDataKey Unique key to identify the session - * @param token Auth response token - */ - private static void addToContext(String sessionDataKey, String token) { - - PushAuthContextManager contextManager = new PushAuthContextManagerImpl(); - AuthenticationContext context = contextManager.getContext(sessionDataKey); - - AuthDataDTO authDataDTO = (AuthDataDTO) context - .getProperty(CIBAAuthenticationEndpointConstants.CONTEXT_AUTH_DATA); - authDataDTO.setAuthToken(token); - context.setProperty(CIBAAuthenticationEndpointConstants.CONTEXT_AUTH_DATA, authDataDTO); - contextManager.storeContext(sessionDataKey, context); - } - - /** - * Get the public key for the device by the device ID. - * - * @param deviceId Unique ID for the device - * @return Public key string - * @throws AuthenticationFailedException if an error occurs while getting the public key - */ - protected static String getPublicKey(String deviceId) throws AuthenticationFailedException { - - DeviceHandler deviceHandler = new DeviceHandlerImpl(); - try { - return deviceHandler.getPublicKey(deviceId); - } catch (PushDeviceHandlerServerException | PushDeviceHandlerClientException e) { - throw new AuthenticationFailedException("Error occurred when trying to get the public key for device: " - + deviceId + "."); - } - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/api/CIBAAuthenticationEndpointConstants.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/api/CIBAAuthenticationEndpointConstants.java deleted file mode 100644 index ee363306..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/api/CIBAAuthenticationEndpointConstants.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba.authentication.endpoint.impl.api; - -/** - * Constants for CIBA authentication endpoint. - */ -public class CIBAAuthenticationEndpointConstants { - - // request related constants - public static final String AUTH_RESPONSE = "authResponse"; - public static final String TOKEN_DEVICE_ID = "did"; - public static final String TOKEN_SESSION_DATA_KEY = "sid"; - public static final String CONTEXT_AUTH_DATA = "authData"; - public static final String TOKEN_RESPONSE = "res"; - public static final String METADATA = "mta"; - public static final String AUTH_REQUEST_STATUS_SUCCESS = "SUCCESSFUL"; - public static final String AUTH_REQUEST_STATUS_DENIED = "DENIED"; - - // device registration related constants - public static final String DEVICE_REGISTRATION_URL = "/api/users/v1/me/push-auth/discovery-data"; - public static final String AUTHENTICATION_ENDPOINT_URL_PREFIX = "/api/openbanking/ciba"; - public static final String AUTHENTICATION_ENDPOINT = "ae"; - public static final String AUTH_HEADER_NAME = "Authorization"; - - // consent related constants - public static final String APPROVAL = "approval"; - public static final String AUTHORIZE = "authorize"; - public static final String ACCOUNT_IDS = "accountIds"; - public static final String METADATA_ACCOUNT_IDS = "approvedAccountIds"; - - /** - * Enum which contains error codes and corresponding error messages. - */ - public enum ErrorMessages { - - ERROR_CODE_AUTH_RESPONSE_TOKEN_NOT_FOUND( - "PBA-15001", - "The request did not contain an authentication response token" - ), - ERROR_CODE_SESSION_DATA_KEY_NOT_FOUND( - "PBA-15002", - "Session data key is not present in the authentication response token received from device: " - ), - ERROR_CODE_GET_DEVICE_ID_FAILED( - "PBA-15003", - "Error occurred when extracting the auth response token." - ), - ERROR_CODE_GET_PUBLIC_KEY_FAILED( - "PBA-15004", - "Error occurred when trying to get the public key from device: " - ), - ERROR_CODE_TOKEN_VALIDATION_FAILED( - "PBA-15005", - "Error occurred when validating auth response token from device: " - ), - ERROR_CODE_PARSE_JWT_FAILED( - "PBA-15006", - "Error occurred when parsing auth response token to JWT." - ), - ERROR_PERSIST_INVALID_AUTHORIZE( - "400", "Invalid value for authorize. Should be true/false" - ), - ERROR_PERSIST_APPROVAL_MANDATORY( - "400", "Mandatory body parameter approval is unavailable" - ), - ERROR_CODE_SERVER_ERROR( - "500", "internal server error" - ), - ERROR_CODE_BAD_REQUEST( - "400", "Bad Request" - ), - ERROR_CODE_UNAUTHORIZED( - "401", "Unauthorized" - ); - - private final String code; - private final String message; - - ErrorMessages(String code, String message) { - - this.code = code; - this.message = message; - } - - public String getCode() { - - return code; - } - - public String getMessage() { - - return message; - } - - @Override - public String toString() { - - return code + " - " + message; - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/exception/CIBAAuthenticationEndpointException.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/exception/CIBAAuthenticationEndpointException.java deleted file mode 100644 index ad88ac80..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/java/com/wso2/openbanking/accelerator/ciba/authentication/endpoint/impl/exception/CIBAAuthenticationEndpointException.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.ciba.authentication.endpoint.impl.exception; - -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; - -/** - * Exception for CIBA authentication endpoint. - */ -public class CIBAAuthenticationEndpointException extends OpenBankingException { - - private String errorDescription; - private String errorCode; - private int httpStatusCode; - - public int getHttpStatusCode() { - - return httpStatusCode; - } - - public void setHttpStatusCode(int httpStatusCode) { - - this.httpStatusCode = httpStatusCode; - } - - public String getErrorDescription() { - - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - - this.errorDescription = errorDescription; - } - - public String getErrorCode() { - - return errorCode; - } - - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - - public CIBAAuthenticationEndpointException(int httpStatusCode, String errorCode, String errorDescription, - Throwable e) { - - super(errorDescription, e); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - this.httpStatusCode = httpStatusCode; - - } - - public CIBAAuthenticationEndpointException(int httpStatusCode, String errorCode, String errorDescription) { - - super(errorDescription); - this.errorDescription = errorDescription; - this.errorCode = errorCode; - this.httpStatusCode = httpStatusCode; - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/META-INF/MANIFEST.mf b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/META-INF/MANIFEST.mf deleted file mode 100644 index 9d885be5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/META-INF/MANIFEST.mf +++ /dev/null @@ -1 +0,0 @@ -Manifest-Version: 1.0 diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index b212826c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index bd83ba12..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 231ed2d8..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.ciba.authentication.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - WSO2 Open Banking - CIBA Authentication Endpoint - WSO2 Open Banking - CIBA Authentication Endpoint - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/pom.xml deleted file mode 100644 index 6c08ef40..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/pom.xml +++ /dev/null @@ -1,181 +0,0 @@ - - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - - openbanking-consent-endpoint - war - WSO2 Open Banking - Consent Endpoint - - - - io.swagger - swagger-jaxrs - - - javax.ws.rs - jsr311-api - - - com.google.guava - guava - - - org.yaml - snakeyaml - - - - - net.minidev - json-smart - provided - - - org.testng - testng - test - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - - - org.slf4j - slf4j-api - - - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.dao - - - org.slf4j - slf4j-api - - - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.service - - - org.slf4j - slf4j-api - - - provided - - - org.wso2.carbon.identity.local.auth.api - org.wso2.carbon.identity.local.auth.api.core - - - org.slf4j - slf4j-api - - - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.extensions - - - org.slf4j - slf4j-api - - - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#consent - WEB-INF/lib/slf4j-api-*.jar - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentAdminEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentAdminEndpoint.java deleted file mode 100644 index fca2ecd5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentAdminEndpoint.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.api; - -import com.wso2.openbanking.accelerator.consent.endpoint.util.ConsentUtils; -import com.wso2.openbanking.accelerator.consent.extensions.admin.builder.ConsentAdminBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.admin.model.ConsentAdminData; -import com.wso2.openbanking.accelerator.consent.extensions.admin.model.ConsentAdminHandler; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * ConsentSearchEndpoint. - *

- * This specifies a RESTful API for consent search to be used at consent user and customer service portals. - */ -@SuppressFBWarnings("JAXRS_ENDPOINT") -// Suppressed content - Endpoints -// Suppression reason - False Positive : These endpoints are secured with access control -// as defined in the IS deployment.toml file -// Suppressed warning count - 7 -@Path("/admin") -public class ConsentAdminEndpoint { - - private static final Log log = LogFactory.getLog(ConsentAdminEndpoint.class); - - private static ConsentAdminHandler consentAdminHandler = null; - - public ConsentAdminEndpoint() { - if (consentAdminHandler == null) { - initializeConsentAdminHandler(); - } - } - - private static void initializeConsentAdminHandler() { - ConsentAdminBuilder consentAdminBuilder = ConsentExtensionExporter.getConsentAdminBuilder(); - - if (consentAdminBuilder != null) { - consentAdminHandler = consentAdminBuilder.getConsentAdminHandler(); - } - - if (consentAdminHandler != null) { - log.info("Consent admin handler " + consentAdminHandler.getClass().getName() + "initialized"); - } else { - log.warn("Consent admin handler is null"); - } - } - - /** - * Search consent data. - */ - @GET - @Path("/search") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response search(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleSearch(consentAdminData); - return sendResponse(consentAdminData); - } - - - /** - * Search consent status audit records. - */ - @GET - @Path("/search/consent-status-audit") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response searchConsentStatusAudit(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleConsentStatusAuditSearch(consentAdminData); - return sendResponse(consentAdminData); - } - - /** - * Search consent file. - */ - @GET - @Path("/search/consent-file") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response searchConsentFile(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleConsentFileSearch(consentAdminData); - return sendResponse(consentAdminData); - } - - /** - * Get consent amendment history. - */ - @GET - @Path("/consent-amendment-history") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response getConsentAmendmentHistoryById(@Context HttpServletRequest request, - @Context HttpServletResponse response, @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleConsentAmendmentHistoryRetrieval(consentAdminData); - return sendResponse(consentAdminData); - } - - /** - * Revoke consent data. - */ - @DELETE - @Path("/revoke") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response revoke(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - ConsentUtils.getJSONObjectPayload(request), uriInfo.getQueryParameters(), - uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleRevoke(consentAdminData); - return sendResponse(consentAdminData); - } - - /** - * Invoke consent expiration task. - */ - @GET - @Path("/expire-consents") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response expireConsents(@Context HttpServletRequest request, - @Context HttpServletResponse response, @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleConsentExpiry(consentAdminData); - return sendResponse(consentAdminData); - } - - /** - * Invoke retention data db sync task. - */ - @GET - @Path("/sync-temporary-retention-data") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response syncTemporaryRetentionData(@Context HttpServletRequest request, - @Context HttpServletResponse response, @Context UriInfo uriInfo) { - - ConsentAdminData consentAdminData = new ConsentAdminData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getAbsolutePath().getPath(), request, response); - consentAdminHandler.handleTemporaryRetentionDataSyncing(consentAdminData); - return sendResponse(consentAdminData); - } - - private Response sendResponse(ConsentAdminData consentAdminData) { - if (consentAdminData.getPayload() != null || consentAdminData.getResponseStatus() != null) { - return Response.status(consentAdminData.getResponseStatus().getStatusCode()). - entity(consentAdminData.getResponsePayload()).build(); - } else { - log.debug("Response status or payload unavailable. Throwing exception"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Response data unavailable"); - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentAuthorizeEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentAuthorizeEndpoint.java deleted file mode 100644 index 0dc62439..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentAuthorizeEndpoint.java +++ /dev/null @@ -1,361 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.api; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.consent.endpoint.util.ConsentConstants; -import com.wso2.openbanking.accelerator.consent.endpoint.util.ConsentUtils; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.builder.ConsentStepsBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistData; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentPersistStep; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentRetrievalStep; -import com.wso2.openbanking.accelerator.consent.extensions.common.AuthErrorCode; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentCache; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.swagger.jaxrs.PATCH; -import net.minidev.json.JSONObject; -import net.minidev.json.JSONValue; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -/** - * ConsentAuthorizeEndpoint. - * This specifies a RESTful API to be used in a code/hybrid flow consent approval. - */ -@SuppressFBWarnings("JAXRS_ENDPOINT") -// Suppressed content - Endpoints -// Suppression reason - False Positive : These endpoints are secured with access control -// as defined in the IS deployment.toml file -// Suppressed warning count - 2 -@Path("/authorize") -public class ConsentAuthorizeEndpoint { - - private static final Log log = LogFactory.getLog(ConsentAuthorizeEndpoint.class); - - private static final String ERROR_PERSIST_INVALID_APPROVAL = "Invalid value for approval. Should be true/false"; - private static final String ERROR_PERSIST_APPROVAL_MANDATORY = "Mandatory body parameter approval is unavailable"; - private static final String ERROR_NO_TYPE_AND_APP_DATA = "Type and application data is unavailable"; - private static final String ERROR_SERVER_ERROR = "Internal server error"; - private static final String ERROR_NO_DATA_IN_SESSION_CACHE = - "Data unavailable in session cache corresponding to the key provided"; - private static final String ERROR_CONSENT_DATA_RETRIEVAL = "Error while retrieving data consent data"; - private static final String ERROR_INVALID_VALUE_FOR_AUTHORIZE_PARAM = "\"authorize\" parameter is not defined " + - "properly or invalid"; - private static final int STATUS_FOUND = 302; - private static final String IS_ERROR = "isError"; - private static final String APPROVAL = "approval"; - private static final String COOKIES = "cookies"; - private static List consentPersistSteps = null; - private static List consentRetrievalSteps = null; - private static ConsentCoreServiceImpl consentCoreService = new ConsentCoreServiceImpl(); - private static final String preserveConsent = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(ConsentConstants.PRESERVE_CONSENT); - private static final boolean storeConsent = preserveConsent == null ? false : Boolean.parseBoolean(preserveConsent); - - public ConsentAuthorizeEndpoint() { - initializeConsentSteps(); - } - - private static synchronized void initializeConsentSteps() { - - if (consentRetrievalSteps == null || consentPersistSteps == null) { - ConsentStepsBuilder consentStepsBuilder = ConsentExtensionExporter.getConsentStepsBuilder(); - - if (consentStepsBuilder != null) { - consentRetrievalSteps = consentStepsBuilder.getConsentRetrievalSteps(); - consentPersistSteps = consentStepsBuilder.getConsentPersistSteps(); - } - - if (consentRetrievalSteps != null && !consentRetrievalSteps.isEmpty()) { - log.info("Consent retrieval steps are not null or empty"); - } else { - log.warn("Consent retrieval steps are null or empty"); - } - if (consentPersistSteps != null && !consentPersistSteps.isEmpty()) { - log.info("Consent persist steps are not null or empty"); - } else { - log.warn("Consent persist steps are null or empty"); - } - } else { - log.debug("Retrieval and persist steps are available"); - } - } - - /** - * Retrieve data for consent page. - */ - @GET - @Path("/retrieve/{session-data-key}") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response retrieve(@Context HttpServletRequest request, @Context HttpServletResponse response, - @PathParam("session-data-key") String sessionDataKey) throws ConsentException, - ConsentManagementException { - - String loggedInUser; - String app; - String spQueryParams; - String scopeString; - - SessionDataCacheEntry cacheEntry = ConsentCache.getCacheEntryFromSessionDataKey(sessionDataKey); - OAuth2Parameters oAuth2Parameters = cacheEntry.getoAuth2Parameters(); - URI redirectURI; - try { - redirectURI = new URI(oAuth2Parameters.getRedirectURI()); - } catch (URISyntaxException e) { - //Unlikely to happen. In case it happens, error response is sent - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Invalid redirect URI"); - } - //Extracting client ID for regulatory identification and redirect URI for error redirects - String clientId = oAuth2Parameters.getClientId(); - String state = oAuth2Parameters.getState(); - - Map sensitiveDataMap = - ConsentExtensionUtils.getSensitiveDataWithConsentKey(sessionDataKey); - - if ("false".equals(sensitiveDataMap.get(IS_ERROR))) { - loggedInUser = (String) sensitiveDataMap.get("loggedInUser"); - app = (String) sensitiveDataMap.get("application"); - spQueryParams = (String) sensitiveDataMap.get("spQueryParams"); - scopeString = (String) sensitiveDataMap.get("scope"); - if (!scopeString.contains("openid")) { - String[] scopes = cacheEntry.getParamMap().get("scope"); - if (scopes != null && scopes.length != 0 && scopes[0].contains("openid")) { - scopeString = scopes[0]; - } - } - } else { - String isError = (String) sensitiveDataMap.get(IS_ERROR); - //Have to throw standard error because cannot access redirect URI with this error - log.error("Error while getting endpoint parameters. " + isError); - throw new ConsentException(redirectURI, AuthErrorCode.SERVER_ERROR, ERROR_SERVER_ERROR, state); - } - - JSONObject jsonObject = new JSONObject(); - ConsentData consentData = new ConsentData(sessionDataKey, loggedInUser, spQueryParams, scopeString, app, - ConsentExtensionUtils.getHeaders(request)); - consentData.setSensitiveDataMap(sensitiveDataMap); - consentData.setRedirectURI(redirectURI); - - if (clientId == null) { - log.error("Client Id not available"); - //Unlikely error. Included just in case. - throw new ConsentException(redirectURI, AuthErrorCode.SERVER_ERROR, ERROR_SERVER_ERROR, state); - } - consentData.setClientId(clientId); - consentData.setState(state); - - try { - consentData.setRegulatory(IdentityCommonUtil.getRegulatoryFromSPMetaData(clientId)); - } catch (OpenBankingException e) { - log.error("Error while getting regulatory data", e); - throw new ConsentException(redirectURI, AuthErrorCode.SERVER_ERROR, "Error while obtaining regulatory data", - state); - } - - executeRetrieval(consentData, jsonObject); - if (consentData.getType() == null || consentData.getApplication() == null) { - log.error(ERROR_NO_TYPE_AND_APP_DATA); - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - ERROR_SERVER_ERROR, state); - } - ConsentExtensionUtils.setCommonDataToResponse(consentData, jsonObject); - Gson gson = new Gson(); - String consent = gson.toJson(consentData); - Map authorizeData = new HashMap<>(); - authorizeData.put(consentData.getSessionDataKey(), consent); - ConsentCache.addConsentDataToCache(sessionDataKey, consentData); - if (storeConsent) { - if (consentCoreService.getConsentAttributesByName(sessionDataKey).isEmpty()) { - consentCoreService.storeConsentAttributes(consentData.getConsentId(), authorizeData); - } - } - return Response.ok(jsonObject.toJSONString(), MediaType.APPLICATION_JSON).build(); - } - - /** - * Persist user consent data. - */ - @PATCH - @Path("/persist/{session-data-key}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response persist(@Context HttpServletRequest request, @Context HttpServletResponse response, - @PathParam("session-data-key") String sessionDataKey, - @QueryParam("authorize") String authorize) - throws ConsentException, ConsentManagementException, URISyntaxException { - - ConsentData consentData = ConsentCache.getConsentDataFromCache(sessionDataKey); - URI location; - try { - if (consentData == null) { - if (storeConsent) { - Map consentDetailsMap = - consentCoreService.getConsentAttributesByName(sessionDataKey); - if (consentDetailsMap.isEmpty()) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - Set keys = consentDetailsMap.keySet(); - String consentId = new ArrayList<>(keys).get(0); - JsonObject consentDetails = new JsonParser() - .parse(consentDetailsMap.get(consentId)).getAsJsonObject(); - consentData = ConsentUtils.getConsentDataFromAttributes(consentDetails, sessionDataKey); - - if (consentDetailsMap.isEmpty()) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - } else { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to get consent data"); - } - } - JSONObject payload; - try { - payload = ConsentUtils.getJSONObjectPayload(request); - } catch (ConsentException e) { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - ERROR_NO_DATA_IN_SESSION_CACHE, consentData.getState()); - } - Map headers = ConsentExtensionUtils.getHeaders(request); - - if (payload == null) { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - "Payload unavailable", consentData.getState()); - } - - boolean approval; - if (payload.containsKey(APPROVAL)) { - try { - if (payload.get(APPROVAL) instanceof Boolean) { - approval = (Boolean) payload.get(APPROVAL); - } else { - approval = Boolean.parseBoolean((String) payload.get(APPROVAL)); - } - } catch (ClassCastException e) { - log.error("Error while processing consent persistence approval", e); - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - ERROR_PERSIST_INVALID_APPROVAL, consentData.getState()); - } - } else { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - ERROR_PERSIST_APPROVAL_MANDATORY, consentData.getState()); - } - - ConsentPersistData consentPersistData = new ConsentPersistData(payload, headers, approval, consentData); - - if (payload.containsKey(COOKIES)) { - consentPersistData.setBrowserCookies((Map) payload.get(COOKIES)); - } - - executePersistence(consentPersistData); - - if (!approval) { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.ACCESS_DENIED, - "User denied the consent", consentData.getState()); - } else if (authorize != null && !StringUtils.equals("true", authorize)) { - if (StringUtils.equals(StringUtils.EMPTY, authorize) || !StringUtils.equals("false", authorize)) { - /* "authorize" parameter comes as an empty string only when a value was not defined for the parameter in - the URL. Throwing an error since a value must be present for the query parameter. Also, the value should - only be true or false */ - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.INVALID_REQUEST, - ERROR_INVALID_VALUE_FOR_AUTHORIZE_PARAM, consentData.getState()); - } else { - return Response.ok().build(); - } - } else { - location = ConsentUtils.authorizeRequest(Boolean.toString(consentPersistData.getApproval()) - , consentPersistData.getBrowserCookies(), consentData); - } - } finally { - if (storeConsent && consentData != null) { - // remove all session data related to the consent from consent attributes - ArrayList keysToDelete = new ArrayList<>(); - - Map consentAttributes = consentCoreService. - getConsentAttributes(consentData.getConsentId()).getConsentAttributes(); - - consentAttributes.forEach((key, value) -> { - if (JSONValue.isValidJson(value) && value.contains("sessionDataKey")) { - keysToDelete.add(key); - } - }); - - consentCoreService.deleteConsentAttributes(consentData.getConsentId(), - keysToDelete); - } - } - - return Response.status(STATUS_FOUND).location(location).build(); - } - - private void executeRetrieval(ConsentData consentData, JSONObject jsonObject) throws ConsentException { - - for (ConsentRetrievalStep step : consentRetrievalSteps) { - if (log.isDebugEnabled()) { - log.debug("Executing retrieval step " + step.getClass().toString()); - } - step.execute(consentData, jsonObject); - } - } - - private void executePersistence(ConsentPersistData consentPersistData) throws ConsentException { - - for (ConsentPersistStep step : consentPersistSteps) { - if (log.isDebugEnabled()) { - log.debug("Executing persistence step " + step.getClass().toString()); - } - step.execute(consentPersistData); - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentManageEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentManageEndpoint.java deleted file mode 100644 index f8054cba..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentManageEndpoint.java +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.api; - -import com.wso2.openbanking.accelerator.consent.endpoint.util.ConsentUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.manage.builder.ConsentManageBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageData; -import com.wso2.openbanking.accelerator.consent.extensions.manage.model.ConsentManageHandler; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.swagger.jaxrs.PATCH; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * ConsentManageEndpoint. - *

- * This specifies a RESTful API for Open Banking specification based consent requests. - */ -@SuppressFBWarnings("JAXRS_ENDPOINT") -// Suppressed content - Endpoints -// Suppression reason - False Positive : These endpoints are secured with access control -// as defined in the IS deployment.toml file -// Suppressed warning count - 7 -@Path("/manage") -public class ConsentManageEndpoint { - - private static final Log log = LogFactory.getLog(ConsentManageEndpoint.class); - - private static ConsentManageHandler consentManageHandler = null; - private static final String CLIENT_ID_HEADER = "x-wso2-client-id"; - - public ConsentManageEndpoint() { - if (consentManageHandler == null) { - initializeConsentManageHandler(); - } - } - - private static void initializeConsentManageHandler() { - ConsentManageBuilder consentManageBuilder = ConsentExtensionExporter.getConsentManageBuilder(); - - if (consentManageBuilder != null) { - consentManageHandler = consentManageBuilder.getConsentManageHandler(); - } - - if (consentManageHandler != null) { - log.info("Consent manage handler " + consentManageHandler.getClass().getName() + "initialized"); - } else { - log.warn("Consent manage handler is null"); - } - } - - /** - * Consent GET requests. - */ - @GET - @Path("/{s:.*}") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response manageGet(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handleGet(consentManageData); - return sendResponse(consentManageData); - } - - /** - * Consent POST requests. - */ - @POST - @Path("/{s:.*}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response managePost(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - ConsentUtils.getPayload(request), uriInfo.getQueryParameters(), - uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handlePost(consentManageData); - return sendResponse(consentManageData); - } - - /** - * Consent DELETE requests. - */ - @DELETE - @Path("/{s:.*}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response manageDelete(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - ConsentUtils.getPayload(request), uriInfo.getQueryParameters(), - uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handleDelete(consentManageData); - return sendResponse(consentManageData); - } - - /** - * Consent PUT requests. - */ - @PUT - @Path("/{s:.*}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response managePut(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - ConsentUtils.getPayload(request), uriInfo.getQueryParameters(), - uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handlePut(consentManageData); - return sendResponse(consentManageData); - } - - /** - * Consent PATCH requests. - */ - @PATCH - @Path("/{s:.*}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response managePatch(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - ConsentUtils.getPayload(request), uriInfo.getQueryParameters(), - uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handlePatch(consentManageData); - return sendResponse(consentManageData); - } - - /** - * Consent File Upload POST requests. - */ - @POST - @Path("/fileUpload/{s:.*}") - @Consumes({"*/*"}) - @Produces({"application/json; charset=utf-8"}) - public Response manageFileUploadPost(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - ConsentUtils.getFileUploadPayload(request), uriInfo.getQueryParameters(), - uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handleFileUploadPost(consentManageData); - return sendFileUploadResponse(consentManageData); - } - - /** - * Consent File GET requests. - */ - @GET - @Path("/fileUpload/{s:.*}") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"*/*"}) - public Response manageFileGet(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - ConsentManageData consentManageData = new ConsentManageData(ConsentExtensionUtils.getHeaders(request), - uriInfo.getQueryParameters(), uriInfo.getPathParameters().getFirst("s"), request, response); - consentManageData.setClientId(consentManageData.getHeaders().get(CLIENT_ID_HEADER)); - consentManageHandler.handleFileGet(consentManageData); - return sendResponse(consentManageData); - } - - private Response sendResponse(ConsentManageData consentManageData) { - if (consentManageData.getPayload() != null || consentManageData.getResponseStatus() != null) { - return Response.status(consentManageData.getResponseStatus().getStatusCode()). - entity(consentManageData.getResponsePayload()).build(); - } else { - log.debug("Response status or payload unavailable. Throwing exception"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Response data unavailable"); - } - } - - private Response sendFileUploadResponse(ConsentManageData consentManageData) { - if (consentManageData.getPayload() != null || consentManageData.getResponseStatus() != null) { - return Response.status(consentManageData.getResponseStatus().getStatusCode()).build(); - } else { - log.debug("Response status or payload unavailable. Throwing exception"); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Response data unavailable"); - } - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentValidationEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentValidationEndpoint.java deleted file mode 100644 index 49698e92..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/api/ConsentValidationEndpoint.java +++ /dev/null @@ -1,200 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.api; - -import com.wso2.openbanking.accelerator.common.exception.ConsentManagementException; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.consent.endpoint.util.ConsentUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionExporter; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentExtensionUtils; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.extensions.validate.builder.ConsentValidateBuilder; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidateData; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidationResult; -import com.wso2.openbanking.accelerator.consent.extensions.validate.model.ConsentValidator; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.DetailedConsentResource; -import com.wso2.openbanking.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; - -/** - * ConsentValidationEndpoint. - * - * This specifies a RESTful API for consent validation to be used at consent enforcement of resource - * retrieval/submission requests. - */ -@SuppressFBWarnings("JAXRS_ENDPOINT") -// Suppressed content - Endpoints -// Suppression reason - False Positive : These endpoints are secured with access control -// as defined in the IS deployment.toml file -// Suppressed warning count - 1 -@Path("/validate") -public class ConsentValidationEndpoint { - - private static final Log log = LogFactory.getLog(ConsentValidationEndpoint.class); - private static final ConsentCoreServiceImpl consentCoreService = new ConsentCoreServiceImpl(); - - private static ConsentValidator consentValidator = null; - private static String requestSignatureAlias; - - public ConsentValidationEndpoint() { - if (consentValidator == null) { - initializeConsentValidator(); - } - } - - private static void initializeConsentValidator() { - ConsentValidateBuilder consentValidateBuilder = ConsentExtensionExporter.getConsentValidateBuilder(); - - if (consentValidateBuilder != null) { - consentValidator = consentValidateBuilder.getConsentValidator(); - requestSignatureAlias = consentValidateBuilder.getRequestSignatureAlias(); - log.info("Consent validator " + consentValidator.getClass().getName() + "initialized"); - } - - if (consentValidator != null) { - log.info("Consent validator " + consentValidator.getClass().getName() + "initialized"); - } else { - log.warn("Consent validator is null"); - } - } - - /** - * Validate by sending consent data. - */ - @POST - @Path("/") - @Consumes({"application/jwt; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response validate(@Context HttpServletRequest request, @Context HttpServletResponse response) { - - String payload = ConsentUtils.getStringPayload(request); - JSONObject requestData; - Object requestDataObj; - - if (IdentityCommonUtil.getConsentJWTPayloadValidatorConfigEnabled()) { - try { - IdentityCommonUtil.validateJWTSignatureWithPublicKey(payload, requestSignatureAlias); - requestData = JWTUtils.decodeRequestJWT(payload, "body"); - } catch (OpenBankingException e) { - log.error("Error while validating JWT signature", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Error while validating JWT " + - "signature"); - } catch (ParseException e) { - log.error("Error while decoding validation JWT", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Error while decoding validation JWT"); - } - } else { - try { - requestDataObj = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(payload); - } catch (net.minidev.json.parser.ParseException e) { - log.error("Unable to parse the request payload", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Unable to parse the request payload"); - } - if (!(requestDataObj instanceof JSONObject)) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Payload is not a JSON object"); - } else { - requestData = (JSONObject) requestDataObj; - } - } - - JSONObject requestHeaders = (JSONObject) requestData.get("headers"); - Set headerNames = requestHeaders.keySet(); - Iterator headersIterator = headerNames.iterator(); - TreeMap headersMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - while (headersIterator.hasNext()) { - String headerName = headersIterator.next(); - headersMap.put(headerName, requestHeaders.getAsString(headerName)); - } - - JSONObject requestPayload = (JSONObject) requestData.get("body"); - String requestPath = requestData.getAsString("electedResource"); - String consentId = requestData.getAsString("consentId"); - String userId = requestData.getAsString("userId"); - String clientId = null; - if (requestData.containsKey("clientId")) { - clientId = requestData.getAsString("clientId"); - } - Map resourceParams = (Map) requestData.get("resourceParams"); - - if (consentId == null) { - throw new ConsentException(ResponseStatus.BAD_REQUEST, "Consent Id is mandatory for consent validation"); - } - - try { - //Adding query parameters to the resource map - resourceParams = ConsentUtils.addQueryParametersToResourceParamMap(resourceParams); - } catch (URISyntaxException e) { - log.error("Error while extracting query parameters", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Error while extracting query parameters"); - } - - ConsentValidateData consentValidateData = new ConsentValidateData(requestHeaders, requestPayload, - requestPath, consentId, userId, clientId, resourceParams, headersMap); - - try { - DetailedConsentResource consentResource = consentCoreService.getDetailedConsent(consentId); - consentValidateData.setComprehensiveConsent(consentResource); - } catch (ConsentManagementException e) { - log.error("Exception while getting consent", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Exception while getting consent"); - } - - ConsentValidationResult validationResult = new ConsentValidationResult(); - consentValidator.validate(consentValidateData, validationResult); - - JSONObject information = ConsentExtensionUtils.detailedConsentToJSON( - consentValidateData.getComprehensiveConsent()); - information.put("additionalConsentInfo", validationResult.getConsentInformation()); - validationResult.setConsentInformation(information); - - JSONObject responsePayload; - try { - responsePayload = validationResult.generatePayload(); - responsePayload.appendField("consentInformation", - IdentityCommonUtil.signJWTWithDefaultKey(validationResult.getConsentInformation().toJSONString())); - } catch (Exception e) { - log.error("Error occurred while getting private key", e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, "Error while getting private key"); - } - return Response.status(HttpServletResponse.SC_OK).entity(responsePayload).build(); - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/error/ConsentThrowableMapper.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/error/ConsentThrowableMapper.java deleted file mode 100644 index 7f9ad49a..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/error/ConsentThrowableMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.error; - -import com.wso2.openbanking.accelerator.consent.endpoint.util.ConsentConstants; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Map exceptions to custom error format. - */ -public class ConsentThrowableMapper implements ExceptionMapper { - - private static final Log log = LogFactory.getLog(ConsentThrowableMapper.class); - private static String defaultError = "A runtime error has occurred while handling the request"; - - @Override - public Response toResponse(Throwable throwable) { - - if (throwable instanceof ConsentException) { - if (((ConsentException) throwable).getErrorRedirectURI() != null) { - return Response.status(((ConsentException) throwable).getStatus().getStatusCode()). - location(((ConsentException) throwable).getErrorRedirectURI()).build(); - } else { - return Response.status(((ConsentException) throwable).getStatus().getStatusCode()) - .entity(((ConsentException) throwable).getPayload().toJSONString()) - .header(ConsentConstants.HEADER_CONTENT_TYPE, ConsentConstants.DEFAULT_RESPONSE_CONTENT_TYPE) - .build(); - } - } else { - log.error("Generic exception. Cause: " + throwable.getMessage(), throwable); - if (throwable instanceof ClientErrorException) { - return toResponse(new ConsentException(ResponseStatus.fromStatusCode(((ClientErrorException) throwable) - .getResponse().getStatus()), throwable.getMessage())); - } else { - return toResponse(new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, defaultError)); - } - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/util/ConsentConstants.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/util/ConsentConstants.java deleted file mode 100644 index 3dfab0eb..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/util/ConsentConstants.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.util; - -/** - * Constant class for consent authorize endpoints. - */ -public class ConsentConstants { - - public static final String HEADER_CONTENT_TYPE = "Content-Type"; - public static final String APPLICATION_JSON = "application/json"; - public static final String DEFAULT_RESPONSE_CONTENT_TYPE = APPLICATION_JSON; - - public static final String ERROR_PAYLOAD_READ = "Error while reading payload"; - public static final String ERROR_PAYLOAD_PARSE = "Error while parsing payload"; - public static final String RESOURCE_PATH = "ResourcePath"; - public static final String HTTP_METHOD = "HttpMethod"; - public static final String RESOURCE_CONTEXT = "ResourceContext"; - public static final String PRESERVE_CONSENT = "Consent.PreserveConsentLink"; - public static final String SENSITIVE_DATA_MAP = "sensitiveDataMap"; - public static final String LOGGED_IN_USER = "loggedInUser"; - public static final String SP_QUERY_PARAMS = "spQueryParams"; - public static final String SCOPES = "scopeString"; - public static final String APPLICATION = "application"; - public static final String REQUEST_HEADERS = "requestHeaders"; - public static final String REQUEST_URI = "redirectURI"; - public static final String USERID = "userId"; - public static final String CONSENT_ID = "consentId"; - public static final String CLIENT_ID = "clientId"; - public static final String REGULATORY = "regulatory"; - public static final String CONSENT_RESOURCE = "consentResource"; - public static final String AUTH_RESOURCE = "authResource"; - public static final String META_DATA = "metaDataMap"; - public static final String TYPE = "type"; - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/util/ConsentUtils.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/util/ConsentUtils.java deleted file mode 100644 index dd95e1f0..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/java/com/wso2/openbanking/accelerator/consent/endpoint/util/ConsentUtils.java +++ /dev/null @@ -1,358 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.consent.endpoint.util; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.consent.extensions.authorize.model.ConsentData; -import com.wso2.openbanking.accelerator.consent.extensions.common.AuthErrorCode; -import com.wso2.openbanking.accelerator.consent.extensions.common.ConsentException; -import com.wso2.openbanking.accelerator.consent.extensions.common.ResponseStatus; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.AuthorizationResource; -import com.wso2.openbanking.accelerator.consent.mgt.dao.models.ConsentResource; -import com.wso2.openbanking.accelerator.identity.util.HTTPClientUtils; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.httpclient.util.HttpURLConnection; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.core.util.IdentityUtil; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.WebApplicationException; - -/** - * Utils class for consent authorize endpoints. - */ -public class ConsentUtils { - - private static final Log log = LogFactory.getLog(ConsentUtils.class); - private static final String ERROR_FETCHING_SP = "Error while fetching service provider"; - private static Gson gson = new Gson(); - - /** - * Send authorize request in order to complete the authorize flow and get the redirect. - * - * @param consent The approval/denial of the consent of the user - * @param cookies The session cookies used in auth flow - * @param consentData Consent data object which contains consent information - * @return The redirect URI to end the authorize flow - */ - public static URI authorizeRequest(String consent, Map cookies, ConsentData consentData) { - - String authorizeURL = IdentityUtil.getProperty("OAuth.OAuth2AuthzEPUrl"); - try (CloseableHttpClient client = HTTPClientUtils.getHttpsClient()) { - - BasicCookieStore cookieStore = new BasicCookieStore(); - String cookieDomain = new URI(authorizeURL).getHost(); - for (Map.Entry cookieValue : cookies.entrySet()) { - BasicClientCookie cookie = new BasicClientCookie(cookieValue.getKey(), cookieValue.getValue()); - cookie.setDomain(cookieDomain); - cookie.setPath("/"); - cookie.setSecure(true); - cookieStore.addCookie(cookie); - } - HttpPost authorizeRequest = new HttpPost(authorizeURL); - List params = new ArrayList<>(); - params.add(new BasicNameValuePair("hasApprovedAlways", "false")); - params.add(new BasicNameValuePair("sessionDataKeyConsent", consentData.getSessionDataKey())); - params.add(new BasicNameValuePair("consent", consent)); - params.add(new BasicNameValuePair("user", consentData.getUserId())); - HttpContext localContext = new BasicHttpContext(); - localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params); - authorizeRequest.setEntity(entity); - HttpResponse authorizeResponse = client.execute(authorizeRequest, localContext); - - if (authorizeResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - "Error while getting authorize redirect", consentData.getState()); - } else { - //Extract the location header from the authorization redirect - return new URI(authorizeResponse.getLastHeader("Location").getValue()); - } - } catch (IOException e) { - log.error("Error while sending authorize request to complete the authorize flow", e); - return null; - } catch (URISyntaxException e) { - log.error("Authorize response URI syntax error", e); - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - "Internal server error", consentData.getState()); - } catch (OpenBankingException e) { - log.error("Error while obtaining HTTP client", e); - throw new ConsentException(consentData.getRedirectURI(), AuthErrorCode.SERVER_ERROR, - "Internal server error", consentData.getState()); - } - } - - /** - * Util method to extract the payload from a HTTP request object. Can be JSONObject or JSONArray - * - * @param request The HTTP request object - * @return Object payload can be either an instance of JSONObject or JSONArray only. Can be a ConsentException if - * is and error scenario. Error is returned instead of throwing since the error response should be handled by the - * toolkit is the manage scenario. - */ - public static Object getPayload(HttpServletRequest request) { - try { - Object payload = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(getStringPayload(request)); - if (payload == null) { - log.debug("Payload is empty. Returning null"); - return null; - } - if (!(payload instanceof JSONObject || payload instanceof JSONArray)) { - //Not throwing error since error should be formatted by manage toolkit - log.error("Payload is not a JSON. Returning null"); - return null; - } - return payload; - } catch (ParseException e) { - //Not throwing error since error should be formatted by manage toolkit - log.error(ConsentConstants.ERROR_PAYLOAD_PARSE + ". Returning null", e); - return null; - } catch (ConsentException e) { - //Not throwing error since error should be formatted by manage toolkit - log.error(e.getMessage() + ". Returning null", e); - return null; - } - } - - /** - * Util method to extract the payload from a HTTP request object. Can be only JSONObject - * - * @param request The request object - * @return JSONObject payload can only be an instance of JSONObject - * @throws ConsentException Parser errors and payload type is not JSON object - */ - public static JSONObject getJSONObjectPayload(HttpServletRequest request) throws ConsentException { - try { - Object payload = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(getStringPayload(request)); - //JSONArray not supported here. If requirement arises, cast the object to JSONArray from here - if (payload == null) { - return null; - } - if (!(payload instanceof JSONObject)) { - return null; - } - return (JSONObject) payload; - } catch (ParseException e) { - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, ConsentConstants.ERROR_PAYLOAD_PARSE); - } catch (ConsentException e) { - //Not throwing error since error should be formatted by manage toolkit - log.error(e.getMessage() + ". Returning null", e); - return null; - } - } - - /** - * Extract string payload from request object. - * - * @param request The request object - * @return String payload - * @throws ConsentException Payload read errors - */ - public static String getStringPayload(HttpServletRequest request) throws ConsentException { - try { - return IOUtils.toString(request.getInputStream()); - } catch (IOException e) { - log.error(ConsentConstants.ERROR_PAYLOAD_READ, e); - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, ConsentConstants.ERROR_PAYLOAD_READ); - } - } - - /** - * Util method to extract the payload from a HTTP request object. - * - * @param request The HTTP request object - * @return Object payload can be xml or json. Can be a ConsentException if is and error scenario. - * Error is returned instead of throwing since the error response should be handled by the - * toolkit is the manage scenario. - */ - public static Object getFileUploadPayload(HttpServletRequest request) { - try { - String payload = getStringPayload(request); - if (payload == null) { - log.debug("Payload is empty. Returning null"); - return null; - } - return payload; - } catch (ConsentException e) { - //Not throwing error since error should be formatted by manage toolkit - log.error(e.getMessage() + ". Returning null", e); - return null; - } - } - - - /** - * Extract and add query parameters from a URL to existing resource map. - * Resource parameter map will contain the resource path(ex: /aisp/accounts/{AccountId}?queryParam=queryParamValue), - * http method, context(ex: /open-banking/v3.1/aisp) - * - * @param resourceParams Map containing the resource parameters - * @return Extracted query parameter map - */ - public static Map addQueryParametersToResourceParamMap(Map resourceParams) - throws URISyntaxException { - - if (resourceParams.isEmpty()) { - return new HashMap(); - } - - URI url = new URI((String) resourceParams.get("resource")); - - resourceParams.put(ConsentConstants.RESOURCE_PATH, url.getRawPath()); - - if (url.getRawQuery() != null) { - String[] params = url.getRawQuery().split("&"); - - for (String param : params) { - if (param.split("=").length == 2) { - String name = param.split("=")[0]; - String value = param.split("=")[1]; - resourceParams.put(name, value); - } - } - } - return resourceParams; - } - - /** - * Get Service provider from clientId. - * - * @param clientId of application. - * @return Service Provider. - * @throws WebApplicationException client error. - */ - public static ServiceProvider getOAuthServiceProvider(String clientId) throws WebApplicationException { - - ApplicationManagementService managementService = getApplicationManagementService(); - Optional serviceProvider; - try { - serviceProvider = Optional.ofNullable(managementService.getServiceProviderByClientId(clientId, - IdentityApplicationConstants.OAuth2.NAME, getTenantDomain())); - } catch (IdentityApplicationManagementException e) { - - log.error(String.format("Unable to retrieve service provider information for clientId %s", clientId), e); - // Throw Web Application exception - throw new ConsentException(ResponseStatus.INTERNAL_SERVER_ERROR, ERROR_FETCHING_SP); - } - - // Reject default service provider and empty service provider. - if (!serviceProvider.isPresent() || - serviceProvider.get().getApplicationName().equals(IdentityApplicationConstants.DEFAULT_SP_CONFIG)) { - - final String errorMessage = String.format("Unable to find application for clientId %s", clientId); - - if (log.isDebugEnabled()) { - log.debug(errorMessage); - } - - // Throw client error for not found service provider. - throw new ConsentException(ResponseStatus.NOT_FOUND, errorMessage); - } - return serviceProvider.get(); - } - - /** - * Get WSO2 IS Application Mgt Service from threadlocal carbon context. - * - * @return Application Management Service Implementation. - */ - public static ApplicationManagementService getApplicationManagementService() { - - return (ApplicationManagementService) PrivilegedCarbonContext - .getThreadLocalCarbonContext() - .getOSGiService(ApplicationManagementService.class, null); - - } - - /** - * Get Tenant Domain String from carbon context. - * - * @return tenant domain of current context. - */ - private static String getTenantDomain() { - - return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); - } - - /** - * @param consentDetails json object of consent data - * @param sessionDataKey - * @return - * @throws URISyntaxException - */ - public static ConsentData getConsentDataFromAttributes(JsonObject consentDetails, String sessionDataKey) - throws URISyntaxException { - - JsonObject sensitiveDataMap = consentDetails.get(ConsentConstants.SENSITIVE_DATA_MAP).getAsJsonObject(); - ConsentData consentData = new ConsentData(sessionDataKey, - sensitiveDataMap.get(ConsentConstants.LOGGED_IN_USER).getAsString(), - sensitiveDataMap.get(ConsentConstants.SP_QUERY_PARAMS).getAsString(), - consentDetails.get(ConsentConstants.SCOPES).getAsString(), - sensitiveDataMap.get(ConsentConstants.APPLICATION).getAsString(), - gson.fromJson(consentDetails.get(ConsentConstants.REQUEST_HEADERS), Map.class)); - consentData.setSensitiveDataMap(gson.fromJson(sensitiveDataMap, Map.class)); - URI redirectURI = new URI(consentDetails.get(ConsentConstants.REQUEST_URI).getAsString()); - consentData.setRedirectURI(redirectURI); - consentData.setUserId(consentDetails.get(ConsentConstants.USERID).getAsString()); - consentData.setConsentId(consentDetails.get(ConsentConstants.CONSENT_ID).getAsString()); - consentData.setClientId(consentDetails.get(ConsentConstants.CLIENT_ID).getAsString()); - consentData.setRegulatory(Boolean.parseBoolean(consentDetails.get(ConsentConstants.REGULATORY).getAsString())); - ConsentResource consentResource = gson.fromJson(consentDetails.get(ConsentConstants.CONSENT_RESOURCE), - ConsentResource.class); - consentData.setConsentResource(consentResource); - AuthorizationResource authorizationResource = - gson.fromJson(consentDetails.get(ConsentConstants.AUTH_RESOURCE), AuthorizationResource.class); - consentData.setAuthResource(authorizationResource); - consentData.setMetaDataMap(gson.fromJson(consentDetails.get(ConsentConstants.META_DATA), Map.class)); - consentData.setType(consentDetails.get(ConsentConstants.TYPE).getAsString()); - return consentData; - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index c4f8e532..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index 7569f0a1..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - false - - - CXF3,Carbon - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index 048b8809..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 3879430c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.consent.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - WSO2 Open Banking - Consent API - WSO2 Open Banking - Consent API - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/pom.xml deleted file mode 100644 index 6eb99a78..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/pom.xml +++ /dev/null @@ -1,203 +0,0 @@ - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.accelerator.dcr.endpoint - WSO2 Open Banking - Dynamic Client Registration Endpoint - WSO2 Open Banking - Dynamic Client Endpoint - war - - - - io.swagger - swagger-jaxrs - - - javax.ws.rs - jsr311-api - - - com.google.guava - guava - - - org.yaml - snakeyaml - - - - - javax.validation - validation-api - provided - - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - - - javax.ws.rs - jsr311-api - - - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.dcr - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.mgt - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - io.swagger - swagger-annotations - - - net.minidev - json-smart - provided - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-source-api - generate-sources - - add-source - - - - src/gen/java - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#dynamic-client-registration - WEB-INF/lib/axis2-kernel-1.6.1-wso2v12.jar, - WEB-INF/lib/slf4j-api-*.jar - - - - org.openapitools - openapi-generator-maven-plugin - ${openapi.generator.plugin.version} - - - - generate - - - - true - true - ${project.basedir}/src/main/resources/dynamic.client.registration.yaml - - jaxrs-cxf - src/gen/java - true - - false - com.wso2.openbanking.accelerator.dynamic.client.registration.src.main.model - com.wso2.openbanking.accelerator.dynamic.client.registration.src.main.api - impl - DTO - ${project.basedir} - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/gen/java/com/wso2/openbanking/accelerator/dynamic/client/registration/dto/RegistrationErrorDTO.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/gen/java/com/wso2/openbanking/accelerator/dynamic/client/registration/dto/RegistrationErrorDTO.java deleted file mode 100644 index c3e3766e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/gen/java/com/wso2/openbanking/accelerator/dynamic/client/registration/dto/RegistrationErrorDTO.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.dto; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; - -/** - * Error model for DCR - */ -public class RegistrationErrorDTO { - - private String error = null; - - private String errorDescription = null; - - /** - * - **/ - @ApiModelProperty(value = "") - @JsonProperty("error") - public String getError() { - - return error; - } - - public void setError(String error) { - - this.error = error; - } - - /** - * - **/ - @ApiModelProperty(value = "") - @JsonProperty("error_description") - public String getError_description() { - - return errorDescription; - } - - public void setErrorDescription(String errorDescription) { - - this.errorDescription = errorDescription; - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - sb.append("class ErrorDTO {\n"); - - sb.append(" error: ").append(error).append("\n"); - sb.append(" error_description: ").append(errorDescription).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/RegistrationConstants.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/RegistrationConstants.java deleted file mode 100644 index 1836dc54..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/RegistrationConstants.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl; - -/** - * Constants for DCR. - */ -public class RegistrationConstants { - - public static final String CLIENT_ID_ISSUED_AT = "client_id_issued_at"; - public static final String CLIENT_ID = "client_id"; - public static final String REGISTRATION_ACCESS_TOKEN = "registration_access_token"; - public static final String CLIENT_NOT_FOUND = "NOT_FOUND"; - public static final String INTERNAL_SERVER_ERROR = "Internal Server error"; -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/api/ClientRegistrationApiImpl.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/api/ClientRegistrationApiImpl.java deleted file mode 100644 index e7e37a9a..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/api/ClientRegistrationApiImpl.java +++ /dev/null @@ -1,321 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.api; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.RegistrationConstants; -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.service.RegistrationServiceHandler; -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.util.RegistrationUtils; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.RegistrationValidator; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonConstants; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonHelper; -import com.wso2.openbanking.accelerator.identity.util.IdentityCommonUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.oauth.dcr.exception.DCRMException; -import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; - -import java.io.IOException; -import java.security.cert.CertificateEncodingException; -import java.text.ParseException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * Implementation class for the DCR API. - */ -@Path("/register") -public class ClientRegistrationApiImpl { - - private static final Log log = LogFactory.getLog(ClientRegistrationApiImpl.class); - - private final IdentityCommonHelper identityCommonHelper = new IdentityCommonHelper(); - private RegistrationServiceHandler registrationServiceHandler = new RegistrationServiceHandler(); - private static Gson gson = new Gson(); - - @DELETE - @Path("/{s:.*}") - @Produces({"application/json; charset=utf-8"}) - public Response registerClientIdDelete(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - RegistrationValidator validator = RegistrationValidator.getRegistrationValidator(); - if (log.isDebugEnabled()) { - log.debug("Invoking the configured registration validator:" + validator); - } - String clientId = uriInfo.getPathParameters().getFirst("s"); - - try { - validator.validateDelete(clientId); - identityCommonHelper.revokeAccessTokensByClientId(clientId); - return registrationServiceHandler.deleteRegistration(clientId); - } catch (DCRMException e) { - log.error("Error while deleting the application", e); - if (e.getErrorCode().contains(RegistrationConstants.CLIENT_NOT_FOUND)) { - return Response.status(Response.Status.UNAUTHORIZED).build(); - } - } catch (DCRValidationException e) { - log.error("Error occurred while validating request", e); - return Response.status(Response.Status.BAD_REQUEST).entity(RegistrationUtils.getErrorDTO(e.getErrorCode(), - e.getErrorDescription())).build(); - } catch (IdentityOAuth2Exception e) { - log.error("Error occurred while revoking application access tokens", e); - } - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(RegistrationUtils - .getErrorDTO(RegistrationConstants.INTERNAL_SERVER_ERROR, - "Error occurred while deleting the application")).build(); - } - - @GET - @Path("/{s:.*}") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response registerClientIdGet(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - try { - String clientId = uriInfo.getPathParameters().getFirst("s"); - - RegistrationValidator validator = RegistrationValidator.getRegistrationValidator(); - if (log.isDebugEnabled()) { - log.debug("Invoking the configured registration validator:" + validator); - } - validator.validateGet(clientId); - Map headers = getHeaders(request); - String accessToken = headers.get(RegistrationConstants.REGISTRATION_ACCESS_TOKEN); - - Map additionalAttributes = new HashMap<>(); - - try { - String tlsCert = new IdentityCommonHelper().encodeCertificateContent( - IdentityCommonUtil.getCertificateFromAttribute( - request.getAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE))); - - // add TLS cert as additional attribute - additionalAttributes.put(IdentityCommonConstants.TLS_CERT, tlsCert); - } catch (CertificateEncodingException e) { - log.error("Certificate not valid", e); - } - - return registrationServiceHandler.retrieveRegistration(additionalAttributes, clientId, accessToken); - } catch (DCRMException e) { - log.error("Error while retrieving application", e); - if (e.getErrorCode().contains(RegistrationConstants.CLIENT_NOT_FOUND)) { - return Response.status(Response.Status.UNAUTHORIZED).build(); - } - } catch (IdentityApplicationManagementException e) { - log.error("Error while retrieving Service Provider details", e); - } catch (DCRValidationException e) { - log.error("Error occurred while validating request", e); - return Response.status(Response.Status.BAD_REQUEST).entity(RegistrationUtils.getErrorDTO(e.getErrorCode(), - e.getErrorDescription())).build(); - } - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - RegistrationUtils.getErrorDTO(RegistrationConstants.INTERNAL_SERVER_ERROR, - "Error occurred while processing the request")).build(); - } - - @PUT - @Path("/{s:.*}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response registerClientIdPut(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - //RegistrationRequest registrationRequest = RegistrationUtils.getRegistrationRequest(requestBody); - - RegistrationValidator registrationValidator = RegistrationValidator.getRegistrationValidator(); - if (log.isDebugEnabled()) { - log.debug("Invoking the configured registration validator:" + registrationValidator); - } - try { - JsonElement registrationRequestDetails = gson.toJsonTree(RegistrationUtils.getPayload(request)); - - RegistrationRequest registrationRequest = - gson.fromJson(registrationRequestDetails, RegistrationRequest.class); - - Map requestAttributes = (Map) - gson.fromJson(registrationRequestDetails, Map.class); - - registrationRequest.setRequestParameters(requestAttributes); - - if (StringUtils.isNotEmpty(registrationRequest.getSoftwareStatement())) { - //decode SSA if provided in the registration request - String ssaBody = JWTUtils.decodeRequestJWT(registrationRequest.getSoftwareStatement(), - OpenBankingConstants.JWT_BODY) - .toString(); - Map ssaAttributesMap = gson.fromJson(ssaBody, Map.class); - registrationRequest.setSsaParameters(ssaAttributesMap); - } - - String clientId = uriInfo.getPathParameters().getFirst("s"); - RegistrationUtils.validateRegistrationCreation(registrationRequest); - log.debug("Invoking specific validations"); - RegistrationValidator.getRegistrationValidator().validateUpdate(registrationRequest); - Map headers = getHeaders(request); - String accessToken = headers.get(RegistrationConstants.REGISTRATION_ACCESS_TOKEN); - - Map additionalAttributes = new HashMap<>(); - - try { - String tlsCert = new IdentityCommonHelper().encodeCertificateContent( - IdentityCommonUtil.getCertificateFromAttribute( - request.getAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE))); - - // add TLS cert as additional attribute - additionalAttributes.put(IdentityCommonConstants.TLS_CERT, tlsCert); - } catch (CertificateEncodingException e) { - log.error("Certificate not valid", e); - } - - return registrationServiceHandler. - updateRegistration(registrationRequest, additionalAttributes, clientId, accessToken); - } catch (ParseException e) { - log.error("Error while parsing the softwareStatement", e); - } catch (DCRMException e) { - log.error("Error occurred while creating the Service provider", e); - if (e.getErrorCode().contains(RegistrationConstants.CLIENT_NOT_FOUND)) { - return Response.status(Response.Status.UNAUTHORIZED).build(); - } - } catch (IdentityApplicationManagementException e) { - log.error("Error occurred while retrieving the Service provider details", e); - } catch (DCRValidationException e) { - log.error("Error occurred while validating request", e); - return Response.status(Response.Status.BAD_REQUEST).entity(RegistrationUtils.getErrorDTO(e.getErrorCode(), - e.getErrorDescription())).build(); - } catch (net.minidev.json.parser.ParseException | IOException e) { - log.error("Error occurred while parsing the request", e); - } - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - RegistrationUtils.getErrorDTO(RegistrationConstants.INTERNAL_SERVER_ERROR, - "Error occurred while processing the request")).build(); - - } - - @POST - @Path("/{s:.*}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response registerPost(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - RegistrationValidator registrationValidator = RegistrationValidator.getRegistrationValidator(); - //invoke the configured registration VALIDATOR - if (log.isDebugEnabled()) { - log.debug("Invoking the configured registration validator:" + registrationValidator); - } - try { - JsonElement registrationRequestDetails = gson.toJsonTree(RegistrationUtils.getPayload(request)); - - RegistrationRequest registrationRequest = - gson.fromJson(registrationRequestDetails, RegistrationRequest.class); - - Map requestAttributes = (Map) - gson.fromJson(registrationRequestDetails, Map.class); - - Map additionalAttributes = new HashMap<>(); - - try { - String tlsCert = new IdentityCommonHelper().encodeCertificateContent( - IdentityCommonUtil.getCertificateFromAttribute( - request.getAttribute(IdentityCommonConstants.JAVAX_SERVLET_REQUEST_CERTIFICATE))); - - // add TLS cert as additional attribute - additionalAttributes.put(IdentityCommonConstants.TLS_CERT, tlsCert); - } catch (CertificateEncodingException e) { - log.error("Certificate not valid", e); - } - - registrationRequest.setRequestParameters(requestAttributes); - if (StringUtils.isNotEmpty(registrationRequest.getSoftwareStatement())) { - //decode SSA if provided in the registration request - String ssaBody = JWTUtils.decodeRequestJWT(registrationRequest.getSoftwareStatement(), - OpenBankingConstants.JWT_BODY) - .toString(); - Map ssaAttributesMap = gson.fromJson(ssaBody, Map.class); - registrationRequest.setSsaParameters(ssaAttributesMap); - } - - RegistrationUtils.validateRegistrationCreation(registrationRequest); - //do specific validations - registrationValidator.validatePost(registrationRequest); - return registrationServiceHandler.createRegistration(registrationRequest, additionalAttributes); - } catch (ParseException e) { - log.error("Error while parsing the softwareStatement", e); - } catch (DCRMException e) { - log.error("Error occurred while creating the Service provider", e); - if (DCRCommonConstants.DUPLICATE_APPLICATION_NAME.equalsIgnoreCase(e.getErrorCode())) { - return Response.status(Response.Status.BAD_REQUEST).entity(RegistrationUtils - .getErrorDTO(DCRCommonConstants.INVALID_META_DATA, e.getErrorDescription())) - .build(); - } - } catch (IdentityApplicationManagementException e) { - log.error("Error occurred while retrieving the Service provider details", e); - } catch (DCRValidationException e) { - log.error("Error occurred while validating request", e); - return Response.status(Response.Status.BAD_REQUEST).entity(RegistrationUtils - .getErrorDTO(e.getErrorCode(), e.getErrorDescription())) - .build(); - } catch (net.minidev.json.parser.ParseException | IOException e) { - log.error("Error occurred while parsing the request", e); - } - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - RegistrationUtils.getErrorDTO(RegistrationConstants.INTERNAL_SERVER_ERROR, - "Error occurred while processing the request")).build(); - } - - /** - * Extract headers from a request object. - * - * @param request The request object - * @return Map of header key value pairs - */ - public static Map getHeaders(HttpServletRequest request) { - Map headers = new HashMap<>(); - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - headers.put(headerName, request.getHeader(headerName)); - } - return headers; - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/model/DCRRequestData.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/model/DCRRequestData.java deleted file mode 100644 index 7efda05b..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/model/DCRRequestData.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.model; - -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.util.ResponseStatus; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Model class for DCR request data. - */ -public class DCRRequestData { - - public Map getHeaders() { - - return headers; - } - - public void setHeaders(Map headers) { - - this.headers = headers; - } - - public Object getPayload() { - - return payload; - } - - public void setPayload(Object payload) { - - this.payload = payload; - } - - public Map getQueryParams() { - - return queryParams; - } - - public void setQueryParams(Map queryParams) { - - this.queryParams = queryParams; - } - - public String getRequestPath() { - - return requestPath; - } - - public void setRequestPath(String requestPath) { - - this.requestPath = requestPath; - } - - public String getClientId() { - - return clientId; - } - - public void setClientId(String clientId) { - - this.clientId = clientId; - } - - public HttpServletRequest getRequest() { - - return request; - } - - public void setRequest(HttpServletRequest request) { - - this.request = request; - } - - public HttpServletResponse getResponse() { - - return response; - } - - public void setResponse(HttpServletResponse response) { - - this.response = response; - } - - public ResponseStatus getResponseStatus() { - - return responseStatus; - } - - public void setResponseStatus(ResponseStatus responseStatus) { - - this.responseStatus = responseStatus; - } - - public Object getResponsePayload() { - - return responsePayload; - } - - public void setResponsePayload(Object responsePayload) { - - this.responsePayload = responsePayload; - } - - private Map headers; - //Payload can either be a JSONObject or a JSONArray - private Object payload; - private Map queryParams; - private String requestPath; - private String clientId; - private HttpServletRequest request; - private HttpServletResponse response; - private ResponseStatus responseStatus; - private Object responsePayload; - - public DCRRequestData(Map headers, Object payload, Map queryParams, - String requestPath, HttpServletRequest request, HttpServletResponse response) { - - this.headers = headers; - this.payload = payload; - this.queryParams = queryParams; - this.requestPath = requestPath; - this.request = request; - this.response = response; - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/service/RegistrationServiceHandler.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/service/RegistrationServiceHandler.java deleted file mode 100644 index 6fdaa3f4..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/service/RegistrationServiceHandler.java +++ /dev/null @@ -1,267 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.service; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.RegistrationConstants; -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.util.RegistrationUtils; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.RegistrationValidator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; -import org.wso2.carbon.identity.application.common.model.ServiceProvider; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.oauth.dcr.bean.Application; -import org.wso2.carbon.identity.oauth.dcr.exception.DCRMException; -import org.wso2.carbon.identity.oauth.dcr.service.DCRMService; - -import java.text.ParseException; -import java.time.Instant; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.Response; - -/** - * Service class to invoke spec specific validators and manage storing, retrieving, updating and - * deleting registrations. - */ -public class RegistrationServiceHandler { - - private static final Log log = LogFactory.getLog(RegistrationServiceHandler.class); - private DCRMService oAuth2DCRMService; - private OpenBankingConfigurationService openBankingConfigurationService; - - public Response createRegistration(RegistrationRequest registrationRequest, - Map additionalAttributes) - throws DCRMException, IdentityApplicationManagementException, IllegalArgumentException, ParseException { - - DCRMService dcrmService = getDCRServiceInstance(); - OpenBankingConfigurationService openBankingConfigurationService = getOBConfigService(); - RegistrationValidator registrationValidator = RegistrationValidator.getRegistrationValidator(); - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - boolean useSoftwareIdAsAppName = false; - String jwksEndpointName = ""; - if (openBankingConfigurationService != null) { - Map configurations = openBankingConfigurationService.getConfigurations(); - useSoftwareIdAsAppName = Boolean.parseBoolean(configurations - .get(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME).toString()); - if (configurations.containsKey(OpenBankingConstants.DCR_JWKS_NAME)) { - jwksEndpointName = configurations - .get(OpenBankingConstants.DCR_JWKS_NAME).toString(); - } - } - String applicationName = RegistrationUtils.getApplicationName(registrationRequest, useSoftwareIdAsAppName); - Application application = dcrmService.registerApplication(RegistrationUtils - .getApplicationRegistrationRequest(registrationRequest, applicationName)); - if (log.isDebugEnabled()) { - log.debug("Created application with name :" + application.getClientName()); - } - ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance(); - ServiceProvider serviceProvider = applicationManagementService - .getServiceProvider(application.getClientName(), tenantDomain); - - //get JWKS URI from the request - String jwksUri = RegistrationUtils.getJwksUriFromRequest(registrationRequest, jwksEndpointName); - serviceProvider.setJwksUri(jwksUri); - - Long clientIdIssuedTime = Instant.now().getEpochSecond(); - //store the client details as SP meta data - Map registrationRequestData = RegistrationUtils - .getAlteredApplicationAttributes(registrationRequest); - registrationRequestData.put(RegistrationConstants.CLIENT_ID_ISSUED_AT, clientIdIssuedTime.toString()); - // Adding SP property to identify create request. Will be removed when setting up authenticators. - registrationRequestData.put("AppCreateRequest", "true"); - List spMetaData = RegistrationUtils.getServiceProviderPropertyList - (registrationRequestData); - serviceProvider.setSpProperties(spMetaData.toArray(new ServiceProviderProperty[0])); - applicationManagementService.updateApplication(serviceProvider, tenantDomain, userName); - - if (log.isDebugEnabled()) { - log.debug("Updated Service Provider " + serviceProvider.getApplicationName() + " with the client data"); - } - Map registrationData = registrationRequest.getRequestParameters(); - registrationData.put(RegistrationConstants.CLIENT_ID, application.getClientId()); - registrationData.put(RegistrationConstants.CLIENT_ID_ISSUED_AT, clientIdIssuedTime.toString()); - if (registrationRequest.getSsaParameters() != null) { - registrationData.putAll(registrationRequest.getSsaParameters()); - } - registrationData.putAll(additionalAttributes); - String registrationResponse = registrationValidator.getRegistrationResponse(registrationData); - return Response.status(Response.Status.CREATED).entity(registrationResponse).build(); - } - - public Response retrieveRegistration(Map additionalAttributes, String clientId, String accessToken) - throws DCRMException, IdentityApplicationManagementException { - - DCRMService dcrmService = getDCRServiceInstance(); - Application application = dcrmService.getApplication(clientId); - - if (log.isDebugEnabled()) { - log.debug("Retrieved Application with name " + application.getClientName()); - } - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - - ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance(); - ServiceProvider serviceProvider = applicationManagementService - .getServiceProvider(application.getClientName(), tenantDomain); - ServiceProviderProperty[] serviceProviderProperties = serviceProvider.getSpProperties(); - - if (log.isDebugEnabled()) { - log.debug("Retrieved client meta data for application " + application.getClientName()); - } - - List spPropertyList = Arrays.asList(serviceProviderProperties); - Map spMetaData = RegistrationUtils.getSpMetaDataMap(spPropertyList); - spMetaData.put(RegistrationConstants.CLIENT_ID, application.getClientId()); - spMetaData.put(RegistrationConstants.REGISTRATION_ACCESS_TOKEN, accessToken); - spMetaData.putAll(additionalAttributes); - - String registrationResponseJson = RegistrationValidator.getRegistrationValidator() - .getRegistrationResponse(spMetaData); - return Response.status(Response.Status.OK).entity(registrationResponseJson).build(); - } - - public Response updateRegistration(RegistrationRequest request, Map additionalAttributes, - String clientId, String accessToken) - throws DCRMException, IdentityApplicationManagementException, DCRValidationException, ParseException { - - DCRMService dcrmService = getDCRServiceInstance(); - OpenBankingConfigurationService openBankingConfigurationService = getOBConfigService(); - boolean useSoftwareIdAsAppName = false; - String jwksEndpointName = ""; - if (openBankingConfigurationService != null) { - Map configurations = openBankingConfigurationService.getConfigurations(); - useSoftwareIdAsAppName = Boolean.parseBoolean(configurations - .get(OpenBankingConstants.DCR_USE_SOFTWAREID_AS_APPNAME).toString()); - if (configurations.containsKey(OpenBankingConstants.DCR_JWKS_NAME)) { - jwksEndpointName = configurations - .get(OpenBankingConstants.DCR_JWKS_NAME).toString(); - } - } - Application applicationToUpdate = dcrmService.getApplication(clientId); - String applicationNameInRequest; - if (useSoftwareIdAsAppName) { - applicationNameInRequest = (request.getSoftwareStatement() != null) ? - request.getSoftwareStatementBody().getSoftwareId() : - request.getSoftwareId(); - } else { - applicationNameInRequest = request.getSoftwareStatementBody().getClientName(); - } - if (!applicationToUpdate.getClientName().equals(applicationNameInRequest)) { - throw new DCRValidationException(DCRCommonConstants.INVALID_META_DATA, "Invalid application name"); - } - String applicationName = RegistrationUtils.getApplicationName(request, useSoftwareIdAsAppName); - Application application = dcrmService.updateApplication - (RegistrationUtils.getApplicationUpdateRequest(request, applicationName), clientId); - if (log.isDebugEnabled()) { - log.debug("Updated Application with name " + application.getClientName()); - } - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - - //retrieve stored client meta data - ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance(); - ServiceProvider serviceProvider = applicationManagementService - .getServiceProvider(application.getClientName(), tenantDomain); - - //get JWKS URI from the request - String jwksUri = RegistrationUtils.getJwksUriFromRequest(request, jwksEndpointName); - serviceProvider.setJwksUri(jwksUri); - - ServiceProviderProperty[] serviceProviderProperties = serviceProvider.getSpProperties(); - if (log.isDebugEnabled()) { - log.debug("Retrieved client meta data for application " + application.getClientName()); - } - List spPropertyList = Arrays.asList(serviceProviderProperties); - Map storedSPMetaData = RegistrationUtils.getSpMetaDataMap(spPropertyList); - - String clientIdIssuedAt = ""; - if (storedSPMetaData.containsKey(RegistrationConstants.CLIENT_ID_ISSUED_AT)) { - clientIdIssuedAt = storedSPMetaData.get(RegistrationConstants.CLIENT_ID_ISSUED_AT).toString(); - } - - //update Service provider with new client data - Map updateRequestData = RegistrationUtils.getAlteredApplicationAttributes(request); - Map updateRegistrationData = request.getRequestParameters(); - if (request.getSsaParameters() != null) { - updateRegistrationData.putAll(request.getSsaParameters()); - } - updateRequestData.put(RegistrationConstants.CLIENT_ID_ISSUED_AT, clientIdIssuedAt); - // Adding SP property to identify update request. Will be removed when updating authenticators. - updateRequestData.put("AppCreateRequest", "false"); - List spMetaData = RegistrationUtils.getServiceProviderPropertyList(updateRequestData); - serviceProvider.setSpProperties(spMetaData.toArray(new ServiceProviderProperty[0])); - applicationManagementService.updateApplication(serviceProvider, tenantDomain, userName); - - if (log.isDebugEnabled()) { - log.debug("Updated Service Provider meta data for application " + application.getClientName()); - } - - updateRegistrationData.put(RegistrationConstants.CLIENT_ID, application.getClientId()); - updateRegistrationData.put(RegistrationConstants.CLIENT_ID_ISSUED_AT, clientIdIssuedAt); - updateRegistrationData.put(RegistrationConstants.REGISTRATION_ACCESS_TOKEN, accessToken); - updateRegistrationData.putAll(additionalAttributes); - String registrationResponse = RegistrationValidator.getRegistrationValidator() - .getRegistrationResponse(updateRegistrationData); - return Response.status(Response.Status.OK).entity(registrationResponse).build(); - } - - public Response deleteRegistration(String clientId) throws DCRMException { - - DCRMService dcrmService = getDCRServiceInstance(); - dcrmService.deleteApplication(clientId); - if (log.isDebugEnabled()) { - log.debug("Deleted application with client Id :" + clientId); - } - return Response.status(Response.Status.NO_CONTENT).build(); - } - - public DCRMService getDCRServiceInstance() { - - if (this.oAuth2DCRMService == null) { - DCRMService oAuth2DCRMService = (DCRMService) PrivilegedCarbonContext. - getThreadLocalCarbonContext().getOSGiService(DCRMService.class, null); - if (oAuth2DCRMService != null) { - this.oAuth2DCRMService = oAuth2DCRMService; - } - } - return this.oAuth2DCRMService; - } - - public OpenBankingConfigurationService getOBConfigService() { - - if (this.openBankingConfigurationService == null) { - OpenBankingConfigurationService openBankingConfigurationService = - (OpenBankingConfigurationService) PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(OpenBankingConfigurationService.class, null); - if (openBankingConfigurationService != null) { - this.openBankingConfigurationService = openBankingConfigurationService; - } - } - return this.openBankingConfigurationService; - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/util/RegistrationUtils.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/util/RegistrationUtils.java deleted file mode 100644 index eef4a113..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/util/RegistrationUtils.java +++ /dev/null @@ -1,359 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.util; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.wso2.openbanking.accelerator.common.util.JWTUtils; -import com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.dto.RegistrationErrorDTO; -import com.wso2.openbanking.accelerator.identity.dcr.exception.DCRValidationException; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationError; -import com.wso2.openbanking.accelerator.identity.dcr.model.RegistrationRequest; -import com.wso2.openbanking.accelerator.identity.dcr.utils.ValidatorUtils; -import com.wso2.openbanking.accelerator.identity.dcr.validation.DCRCommonConstants; -import com.wso2.openbanking.accelerator.identity.dcr.validation.RegistrationValidator; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; -import org.wso2.carbon.identity.oauth.dcr.bean.ApplicationRegistrationRequest; -import org.wso2.carbon.identity.oauth.dcr.bean.ApplicationUpdateRequest; - -import java.io.IOException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.servlet.http.HttpServletRequest; - -/** - * Util class which includes helper methods required for DCR. - */ -public class RegistrationUtils { - - private static final Log log = LogFactory.getLog(RegistrationUtils.class); - - private static final String DISALLOWED_CHARS_PATTERN = "([~!#$;%^&*+={}\\s\\|\\\\<>\\\"\\'\\/,\\]\\[\\(\\)])"; - private static final String SUBSTITUTE_STRING = "_"; - private static final int ABBREVIATED_STRING_LENGTH = 70; - private static Gson gson = new Gson(); - - /** - * this method invokes the configured registration VALIDATOR class - * by default the DefaultRegistrationValidatorImpl class will be configured. - * - * @param registrationRequest object containing the client registration request details - */ - public static void validateRegistrationCreation(RegistrationRequest registrationRequest) - throws ParseException, DCRValidationException { - - RegistrationValidator dcrRequestValidator; - dcrRequestValidator = RegistrationValidator.getRegistrationValidator(); - - if (StringUtils.isNotEmpty(registrationRequest.getSoftwareStatement())) { - // set the ssa payload according to the specification format - String decodedSSA = JWTUtils - .decodeRequestJWT(registrationRequest.getSoftwareStatement(), "body").toJSONString(); - dcrRequestValidator.setSoftwareStatementPayload(registrationRequest, decodedSSA); - } - - // do common validations - ValidatorUtils.getValidationViolations(registrationRequest); - - } - - public static RegistrationErrorDTO getErrorDTO(String errorCode, String errorMessage) { - - RegistrationErrorDTO registrationErrorDTO = new RegistrationErrorDTO(); - registrationErrorDTO.setError(errorCode); - registrationErrorDTO.setErrorDescription(errorMessage); - return registrationErrorDTO; - } - - public static RegistrationError getRegistrationError(String errorCode, String errorMessage) { - - RegistrationError registrationError = new RegistrationError(); - registrationError.setErrorCode(errorCode); - registrationError.setErrorMessage(errorMessage); - return registrationError; - } - - public static ApplicationRegistrationRequest getApplicationRegistrationRequest( - RegistrationRequest registrationRequest, String applicationName) { - - ApplicationRegistrationRequest appRegistrationRequest = new ApplicationRegistrationRequest(); - appRegistrationRequest.setClientName(applicationName); - appRegistrationRequest.setGrantTypes(registrationRequest.getGrantTypes()); - - // Get the redirect URIs based on the presence of software statement - List redirectUris = StringUtils.isEmpty(registrationRequest.getSoftwareStatement()) - ? registrationRequest.getCallbackUris() - : registrationRequest.getSoftwareStatementBody().getCallbackUris(); - - appRegistrationRequest.setRedirectUris(redirectUris); - - return appRegistrationRequest; - } - - public static ApplicationUpdateRequest getApplicationUpdateRequest(RegistrationRequest registrationRequest, - String applicationName) { - - ApplicationUpdateRequest applicationUpdateRequest = new ApplicationUpdateRequest(); - applicationUpdateRequest.setClientName(applicationName); - applicationUpdateRequest.setGrantTypes(registrationRequest.getGrantTypes()); - - // Get the redirect URIs based on the presence of software statement - List redirectUris = StringUtils.isEmpty(registrationRequest.getSoftwareStatement()) - ? registrationRequest.getCallbackUris() - : registrationRequest.getSoftwareStatementBody().getCallbackUris(); - - applicationUpdateRequest.setRedirectUris(redirectUris); - - return applicationUpdateRequest; - } - /** - * Retrieves the application name from the registration request. - * - * @param request registration or update request - * @param useSoftwareIdAsAppName Indicates whether to use the software ID as the application name - * @return The application name - */ - public static String getApplicationName(RegistrationRequest request, boolean useSoftwareIdAsAppName) { - if (useSoftwareIdAsAppName) { - // If the request does not contain a software statement, get the software Id directly from the request - if (StringUtils.isEmpty(request.getSoftwareStatement())) { - return request.getSoftwareId(); - } - return request.getSoftwareStatementBody().getSoftwareId(); - } - return RegistrationUtils.getSafeApplicationName(request.getSoftwareStatementBody().getClientName()); - } - - /** - * Retrieves the JWKS URI from the registration request based on the presence of the software statement. - * - * @param registrationRequest registration or update request - * @param jwksEndpointName name used for the JWKS endpoint in the software statement - * @return JWKS URI. - */ - public static String getJwksUriFromRequest(RegistrationRequest registrationRequest, String jwksEndpointName) { - if (StringUtils.isEmpty(registrationRequest.getSoftwareStatement())) { - return registrationRequest.getJwksURI(); - } - if (StringUtils.isNotEmpty(jwksEndpointName)) { - return registrationRequest.getSsaParameters().get(jwksEndpointName).toString(); - } - return registrationRequest.getSoftwareStatementBody().getJwksURI(); - } - - public static ArrayList getServiceProviderPropertyList - (Map clientMetaData) { - - ArrayList spPropList = new ArrayList<>(); - for (Map.Entry entry : clientMetaData.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - ServiceProviderProperty serviceProviderproperty = new ServiceProviderProperty(); - if (value != null) { - serviceProviderproperty.setDisplayName(key); - serviceProviderproperty.setName(key); - serviceProviderproperty.setValue(value); - spPropList.add(serviceProviderproperty); - } - } - return spPropList; - - } - - public static Map getSpMetaDataMap(List spPropertyList) { - - Map spMetaDataMap = new HashMap<>(); - for (ServiceProviderProperty spProperty : spPropertyList) { - if (spProperty.getValue().contains(DCRCommonConstants.ARRAY_ELEMENT_SEPERATOR)) { - List metaDataList = Stream.of(spProperty.getValue() - .split(DCRCommonConstants.ARRAY_ELEMENT_SEPERATOR)) - .map(String::trim) - .collect(Collectors.toList()); - getJsonElementListFromString(metaDataList); - spMetaDataMap.put(spProperty.getName(), metaDataList); - } else if (spProperty.getValue().contains("{")) { - JsonParser jsonParser = new JsonParser(); - JsonObject jsonObject = ((JsonObject) jsonParser - .parse(spProperty.getValue())); - spMetaDataMap.put(spProperty.getName(), jsonObject); - } else { - spMetaDataMap.put(spProperty.getName(), spProperty.getValue()); - } - - } - return spMetaDataMap; - } - - public static String getSafeApplicationName(String applicationName) { - - if (StringUtils.isEmpty(applicationName)) { - throw new IllegalArgumentException("Application name should be a valid string"); - } - - String sanitizedInput = applicationName.trim().replaceAll(DISALLOWED_CHARS_PATTERN, SUBSTITUTE_STRING); - return StringUtils.abbreviate(sanitizedInput, ABBREVIATED_STRING_LENGTH); - - } - - public static Map getAlteredApplicationAttributes(RegistrationRequest registrationRequest) { - - Map alteredAppAttributeMap = new HashMap<>(); - addAttributes(registrationRequest.getRequestParameters(), alteredAppAttributeMap); - - if (StringUtils.isNotEmpty(registrationRequest.getSoftwareStatement())) { - //add ssa attributes - addAttributes(registrationRequest.getSsaParameters(), alteredAppAttributeMap); - //add ssa issuer - alteredAppAttributeMap.put("ssaIssuer", registrationRequest.getSsaParameters().get("iss").toString()); - } - - return alteredAppAttributeMap; - } - - public static void addAttributes(Map requestAttributes, - Map alteredAttributes) { - - String alteredValue = ""; - for (Map.Entry entry : requestAttributes.entrySet()) { - alteredValue = ""; - if (entry.getValue() instanceof ArrayList) { - - ArrayList list = ((ArrayList) entry.getValue()); - Object lastListElement = new Object(); - if (list.size() > 0) { - lastListElement = list.get(list.size() - 1); - } - getJsonElementList(list); - if (list.size() == 1) { - alteredValue = list.get(0).toString().concat(DCRCommonConstants.ARRAY_ELEMENT_SEPERATOR); - alteredAttributes.put(entry.getKey().toString(), alteredValue); - } else if (list.size() > 0) { - for (Object listElement : list) { - if (!lastListElement.equals(listElement)) { - alteredValue = alteredValue.concat( - listElement.toString().concat(DCRCommonConstants.ARRAY_ELEMENT_SEPERATOR)); - } else { - alteredValue = alteredValue.concat(lastListElement.toString()); - } - } - alteredAttributes.put(entry.getKey().toString(), alteredValue); - } - } else if (entry.getValue() instanceof Map) { - alteredAttributes.put(entry.getKey().toString(), gson.toJson(entry.getValue())); - } else { - //remove unnecessary inverted commas. - if (entry.getValue() != null) { - // This is to handle optional nullable params. - // Ex: "software_on_behalf_of_org":null - alteredAttributes.put(entry.getKey().toString(), entry.getValue().toString()); - } - } - } - } - - public static Map getRegistrationDetailsForResponse(RegistrationRequest registrationRequest) { - - String registrationRequestJson = gson.toJson(registrationRequest); - return gson.fromJson(registrationRequestJson, Map.class); - } - - /** - * Extract headers from a request object. - * - * @param request The request object - * @return Map of header key value pairs - */ - public static Map getHeaders(HttpServletRequest request) { - - Map headers = new HashMap<>(); - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - headers.put(headerName, request.getHeader(headerName)); - } - return headers; - } - - /** - * Util method to extract the payload from a HTTP request object. Can be JSONObject or JSONArray - * - * @param request The HTTP request object - * @return Object payload can be either an instance of JSONObject or JSONArray only. Can be a ConsentException if - * is and error scenario. Error is returned instead of throwing since the error response should be handled by the - * toolkit is the manage scenario. - */ - public static Object getPayload(HttpServletRequest request) throws IOException, - net.minidev.json.parser.ParseException { - - Object payload = new JSONParser(JSONParser.MODE_PERMISSIVE) - .parse(IOUtils.toString(request.getInputStream())); - if (payload == null) { - log.debug("Payload is empty. Returning null"); - return null; - } - if (!(payload instanceof JSONObject || payload instanceof JSONArray)) { - //Not throwing error since error should be formatted by manage toolkit - log.error("Payload is not a JSON. Returning null"); - return null; - } - return payload; - } - - /** - * check whether the elemet is a json and convert to a json. - * - * @param metaDataList meta data property list - */ - public static void getJsonElementList(List metaDataList) { - - for (Iterator iterator = metaDataList.iterator(); iterator.hasNext(); ) { - Object element = iterator.next(); - if (element.toString().contains("{")) { - //Object elementToRemove = element; - metaDataList.set(metaDataList.indexOf(element), gson.toJson(element)); - } - } - } - - public static void getJsonElementListFromString(List metaDataList) { - - for (Iterator iterator = metaDataList.iterator(); iterator.hasNext(); ) { - Object element = iterator.next(); - if (element.toString().contains("{")) { - metaDataList.set(metaDataList.indexOf(element), - new JsonParser().parse(element.toString()).getAsJsonObject()); - } - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/util/ResponseStatus.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/util/ResponseStatus.java deleted file mode 100644 index ab002635..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/java/com/wso2/openbanking/accelerator/identity/dcr/endpoint/impl/util/ResponseStatus.java +++ /dev/null @@ -1,231 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.identity.dcr.endpoint.impl.util; - -/** - * Enum of the supported response status in accelerator. - */ -public enum ResponseStatus { - - /** - * 200 OK, see .... - */ - OK(200, "OK"), - /** - * 201 Created, see .... - */ - CREATED(201, "Created"), - /** - * 202 Accepted, see .... - */ - ACCEPTED(202, "Accepted"), - /** - * 204 No Content, see .... - */ - NO_CONTENT(204, "No Content"), - /** - * 205 Reset Content, see .... - * - * @since 2.0 - */ - RESET_CONTENT(205, "Reset Content"), - /** - * 206 Reset Content, see .... - * - * @since 2.0 - */ - PARTIAL_CONTENT(206, "Partial Content"), - /** - * 301 Moved Permanently, - * see .... - */ - MOVED_PERMANENTLY(301, "Moved Permanently"), - /** - * 302 Found, see .... - * - * @since 2.0 - */ - FOUND(302, "Found"), - /** - * 303 See Other, see .... - */ - SEE_OTHER(303, "See Other"), - /** - * 304 Not Modified, see .... - */ - NOT_MODIFIED(304, "Not Modified"), - /** - * 305 Use Proxy, see .... - * - * @since 2.0 - */ - USE_PROXY(305, "Use Proxy"), - /** - * 307 Temporary Redirect, see .... - */ - TEMPORARY_REDIRECT(307, "Temporary Redirect"), - /** - * 400 Bad Request, see .... - */ - BAD_REQUEST(400, "Bad Request"), - /** - * 401 Unauthorized, see .... - */ - UNAUTHORIZED(401, "Unauthorized"), - /** - * 402 Payment Required, see .... - * - * @since 2.0 - */ - PAYMENT_REQUIRED(402, "Payment Required"), - /** - * 403 Forbidden, see .... - */ - FORBIDDEN(403, "Forbidden"), - /** - * 404 Not Found, see .... - */ - NOT_FOUND(404, "Not Found"), - /** - * 405 Method Not Allowed, see .... - * - * @since 2.0 - */ - METHOD_NOT_ALLOWED(405, "Method Not Allowed"), - /** - * 406 Not Acceptable, see .... - */ - NOT_ACCEPTABLE(406, "Not Acceptable"), - /** - * 409 Conflict, see .... - */ - CONFLICT(409, "Conflict"), - /** - * 410 Gone, see .... - */ - GONE(410, "Gone"), - /** - * 411 Length Required, see .... - * - * @since 2.0 - */ - LENGTH_REQUIRED(411, "Length Required"), - /** - * 412 Precondition Failed, see .... - */ - PRECONDITION_FAILED(412, "Precondition Failed"), - /** - * 413 Request Entity Too Large, see HTTP/1.1 documentation. - * - * @since 2.0 - */ - REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"), - /** - * 414 Request-URI Too Long, - * see .... - * - * @since 2.0 - */ - REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"), - /** - * 415 Unsupported Media Type, see HTTP/1.1 documentation. - */ - UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), - /** - * 416 Requested Range Not Satisfiable, see HTTP/1.1 documentation. - * - * @since 2.0 - */ - REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), - /** - * 417 Expectation Failed, see .... - * - * @since 2.0 - */ - EXPECTATION_FAILED(417, "Expectation Failed"), - /** - * 500 Internal Server Error, - * see .... - */ - INTERNAL_SERVER_ERROR(500, "Internal Server Error"), - /** - * 501 Not Implemented, see .... - * - * @since 2.0 - */ - NOT_IMPLEMENTED(501, "Not Implemented"), - /** - * 503 Service Unavailable, see .... - */ - SERVICE_UNAVAILABLE(503, "Service Unavailable"); - - private final int code; - private final String reason; - - ResponseStatus(final int statusCode, final String reasonPhrase) { - this.code = statusCode; - this.reason = reasonPhrase; - } - - /** - * Get the associated status code. - * - * @return the status code. - */ - public int getStatusCode() { - return code; - } - - /** - * Get the reason phrase. - * - * @return the reason phrase. - */ - public String getReasonPhrase() { - return toString(); - } - - /** - * Get the reason phrase. - * - * @return the reason phrase. - */ - @Override - public String toString() { - return reason; - } - - /** - * Convert a numerical status code into the corresponding Status. - * - * @param statusCode the numerical status code. - * @return the matching Status or null is no matching Status is defined. - */ - public static ResponseStatus fromStatusCode(final int statusCode) { - for (ResponseStatus s : ResponseStatus.values()) { - if (s.code == statusCode) { - return s; - } - } - return null; - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/META-INF/MANIFEST.mf b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/META-INF/MANIFEST.mf deleted file mode 100644 index 9d885be5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/META-INF/MANIFEST.mf +++ /dev/null @@ -1 +0,0 @@ -Manifest-Version: 1.0 diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index b212826c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index 32e98763..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 6eb2b9c3..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.dcr.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - WSO2 Open Banking - Dynamic Client Registration API - WSO2 Open Banking - Dynamic Client Registration API - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/pom.xml deleted file mode 100644 index c5cae4ff..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - open-banking-backend - war - WSO2 Open Banking - Demo Backend - - - - javax.ws.rs - jsr311-api - - - com.github.spotbugs - spotbugs-annotations - ${spotbugs.annotations.version} - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - - - - - - - maven-war-plugin - - WEB-INF/lib/*.jar - api#openbanking#backend - - ${maven-war-plugin.version} - - - org.apache.maven.plugins - maven-compiler-plugin - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/BankException.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/BankException.java deleted file mode 100644 index 96fc5f57..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/BankException.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demo.backend; - -/** - * BankException class. - */ -public class BankException extends Exception { - - public BankException(String msg) { - super(msg); - } - - public BankException(String msg, Throwable e) { - super(msg, e); - } - - public BankException(Throwable throwable) { - super(throwable); - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/BankExceptionHandler.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/BankExceptionHandler.java deleted file mode 100644 index f53f5612..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/BankExceptionHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demo.backend; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * BankExceptionHandler class. - */ -public class BankExceptionHandler implements ExceptionMapper { - - public Response toResponse(BankException exception) { - return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()) - .type(MediaType.APPLICATION_JSON).build(); - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/AccountService.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/AccountService.java deleted file mode 100644 index 3ac2652d..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/AccountService.java +++ /dev/null @@ -1,203 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demo.backend.services; - -import com.wso2.openbanking.accelerator.demo.backend.BankException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - -import java.util.UUID; - -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -/** - * AccountService class. - */ -@Path("/accountservice/") -public class AccountService { - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - @GET - @Path("/accounts/{AccountId}") - @Produces("application/json; charset=utf-8") - public Response getOneAccount(@PathParam("AccountId") String accountId, - @HeaderParam("x-fapi-interaction-id") String xFapiInteractionId, - @HeaderParam("Account-Request-Information") String accountRequestInfo) - throws BankException { - - String response = "{\n" + - " \"Data\": {\n" + - " \"Account\": [\n" + - " {\n" + - " \"AccountId\": \"" + accountId + "\",\n" + - " \"Status\": \"Enabled\",\n" + - " \"StatusUpdateDateTime\": \"2020-04-16T06:06:06+00:00\",\n" + - " \"Currency\": \"GBP\",\n" + - " \"AccountType\": \"Personal\",\n" + - " \"AccountSubType\": \"CurrentAccount\",\n" + - " \"Nickname\": \"Bills\",\n" + - " \"Account\": [{\n" + - " \"SchemeName\": \"SortCodeAccountNumber\",\n" + - " \"Identification\": \"" + accountId + "\",\n" + - " \"Name\": \"Mr Kevin\",\n" + - " \"SecondaryIdentification\": \"00021\"\n" + - " }]\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Links\": {\n" + - " \"Self\": \"https://api.alphabank.com/open-banking/v3.0/accounts/" + accountId + - "\"\n" + - " },\n" + - " \"Meta\": {\n" + - " \"TotalPages\": 1\n" + - " }\n" + - "}"; - - if (xFapiInteractionId == null) { - xFapiInteractionId = UUID.randomUUID().toString(); - } - return Response.status(200).entity(response) - .header("x-fapi-interaction-id", xFapiInteractionId).build(); - - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - @GET - @Path("/accounts/{AccountId}/transactions") - @Produces("application/json; charset=utf-8") - public Response getAccountTransactions(@PathParam("AccountId") String accountId, - @HeaderParam("x-fapi-interaction-id") String xFapiInteractionId, - @HeaderParam("Account-Request-Information") String accountRequestInfo) - throws BankException { - - String response = "{\n" + - " \"Data\": {\n" + - " \"Transaction\": [\n" + - " {\n" + - " \"AccountId\": \"" + accountId + "\",\n" + - " \"TransactionId\": \"123\",\n" + - " \"TransactionReference\": \"Ref 1\",\n" + - " \"Amount\": {\n" + - " \"Amount\": \"10.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"CreditDebitIndicator\": \"" + "Credit" + "\",\n" + - " \"Status\": \"Booked\",\n" + - " \"BookingDateTime\": \"2017-04-05T10:43:07+00:00\",\n" + - " \"ValueDateTime\": \"2017-04-05T10:45:22+00:00\",\n" + - " \"TransactionInformation\": \"Cash from Aubrey\",\n" + - " \"BankTransactionCode\": {\n" + - " \"Code\": \"str\",\n" + - " \"SubCode\": \"str\"\n" + - " },\n" + - " \"ProprietaryBankTransactionCode\": {\n" + - " \"Code\": \"Transfer\",\n" + - " \"Issuer\": \"AlphaBank\"\n" + - " },\n" + - " \"Balance\": {\n" + - " \"Amount\": {\n" + - " \"Amount\": \"230.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"CreditDebitIndicator\": \"Credit\",\n" + - " \"Type\": \"InterimBooked\"\n" + - " }\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Links\": {\n" + - " \"Self\": \"https://api.alphabank.com/open-banking/v3.0/accounts/" + accountId + - "/transactions/\"\n" + - " },\n" + - " \"Meta\": {\n" + - " \"TotalPages\": 1,\n" + - " \"FirstAvailableDateTime\": \"2017-05-03T00:00:00+00:00\",\n" + - " \"LastAvailableDateTime\": \"2017-12-03T00:00:00+00:00\"\n" + - " }\n" + - "}"; - if (xFapiInteractionId == null) { - xFapiInteractionId = UUID.randomUUID().toString(); - } - return Response.status(200).entity(response) - .header("x-fapi-interaction-id", xFapiInteractionId).build(); - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - @GET - @Path("/accounts/{AccountId}/balances") - @Produces("application/json; charset=utf-8") - public Response getAccountBalance(@PathParam("AccountId") String accountId, - @HeaderParam("x-fapi-interaction-id") String xFapiInteractionId, - @HeaderParam("Account-Request-Information") String accountRequestInfo) - throws BankException { - - String response = "{\n" + - " \"Data\": {\n" + - " \"Balance\": [\n" + - " {\n" + - " \"AccountId\": \"" + accountId + "\",\n" + - " \"Amount\": {\n" + - " \"Amount\": \"1230.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"CreditDebitIndicator\": \"Credit\",\n" + - " \"Type\": \"InterimAvailable\",\n" + - " \"DateTime\": \"2017-04-05T10:43:07+00:00\",\n" + - " \"CreditLine\": [\n" + - " {\n" + - " \"Included\": true,\n" + - " \"Amount\": {\n" + - " \"Amount\": \"1000.00\",\n" + - " \"Currency\": \"GBP\"\n" + - " },\n" + - " \"Type\": \"Pre-Agreed\"\n" + - " }\n" + - " ]\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"Links\": {\n" + - " \"Self\": \"https://api.alphabank.com/open-banking/v3.0/accounts/" + accountId + - "/balances/\"\n" + - " },\n" + - " \"Meta\": {\n" + - " \"TotalPages\": 1\n" + - " }\n" + - "}"; - if (xFapiInteractionId == null) { - xFapiInteractionId = UUID.randomUUID().toString(); - } - return Response.status(200).entity(response) - .header("x-fapi-interaction-id", xFapiInteractionId).build(); - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/FundsConfirmationService.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/FundsConfirmationService.java deleted file mode 100644 index b1b540cd..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/FundsConfirmationService.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demo.backend.services; - -import com.wso2.openbanking.accelerator.demo.backend.BankException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; - -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -/** - * FundsConfirmationService class. - */ -@Path("/fundsconfirmationservice/") -public class FundsConfirmationService { - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - JAXRS_ENDPOINT - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - - @POST - @Path("/funds-confirmations") - @Produces("application/json; charset=utf-8") - public Response getAccountBalance(String requestString, - @HeaderParam("x-fapi-interaction-id") String xFapiInteractionId) - throws BankException { - - JSONObject request; - try { - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - request = (JSONObject) parser.parse(requestString); - } catch (ParseException e) { - throw new BankException("Error in casting JSON body " + e); - } - - String consentId = ((JSONObject) request.get("Data")).getAsString("ConsentId"); - String response = "{\n" + - " \"Data\": {\n" + - " \"FundsConfirmationId\": \"836403\",\n" + - " \"ConsentId\": \"" + consentId + "\",\n" + - " \"CreationDateTime\": \"2017-06-02T00:00:00+00:00\",\n" + - " \"FundsAvailable\": true,\n" + - " \"Reference\": \"Purchase02\",\n" + - " \"InstructedAmount\": {\n" + - " \"Amount\": \"20.00\",\n" + - " \"Currency\": \"USD\"\n" + - " }\n" + - " },\n" + - " \"Links\": {\n" + - " \"Self\": \"https://api.alphabank.com/open-banking/v3.0/funds-confirmations/836403\"\n" + - " },\n" + - " \"Meta\": {\n" + - " }\n" + - "}"; - return Response.status(201).entity(response) - .header("x-fapi-interaction-id", xFapiInteractionId).build(); - } -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/PaymentService.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/PaymentService.java deleted file mode 100644 index ffc077fc..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/PaymentService.java +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demo.backend.services; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.demo.backend.BankException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; - -import java.nio.charset.StandardCharsets; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.format.DateTimeFormatter; -import java.util.Base64; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Queue; -import java.util.Random; -import java.util.UUID; - -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -/** - * Payments Service class. - */ -@Path("/paymentservice/") -public class PaymentService { - - public static final String EXPECTED_EXECUTION_TIME = "ExpectedExecutionDateTime"; - public static final String EXPECTED_SETTLEMENT_TIME = "ExpectedSettlementDateTime"; - private static final Map domesticPayments = new HashMap<>(); - private static final int MAX_LIMIT = 500; - private static final Queue domesticPaymentsIdQueue = new LinkedList<>(); - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - @GET - @Path("/payment-consents/{ConsentId}/funds-confirmation") - @Produces("application/json; charset=utf-8") - public Response getPaymentTypeFundsConfirmation(@PathParam("ConsentId") String paymentId) { - - Instant currentDate = Instant.now(); - - String response = "{\n" + - " \"Data\": {\n" + - " \"FundsAvailableResult\": {\n" + - " \"FundsAvailableDateTime\": \"" + currentDate.toString() + "\",\n" + - " \"FundsAvailable\": true\n" + - " }\n" + - " },\n" + - " \"Links\": {\n" + - " \"Self\": \"/pisp/payments/" + paymentId + "/funds-confirmation\"\n" + - " },\n" + - " \"Meta\": {}\n" + - "}"; - - return Response.status(200).entity(response) - .header("x-fapi-interaction-id", UUID.randomUUID().toString()) - .build(); - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - - @POST - @Path("/payments") - @Produces("application/json; charset=utf-8") - public Response paymentSubmission(String requestString, @HeaderParam("x-fapi-interaction-id") String fid, - @HeaderParam("Account-Request-Information") String accountRequestInfo) - throws BankException { - - JSONObject jsonObject; - JSONObject accountRequestInformation; - - try { - accountRequestInformation = getRequest(accountRequestInfo); - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - jsonObject = (JSONObject) parser.parse(requestString); - } catch (ParseException e) { - throw new BankException("Error in casting JSON body " + e); - } - - JSONObject additionalConsentInfo = (JSONObject) accountRequestInformation.get("additionalConsentInfo"); - - JSONObject response = cacheAndGetPaymentResponse(jsonObject, additionalConsentInfo); - return Response.status(201).entity(response.toString()) - .header("x-fapi-interaction-id", fid) - .build(); - - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - - @GET - @Path("/payments/{paymentId}") - @Produces("application/json; charset=utf-8") - public Response getPaymentTypePayment(@PathParam("paymentId") String paymentId) { - - JSONObject responseObject = null; - if (StringUtils.isNotBlank(paymentId)) { - - responseObject = domesticPayments.get(paymentId); - - } - if (responseObject == null) { - responseObject = new JSONObject(); - } - - - return Response.status(200).entity(responseObject.toString()) - .header("x-fapi-interaction-id", "93bac548-d2de-4546-b106-880a5018460d") - .build(); - } - - private static JSONObject getRequest(String json) throws ParseException { - - String[] splitString = json.split("\\."); - String base64EncodedBody = splitString[1]; - String decodedString = null; - decodedString = new String(Base64.getUrlDecoder() - .decode(base64EncodedBody.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); - - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - JSONObject jsonObject = (JSONObject) parser.parse(decodedString); - return jsonObject; - } - - @SuppressFBWarnings("PREDICTABLE_RANDOM") - // Suppressed content - PREDICTABLE_RANDOM - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - private JSONObject cacheAndGetPaymentResponse(JSONObject requestObject, - JSONObject additionalConsentInfo) - throws BankException { - - JSONObject responseObject; - - int randomPIN = new Random().nextInt(100); - - String status; - String paymentIdValue; - - paymentIdValue = ((JSONObject) requestObject.get("Data")).getAsString("ConsentId"); - paymentIdValue = paymentIdValue + "-" + randomPIN; - - status = "AcceptedSettlementCompleted"; - - - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - Date date = new Date(); - String currentDate = dateFormat.format(date); - - String readRefundAccount = additionalConsentInfo.getAsString("ReadRefundAccount"); - String cutOffTimeAcceptable = additionalConsentInfo.getAsString("CutOffTimeAcceptable"); - - try { - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - responseObject = (JSONObject) parser.parse(requestObject.toString()); - - JSONObject dataObject = (JSONObject) responseObject.get("Data"); - - dataObject.put("PaymentId", paymentIdValue); - dataObject.put("Status", status); - dataObject.put("CreationDateTime", currentDate); - dataObject.put("StatusUpdateDateTime", currentDate); - - // Add refund account details if requested during consent initiation - if (Boolean.parseBoolean(readRefundAccount)) { - addRefundAccount(dataObject); - } - - if (Boolean.parseBoolean(cutOffTimeAcceptable)) { - dataObject.put(EXPECTED_EXECUTION_TIME, constructDateTime(1L, - OpenBankingConstants.EXPECTED_EXECUTION_TIME)); - dataObject.put(EXPECTED_SETTLEMENT_TIME, constructDateTime(1L, - OpenBankingConstants.EXPECTED_SETTLEMENT_TIME)); - } - - JSONObject linksObject = new JSONObject(); - linksObject.put("Self", "/payments/" + paymentIdValue); - responseObject.put("Links", linksObject); - - JSONObject metaObject = new JSONObject(); - responseObject.put("Meta", metaObject); - - responseObject.remove("Risk"); - - } catch (ParseException e) { - throw new BankException(e); - } - addToCache(paymentIdValue, responseObject); - return responseObject; - } - - /** - * Add Refund account details to the response. - * - * @param dataObject - */ - private void addRefundAccount(JSONObject dataObject) { - - String schemeName = "OB.SortCodeAccountNumber"; - String identification = "Identification"; - String name = "NTPC Inc"; - - JSONObject accountData = new JSONObject(); - accountData.put("SchemeName", schemeName); - accountData.put("Identification", identification); - accountData.put("Name", name); - - JSONObject account = new JSONObject(); - account.put("Account", accountData); - - dataObject.put("Refund", account); - } - - public static String constructDateTime(long daysToAdd, String configToRead) { - - OpenBankingConfigParser parser = OpenBankingConfigParser.getInstance(); - String time = (String) parser.getConfiguration().get(configToRead); - String dateValue = LocalDate.now().plusDays(daysToAdd) + "T" + (OffsetTime.parse(time)); - - OffsetDateTime offSetDateVal = OffsetDateTime.parse(dateValue); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"); - return dateTimeFormatter.format(offSetDateVal); - } - - private void addToCache(String paymentIdValue, JSONObject responseObject) { - - if (domesticPayments.size() > MAX_LIMIT) { - // Max limit reached - domesticPayments.remove(domesticPaymentsIdQueue.poll()); - } - domesticPayments.put(paymentIdValue, responseObject); - domesticPaymentsIdQueue.add(paymentIdValue); - - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/VrpService.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/VrpService.java deleted file mode 100644 index 14ce852c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/java/com/wso2/openbanking/accelerator/demo/backend/services/VrpService.java +++ /dev/null @@ -1,290 +0,0 @@ -/** - * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). - *

- * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.wso2.openbanking.accelerator.demo.backend.services; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.demo.backend.BankException; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; - -import java.nio.charset.StandardCharsets; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.format.DateTimeFormatter; -import java.util.Base64; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Queue; -import java.util.Random; -import java.util.UUID; - - -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - - -/** - * Vrp Service class. - */ -@Path("/vrpservice/") -public class VrpService { - - public static final String EXPECTED_EXECUTION_TIME = "ExpectedExecutionDateTime"; - public static final String EXPECTED_SETTLEMENT_TIME = "ExpectedSettlementDateTime"; - private static final int MAX_LIMIT = 500; - private static final Queue domesticVRPsIdQueue = new LinkedList<>(); - private static final Map domesticVRPs = new HashMap<>(); - - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - @GET - @Path("/domestic-vrp-consents/{ConsentId}/funds-confirmation") - @Produces("application/json; charset=utf-8") - public Response getPaymentTypeFundsConfirmation(@PathParam("ConsentId") String domesticVRPId) { - - Instant currentDate = Instant.now(); - - String response = "{\n" + - " \"Data\": {\n" + - " \"FundsAvailableResult\": {\n" + - " \"FundsAvailableDateTime\": \"" + currentDate.toString() + "\",\n" + - " \"FundsAvailable\": true\n" + - " }\n" + - " },\n" + - " \"Links\": {\n" + - " \"Self\": \"/vrp/domestic-vrps/" + domesticVRPId + "/funds-confirmation\"\n" + - " },\n" + - " \"Meta\": {}\n" + - "}"; - - return Response.status(200).entity(response) - .header("x-fapi-interaction-id", UUID.randomUUID().toString()) - .build(); - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - - @POST - @Path("/domestic-vrps") - @Produces("application/json; charset=utf-8") - public Response paymentSubmission(String requestString, @PathParam("paymentType") String paymentType, - @HeaderParam("x-fapi-interaction-id") String fid, - @HeaderParam("Account-Request-Information") String accountRequestInfo) - throws BankException { - - JSONObject jsonObject; - JSONObject accountRequestInformation; - - try { - accountRequestInformation = getRequest(paymentType, accountRequestInfo); - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - jsonObject = (JSONObject) parser.parse(requestString); - } catch (ParseException e) { - throw new BankException("Error in casting JSON body " + e); - } - - JSONObject additionalConsentInfo = (JSONObject) accountRequestInformation.get("additionalConsentInfo"); - - JSONObject response = cacheAndGetPaymentResponse(paymentType, jsonObject, additionalConsentInfo); - return Response.status(201).entity(response.toString()) - .header("x-fapi-interaction-id", fid) - .build(); - - } - - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - - @GET - @Path("/domestic-vrps/{domesticVRPId}") - @Produces("application/json; charset=utf-8") - public Response getPaymentTypePayment(@PathParam("domesticVRPId") String domesticVRPId) { - - JSONObject responseObject = null; - if (StringUtils.isNotBlank(domesticVRPId)) { - - responseObject = domesticVRPs.get(domesticVRPId); - - } - if (responseObject == null) { - responseObject = new JSONObject(); - } - - - return Response.status(200).entity(responseObject.toString()) - .header("x-fapi-interaction-id", "93bac548-d2de-4546-b106-880a5018460d") - .build(); - } - - - private static JSONObject getRequest(String paymentType, String json) throws ParseException { - - String[] splitString = json.split("\\."); - String base64EncodedBody = splitString[1]; - String decodedString = null; - decodedString = new String(Base64.getUrlDecoder() - .decode(base64EncodedBody.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); - - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - JSONObject jsonObject = (JSONObject) parser.parse(decodedString); - return jsonObject; - } - - - @SuppressFBWarnings("PREDICTABLE_RANDOM") - // Suppressed content - PREDICTABLE_RANDOM - // Suppression reason - False Positive : This endpoint is a demo endpoint that is not exposed in production - // Suppressed warning count - 1 - private JSONObject cacheAndGetPaymentResponse(String paymentType, JSONObject requestObject, - JSONObject additionalConsentInfo) - throws BankException { - - JSONObject responseObject; - - int randomPIN = new Random().nextInt(100); - - String status; - String paymentIdValue; - - paymentIdValue = ((JSONObject) requestObject.get("Data")).getAsString("ConsentId"); - paymentIdValue = paymentIdValue + "-" + randomPIN; - - status = "AcceptedSettlementCompleted"; - - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - Date date = new Date(); - String currentDate = dateFormat.format(date); - - String readRefundAccount = additionalConsentInfo.getAsString("ReadRefundAccount"); - String cutOffTimeAcceptable = additionalConsentInfo.getAsString("CutOffTimeAcceptable"); - - try { - JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - responseObject = (JSONObject) parser.parse(requestObject.toString()); - - JSONObject dataObject = (JSONObject) responseObject.get("Data"); - - dataObject.put("DomesticVRPId", paymentIdValue); - dataObject.put("Status", status); - dataObject.put("CreationDateTime", currentDate); - dataObject.put("StatusUpdateDateTime", currentDate); - - if ("domestic-vrps".equals(paymentType)) { - JSONObject debtorAccount = new JSONObject(); - debtorAccount.put("SchemeName", "SortCodeAccountNumber"); - debtorAccount.put("SecondaryIdentification", "Roll 2901"); - debtorAccount.put("Name", "Deb Mal"); - debtorAccount.put("Identification", additionalConsentInfo.getAsString("AccountIds") - .split(":")[0].replace("[\"", "")); - - dataObject.put("DebtorAccount", debtorAccount); - - } - - // Add refund account details if requested during consent initiation - if (Boolean.parseBoolean(readRefundAccount)) { - addRefundAccount(dataObject); - } - - if (Boolean.parseBoolean(cutOffTimeAcceptable)) { - dataObject.put(EXPECTED_EXECUTION_TIME, constructDateTime(1L, - OpenBankingConstants.EXPECTED_EXECUTION_TIME)); - dataObject.put(EXPECTED_SETTLEMENT_TIME, constructDateTime(1L, - OpenBankingConstants.EXPECTED_SETTLEMENT_TIME)); - } - - JSONObject linksObject = new JSONObject(); - linksObject.put("Self", "/domestic-vrps/" + paymentIdValue); - responseObject.put("Links", linksObject); - - JSONObject metaObject = new JSONObject(); - responseObject.put("Meta", metaObject); - - } catch (ParseException e) { - throw new BankException(e); - } - addToCache(paymentIdValue, responseObject); - return responseObject; - } - - /** - * Add Refund account details to the response. - * - * @param dataObject - */ - private void addRefundAccount(JSONObject dataObject) { - - String schemeName = "OB.SortCodeAccountNumber"; - String identification = "Identification"; - String name = "NTPC Inc"; - - JSONObject accountData = new JSONObject(); - accountData.put("SchemeName", schemeName); - accountData.put("Identification", identification); - accountData.put("Name", name); - - JSONObject account = new JSONObject(); - account.put("Account", accountData); - - dataObject.put("Refund", account); - } - - public static String constructDateTime(long daysToAdd, String configToRead) { - - OpenBankingConfigParser parser = OpenBankingConfigParser.getInstance(); - String time = (String) parser.getConfiguration().get(configToRead); - String dateValue = LocalDate.now().plusDays(daysToAdd) + "T" + (OffsetTime.parse(time)); - - OffsetDateTime offSetDateVal = OffsetDateTime.parse(dateValue); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"); - return dateTimeFormatter.format(offSetDateVal); - } - - private void addToCache(String paymentIdValue, JSONObject responseObject) { - - if (domesticVRPs.size() > MAX_LIMIT) { - // Max limit reached - domesticVRPs.remove(domesticVRPsIdQueue.poll()); - } - domesticVRPs.put(paymentIdValue, responseObject); - domesticVRPsIdQueue.add(paymentIdValue); - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index fe6f12f8..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/WEB-INF/cxf-servlet.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 71138c28..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 7fa90a98..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demo.backend/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - Open-Banking - - - JAXServlet - JAX-WS/JAX-RS Servlet - JAX-WS/JAX-RS Endpoint - - org.apache.cxf.transport.servlet.CXFServlet - - - service-list-stylesheet - servicelist.css - - - jersey.config.server.provider.classnames - org.glassfish.jersey.media.multipart.MultiPartFeature - - - 1 - - - - JAXServlet - /services/* - - - - 60 - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/pom.xml deleted file mode 100644 index 24cf3bb7..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - - open-banking - com.wso2.openbanking.accelerator - 3.2.0-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - openbanking-accelerator-demosite-endpoint - war - WSO2 Open Banking - Demo-site Backend Endpoint - - - - commons-logging - commons-logging - - - io.rest-assured - rest-assured - compile - - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - javax.ws.rs - jsr311-api - - - - - com.fasterxml.jackson.core - jackson-databind - provided - - - net.minidev - json-smart - provided - - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#demosite - WEB-INF/lib/slf4j-api-*.jar - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - High - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/api/JWTGeneratorEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/api/JWTGeneratorEndpoint.java deleted file mode 100644 index fad588b5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/api/JWTGeneratorEndpoint.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demosite.endpoint.api; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.demosite.endpoint.model.JWTGeneratorEndpointErrorResponse; -import com.wso2.openbanking.accelerator.demosite.endpoint.model.PayloadData; -import com.wso2.openbanking.accelerator.demosite.endpoint.util.GeneratorUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -/** - * Demo-site Endpoint - * This specifies the RESTful APIs to generate the payloads required to try out the OB flows in the demo-site. - */ -@Path("/") -public class JWTGeneratorEndpoint { - - private static Log log = LogFactory.getLog(JWTGeneratorEndpoint.class); - - /** - * Generate the RequestObject, DCR Payload and Token Assertion - */ - @POST - @Path("/getJWT") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - public Response getJWT(@Context HttpServletRequest request, @Context HttpServletResponse response, - MultivaluedMap parameterMap) { - String requestPayload; - try { - requestPayload = new ObjectMapper().writeValueAsString(parameterMap); - } catch (JsonProcessingException e) { - String error = "Error in formatting the request payload"; - log.error(error, e); - JWTGeneratorEndpointErrorResponse errorResponse = GeneratorUtil.createErrorResponse(400, error); - return Response.status(400).entity(errorResponse.getPayload()).build(); - } - PayloadData data = new Gson().fromJson(requestPayload.replaceAll("\\\\r|\\\\n|\\r|\\n|\\[|]", ""), - PayloadData.class); - try { - return Response.status(201).entity(GeneratorUtil.generateJWT(data)).build(); - } catch (OpenBankingException e) { - String error = "Error occurred while building the JWT"; - log.error(error, e); - JWTGeneratorEndpointErrorResponse errorResponse = GeneratorUtil.createErrorResponse(500, error); - return Response.status(500).entity(errorResponse.getPayload()).build(); - } - } - - /** - * Update key and certificate used to sign the JWT content - */ - @GET - @Path("/updateCerts") - @Produces({"application/json; charset=utf-8"}) - public Response updateCertificates(@Context HttpServletRequest request, @Context HttpServletResponse response) { - try { - return Response.status(201).entity(GeneratorUtil.updateConfigurations()).build(); - } catch (OpenBankingException e) { - String error = "Error occurred while updating the certificates"; - log.error(error, e); - JWTGeneratorEndpointErrorResponse errorResponse = GeneratorUtil.createErrorResponse(500, error); - return Response.status(500).entity(errorResponse.getPayload()).build(); - } - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/model/JWTGeneratorEndpointErrorResponse.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/model/JWTGeneratorEndpointErrorResponse.java deleted file mode 100644 index e6f07eb4..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/model/JWTGeneratorEndpointErrorResponse.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demosite.endpoint.model; - -import net.minidev.json.JSONObject; - -/** - * Demo-site JWT generator endpoint error response - */ -public class JWTGeneratorEndpointErrorResponse { - - private int httpStatusCode = 0; - private JSONObject payload = null; - - public int getHttpStatusCode() { - - return httpStatusCode; - } - public void setHttpStatusCode(int httpStatusCode) { - - this.httpStatusCode = httpStatusCode; - } - - public JSONObject getPayload() { - - return payload; - } - public void setPayload(JSONObject payload) { - - this.payload = payload; - } - -} - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/model/PayloadData.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/model/PayloadData.java deleted file mode 100644 index b5a42dcf..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/model/PayloadData.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demosite.endpoint.model; - -/** - * Data wrapper for the request payload data. - */ -public class PayloadData { - - private String clientId; - private String payload; - private String redirectUri; - private String consentId; - private String scopes; - private String type; - private String apiName; - private String ssa; - private String softwareId; - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public String getRedirectUri() { - return redirectUri; - } - - public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } - - public String getConsentId() { - return consentId; - } - - public void setConsentId(String consentId) { - this.consentId = consentId; - } - - public String getScopes() { - return scopes; - } - - public void setScopes(String scopes) { - this.scopes = scopes; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getApiName() { - return apiName; - } - - public void setApiName(String apiName) { - this.apiName = apiName; - } - - public String getSsa() { - return ssa; - } - - public void setSsa(String ssa) { - this.ssa = ssa; - } - - public String getSoftwareId() { - return softwareId; - } - - public void setSoftwareId(String softwareId) { - this.softwareId = softwareId; - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/util/GeneratorUtil.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/util/GeneratorUtil.java deleted file mode 100644 index 2423ff79..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/java/com/wso2/openbanking/accelerator/demosite/endpoint/util/GeneratorUtil.java +++ /dev/null @@ -1,434 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.demosite.endpoint.util; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JOSEObjectType; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.jwk.RSAKey; -import com.wso2.openbanking.accelerator.common.exception.OpenBankingException; -import com.wso2.openbanking.accelerator.demosite.endpoint.model.JWTGeneratorEndpointErrorResponse; -import com.wso2.openbanking.accelerator.demosite.endpoint.model.PayloadData; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.time.Instant; -import java.util.Base64; -import java.util.Locale; -import java.util.Properties; -import java.util.UUID; - -/** - * Utils class for the demo-site JWTGenerator endpoint - */ -public class GeneratorUtil { - - private static final Log log = LogFactory.getLog(GeneratorUtil.class); - private static final JWSAlgorithm DEFAULT_ALGORITHM = JWSAlgorithm.PS256; - private static String certPath = ""; - private static String keyPath = ""; - private static String serverDomain = ""; - private static String port = ""; - private static boolean isExternalLink = false; - private static String kid = ""; - private static Certificate certificate = null; - private static JWSSigner signer = null; - - /** - * Generate the JWT required for token assertion, request object and DCR payload - * - * @param requestData Request data object which contains request parameters - * @return The signed JWT - * @throws OpenBankingException - */ - public static String generateJWT(PayloadData requestData) throws OpenBankingException { - - JWSHeader header; - Payload payload; - String appName = null; - - if (certificate == null || signer == null || kid.equals("") || serverDomain.equals("") || port.equals("")) { - try { - updateConfigurations(); - } catch (OpenBankingException e) { - String error = "Error in updating certificates"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - if (requestData.getType().toLowerCase(Locale.ENGLISH).contains("dcr")) { - // For DCR app registrations the software ID is set to newApp from the frontend - if (requestData.getSoftwareId().equals("newApp")) { - appName = UUID.randomUUID().toString(); - } else { - appName = requestData.getSoftwareId(); - } - requestData.setSsa(generateSSA(requestData, appName)); - } - header = generateHeader(requestData); - payload = generatePayload(requestData, appName); - - try { - return signJWT(header, payload); - } catch (OpenBankingException e) { - String error = "Error while signing JWT/JWS"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Download and update the stored certificates - * - * @throws OpenBankingException - */ - public static String updateConfigurations() throws OpenBankingException { - try { - InputStream configurations = GeneratorUtil.class.getClassLoader() - .getResourceAsStream("configurations.properties"); - Properties configurationProperties = new Properties(); - configurationProperties.load(configurations); - certPath = configurationProperties.getProperty("CertificateConfigs.CertUrl"); - keyPath = configurationProperties.getProperty("CertificateConfigs.KeyUrl"); - isExternalLink = Boolean.parseBoolean( - configurationProperties.getProperty("CertificateConfigs.IsExternalLink")); - serverDomain = configurationProperties.getProperty("PayloadConfigs.IamDomain"); - port = configurationProperties.getProperty("PayloadConfigs.Port"); - } catch (IOException e) { - String error = "Error occurred while reading the configurations"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - - try { - certificate = getPublicSigningCert(); - signer = new RSASSASigner((PrivateKey) getSigningKey()); - try { - kid = getThumbPrint(certificate); - log.info("The certificates were updated successfully"); - return "Certificates updated successfully"; - } catch (OpenBankingException e) { - String error = "Error when getting thumbprint of primary public cert"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } catch (OpenBankingException e) { - String error = "Error when retrieving primary public cert"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Generate SHA-1 DER Thumbprint. - * - * @param certificate - * @return Thumbprint - * @throws OpenBankingException - */ - private static String getThumbPrint(Certificate certificate) throws OpenBankingException { - - try { - X509Certificate x509cert = (X509Certificate) CertificateFactory.getInstance("X.509") - .generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); - return RSAKey.parse(x509cert).computeThumbprint("SHA-1").toString(); - } catch (CertificateException | JOSEException e) { - String error = "Error occurred while generating SHA-1 JWK thumbprint"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Generate the payload of the JWT - * - * @param requestData Request data object which contains request parameters - * @param appName Name of the application to be created - * @return The payload of the JWT - */ - private static Payload generatePayload(PayloadData requestData, String appName) { - - long initiationTime = Instant.now().getEpochSecond(); - long expirationTime = initiationTime + 3600; - long jtiValue = initiationTime + 10; - String apiName = requestData.getApiName().toLowerCase(Locale.ENGLISH); - String payloadString = ""; - - if (apiName.contains("authorize")) { - payloadString = "{\n" + - " \"max_age\": 86400,\n" + - " \"aud\": \"" + serverDomain + ":" + port + "/oauth2/token\",\n" + - " \"scope\": \"" + requestData.getScopes() + "\",\n" + - " \"iss\": \"" + requestData.getClientId() + "\",\n" + - " \"claims\": {\n" + - " \"id_token\": {\n" + - " \"acr\": {\n" + - " \"values\": [\n" + - " \"urn:openbanking:psd2:sca\",\n" + - " \"urn:openbanking:psd2:ca\"\n" + - " ],\n" + - " \"essential\": true\n" + - " },\n" + - " \"openbanking_intent_id\": {\n" + - " \"value\": \"" + requestData.getConsentId() + "\",\n" + - " \"essential\": true\n" + - " }\n" + - " },\n" + - " \"userinfo\": {\n" + - " \"openbanking_intent_id\": {\n" + - " \"value\": \"" + requestData.getConsentId() + "\",\n" + - " \"essential\": true\n" + - " }\n" + - " }\n" + - " },\n" + - " \"response_type\": \"code id_token\",\n" + - " \"redirect_uri\": \"" + requestData.getRedirectUri() + "\",\n" + - " \"state\": \"YWlzcDozMTQ2\",\n" + - " \"exp\": " + expirationTime + ",\n" + - " \"nonce\": \"n-0S6_WzA2M0000025\",\n" + - " \"client_id\": \"" + requestData.getClientId() + "\"\n" + - "}"; - } else if (apiName.contains("token")) { - payloadString = "{\n" + - " \"iss\": \"" + requestData.getClientId() + "\",\n" + - " \"sub\": \"" + requestData.getClientId() + "\",\n" + - " \"exp\": " + expirationTime + ",\n" + - " \"iat\": " + initiationTime + ",\n" + - " \"jti\": \"" + jtiValue + "\",\n" + - " \"aud\": \"" + serverDomain + ":" + port + "/oauth2/token\"\n" + - "}"; - } else if (apiName.contains("dynamic")) { - payloadString = "{\n" + - " \"iss\": \"" + appName + "\",\n" + - " \"iat\": " + initiationTime + ",\n" + - " \"exp\": " + expirationTime + ",\n" + - " \"jti\": \"" + jtiValue + "\",\n" + - " \"aud\": \"https://localbank.com\",\n" + - " \"scope\": \"accounts payments\",\n" + - " \"token_endpoint_auth_method\": \"private_key_jwt\",\n" + - " \"token_endpoint_auth_signing_alg\": \"PS256\",\n" + - " \"grant_types\": [\n" + - " \"authorization_code\",\n" + - " \"client_credentials\",\n" + - " \"refresh_token\"\n" + - " ],\n" + - " \"response_types\": [\n" + - " \"code id_token\"\n" + - " ],\n" + - " \"id_token_signed_response_alg\": \"PS256\",\n" + - " \"request_object_signing_alg\": \"PS256\",\n" + - " \"application_type\": \"web\",\n" + - " \"software_id\": \"" + appName + "\",\n" + - " \"redirect_uris\": [\n" + - " \"" + serverDomain + "/ob/authenticationendpoint/auth_code.do\"\n" + - " ],\n" + - " \"software_statement\": \"" + requestData.getSsa() + "\"\n" + - "}"; - } - return new Payload(payloadString); - } - - /** - * Extract the signing key from the keystore - * - * @return The signing key - * @throws OpenBankingException - */ - private static PrivateKey getSigningKey() throws OpenBankingException { - try { - if (isExternalLink) { - Files.copy(new URL(keyPath).openStream(), Paths.get("key.key"), StandardCopyOption.REPLACE_EXISTING); - } else { - Files.copy(GeneratorUtil.class.getClassLoader().getResourceAsStream("signing.key"), - Paths.get("key.key"), StandardCopyOption.REPLACE_EXISTING); - } - String privateKeyPath = "key.key"; - String keyContent = new String(Files.readAllBytes(Paths.get(privateKeyPath)), StandardCharsets.UTF_8); - keyContent = keyContent.replace("-----BEGIN PRIVATE KEY-----", ""); - keyContent = keyContent.replace("-----END PRIVATE KEY-----", ""); - keyContent = keyContent.replace("\n", ""); - return KeyFactory.getInstance("RSA") - .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(keyContent))); - } catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) { - String error = "Error in extracting the signing private key"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Extract the certificate from the keystore - * - * @return The certificate - * @throws OpenBankingException - */ - private static Certificate getPublicSigningCert() throws OpenBankingException { - try { - if (isExternalLink) { - Files.copy(new URL(certPath).openStream(), Paths.get("cert.pem"), StandardCopyOption.REPLACE_EXISTING); - } else { - Files.copy(GeneratorUtil.class.getClassLoader().getResourceAsStream("signing.pem"), - Paths.get("cert.pem"), StandardCopyOption.REPLACE_EXISTING); - } - String publicCertPath = "cert.pem"; - return CertificateFactory.getInstance("X.509").generateCertificate( - new FileInputStream(publicCertPath)); - } catch (CertificateException | IOException e) { - String error = "Error in extracting the signing certificate"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Sign the JWT including header and payload content - * - * @param header Header content of the JWT - * @param payload Payload content of the JWT - * @return signed JWT - * @throws OpenBankingException - */ - private static String signJWT(JWSHeader header, Payload payload) throws OpenBankingException { - - JWSObject jwsObject = new JWSObject(header, payload); - try { - jwsObject.sign(signer); - log.info("The JWT was generated successfully"); - return jwsObject.serialize(); - } catch (JOSEException e) { - String error = "Unable to sign JWT with signer"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Generate SSA payload of the DCR App - * - * @param requestData Request data object which contains request parameters - * @param appName Name of the application to be created - * @return SSA payload - * @throws OpenBankingException - */ - private static String generateSSA(PayloadData requestData, String appName) throws OpenBankingException { - long initiationTime = Instant.now().getEpochSecond(); - long expirationTime = initiationTime + 3600; - long jtiValue = initiationTime + 10; - String requestType = requestData.getType(); - - String ssaContent = new String(Base64.getUrlDecoder() - .decode(requestData.getSsa().split("\\.")[1]), StandardCharsets.UTF_8); - JSONObject ssaContentObject = new JSONObject(ssaContent); - ssaContentObject.remove("iat"); - ssaContentObject.put("iat", initiationTime); - ssaContentObject.remove("exp"); - ssaContentObject.put("exp", expirationTime); - ssaContentObject.remove("jti"); - ssaContentObject.put("jti", String.valueOf(jtiValue)); - ssaContentObject.remove("software_id"); - ssaContentObject.put("software_id", appName); - ssaContentObject.remove("software_client_id"); - ssaContentObject.put("software_client_id", appName); - ssaContentObject.remove("software_redirect_uris"); - String[] redirectUris = { serverDomain + "/ob/authenticationendpoint/auth_code.do" }; - ssaContentObject.put("software_redirect_uris", redirectUris); - requestData.setType("ssa"); - - JWSHeader header = generateHeader(requestData); - requestData.setType(requestType); - try { - return signJWT(header, new Payload(ssaContentObject.toString())); - } catch (OpenBankingException e) { - String error = "Error while signing JWT/JWS"; - log.error(error, e); - throw new OpenBankingException(error, e); - } - } - - /** - * Generate the header of the JWT - * - * @param requestData Request data object which contains request parameters - * @return The header of the JWT - */ - private static JWSHeader generateHeader(PayloadData requestData) { - - String type = requestData.getType().toLowerCase(Locale.ENGLISH); - JWSHeader header; - if (type.contains("ssa")) { - header = new JWSHeader.Builder(DEFAULT_ALGORITHM) - .keyID(kid) - .type(JOSEObjectType.JWT) - .build(); - } else if (type.contains("dcr")) { - header = new JWSHeader.Builder(DEFAULT_ALGORITHM) - .keyID(kid) - .build(); - } else { - header = new JWSHeader.Builder(DEFAULT_ALGORITHM) - .keyID(kid) - .build(); - } - return header; - } - - /** - * Generate error response in case of an exception that may occur when processing the request - * - * @param httpStatusCode Status code of the error encountered - * @param errorDescription Description of the error encountered - * @return Error response - */ - public static JWTGeneratorEndpointErrorResponse createErrorResponse(int httpStatusCode, String errorDescription) { - - JWTGeneratorEndpointErrorResponse demositeErrorResponse = new JWTGeneratorEndpointErrorResponse(); - net.minidev.json.JSONObject errorResponse = new net.minidev.json.JSONObject(); - errorResponse.put("error_description", errorDescription); - demositeErrorResponse.setPayload(errorResponse); - demositeErrorResponse.setHttpStatusCode(httpStatusCode); - - return demositeErrorResponse; - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/resources/configurations.properties b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/resources/configurations.properties deleted file mode 100644 index 713ec04f..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/resources/configurations.properties +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). -# -# WSO2 LLC. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -CertificateConfigs.CertUrl = null -CertificateConfigs.KeyUrl = null -CertificateConfigs.IsExternalLink = false -PayloadConfigs.IamDomain = https://localhost -PayloadConfigs.Port = 9446 diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index b212826c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index 73766b03..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b86062ad..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.demosite.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - WSO2 Open Banking - Demo-site Backend Endpoint - WSO2 Open Banking - Demo-site Backend Endpoint - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/findbugs-exclude.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/findbugs-exclude.xml deleted file mode 100644 index 262dbed5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/findbugs-exclude.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/pom.xml deleted file mode 100644 index cdd54d0a..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/pom.xml +++ /dev/null @@ -1,172 +0,0 @@ - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - openbanking-event-notifications-endpoint - war - WSO2 Open Banking - Event Notifications Endpoint - - - - io.swagger - swagger-jaxrs - - - javax.ws.rs - jsr311-api - - - com.google.guava - guava - - - org.yaml - snakeyaml - - - - - javax.validation - validation-api - provided - - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.common - provided - - - javax.ws.rs - jsr311-api - - - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.dcr - provided - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.mgt - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - io.swagger - swagger-annotations - - - javax.ws.rs - jsr311-api - - - - - net.minidev - json-smart - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.event.notifications.service - - - javax.ws.rs - jsr311-api - - - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.extensions - provided - - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#event-notifications - WEB-INF/lib/slf4j-api-*.jar - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventCreationEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventCreationEndpoint.java deleted file mode 100644 index 31103497..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventCreationEndpoint.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.endpoint.api; - -import com.wso2.openbanking.accelerator.event.notifications.endpoint.constants.EventNotificationEndPointConstants; -import com.wso2.openbanking.accelerator.event.notifications.endpoint.util.EventNotificationUtils; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.NotificationCreationDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventCreationServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.swagger.annotations.ApiOperation; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -/** - * Events creation API. - */ -@Path("/") -public class EventCreationEndpoint { - - private static final Log log = LogFactory.getLog(EventCreationEndpoint.class); - private static final EventCreationServiceHandler eventCreationServiceHandler = EventNotificationUtils. - getEventNotificationCreationServiceHandler(); - private static final String specialChars = "!@#$%&*()'+,./:;<=>?[]^_`{|}"; - - /** - * This API will be used to create events. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is secured with access control lists in the configuration - // Suppressed content - request.getHeader() - // Suppression reason - False Positive : Header is properly validated to ensure no special characters are passed - // Suppressed warning count - 4 - @POST - @Path("/create-events") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8"}) - - @ApiOperation(value = "Create Events", tags = {" Create Events"}) - public Response createEvents(@Context HttpServletRequest request, @Context HttpServletResponse response, - MultivaluedMap parameterMap) { - - - NotificationCreationDTO notificationCreationDTO = new NotificationCreationDTO(); - String requestData = StringUtils.EMPTY; - JSONObject notificationEvents; - - try { - //Check if the request pay load is empty - if (!parameterMap.isEmpty() && parameterMap.containsKey(EventNotificationEndPointConstants.REQUEST)) { - - requestData = parameterMap.get(EventNotificationEndPointConstants.REQUEST). - toString().replaceAll("\\\\r|\\\\n|\\r|\\n|\\[|]| ", StringUtils.EMPTY); - - byte[] decodedBytes = Base64.getDecoder().decode(requestData); - String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); - notificationEvents = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(decodedString); - log.debug("Decoded payload string : " + decodedString.replaceAll("[\r\n]", "")); - - } else { - - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.MISSING_REQUEST_PAYLOAD, - EventNotificationConstants.MISSING_REQ_PAYLOAD)).build(); - } - - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (!StringUtils.isBlank(clientId)) { - notificationCreationDTO.setClientId(request.getHeader( - EventNotificationEndPointConstants.X_WSO2_CLIENT_ID)); - } else { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - - //check if the resource id is present in the header - String resourceId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_RESOURCE_ID); - if (!StringUtils.isBlank(resourceId)) { - if (StringUtils.containsAny(resourceId, specialChars)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.INVALID_REQUEST_HEADER, - EventNotificationConstants.INVALID_CHARS_IN_HEADER_ERROR)).build(); - } - notificationCreationDTO.setResourceId(request.getHeader( - EventNotificationEndPointConstants.X_WSO2_RESOURCE_ID));; - } else { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_RESOURCE_ID)).build(); - } - - //set events to notificationCreationDTO - JSONObject finalNotificationEvents = notificationEvents; - notificationEvents.keySet().forEach(eventName -> { - JSONObject eventInformation = (JSONObject) finalNotificationEvents.get(eventName); - notificationCreationDTO.setEventPayload(eventName, eventInformation); - }); - - } catch (ParseException e) { - log.error("Error while parsing the request payload", e); - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils - .getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR)).build(); - } catch (ClassCastException e) { - log.error(EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR, e); - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils - .getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR)).build(); - } - - EventCreationResponse eventCreationResponse = eventCreationServiceHandler. - publishOBEvent(notificationCreationDTO); - - return EventNotificationUtils.mapEventCreationServiceResponse(eventCreationResponse); - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventPollingEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventPollingEndpoint.java deleted file mode 100644 index 9ab95c6e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventPollingEndpoint.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.endpoint.api; - -import com.wso2.openbanking.accelerator.event.notifications.endpoint.constants.EventNotificationEndPointConstants; -import com.wso2.openbanking.accelerator.event.notifications.endpoint.util.EventNotificationUtils; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventPollingServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventPollingResponse; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.swagger.annotations.ApiOperation; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -/** - * Aggregated Event Polling API Specification. - * - *

Swagger for Aggregated Event Polling API Specification - */ -@Path("/events") -public class EventPollingEndpoint { - - private static final Log log = LogFactory.getLog(EventCreationEndpoint.class); - private static final EventPollingServiceHandler eventPollingServiceHandler = EventNotificationUtils. - getEventPollingServiceHandler(); - - /** - * Retrieve Event Notifications Using Aggregated Polling. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is secured with access control lists in the configuration - // Suppressed content - request.getHeader() - // Suppression reason - False Positive : Header is properly validated to ensure no special characters are passed - // Suppressed warning count - 4 - @POST - @Path("/{s:.*}") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json; charset=utf-8", "application/jose+jwe"}) - @ApiOperation(value = "Retrieve Events", tags = {"Events"}) - - public Response pollEvents(@Context HttpServletRequest request, @Context HttpServletResponse response, - MultivaluedMap parameterMap) { - - String eventPollingData; - JSONObject eventPollingRequest; - - if (!parameterMap.isEmpty() && parameterMap.containsKey(EventNotificationEndPointConstants.REQUEST)) { - - eventPollingData = parameterMap.get(EventNotificationEndPointConstants.REQUEST). - toString().replaceAll("\\\\r|\\\\n|\\r|\\n|\\[|]| ", StringUtils.EMPTY); - - if (StringUtils.isNotBlank(eventPollingData)) { - byte[] decodedBytes = Base64.getDecoder().decode(eventPollingData); - String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); - try { - eventPollingRequest = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(decodedString); - - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationConstants.X_WSO2_CLIENT_ID); - if (!StringUtils.isBlank(clientId)) { - eventPollingRequest.put(EventNotificationConstants.X_WSO2_CLIENT_ID, request. - getHeader(EventNotificationConstants.X_WSO2_CLIENT_ID)); - } else { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - - EventPollingResponse eventPollingResponse = eventPollingServiceHandler. - pollEvents(eventPollingRequest); - - return EventNotificationUtils.mapEventPollingServiceResponse(eventPollingResponse); - - } catch (ParseException e) { - log.error("Exception when parsing the request payload", e); - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR)).build(); - } catch (ClassCastException e) { - log.error(EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR, e); - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR)).build(); - } - } else { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.EMPTY_REQ_PAYLOAD)).build(); - } - } else { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.MISSING_REQUEST_PAYLOAD, - EventNotificationConstants.MISSING_REQ_PAYLOAD)).build(); - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventSubscriptionEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventSubscriptionEndpoint.java deleted file mode 100644 index c5f2693b..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/api/EventSubscriptionEndpoint.java +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.endpoint.api; - -import com.wso2.openbanking.accelerator.event.notifications.endpoint.constants.EventNotificationEndPointConstants; -import com.wso2.openbanking.accelerator.event.notifications.endpoint.util.EventNotificationUtils; -import com.wso2.openbanking.accelerator.event.notifications.endpoint.util.EventSubscriptionUtils; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventSubscriptionDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventSubscriptionServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventSubscriptionResponse; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.swagger.annotations.ApiOperation; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * Events Notification Subscription API. - */ -@Path("/subscription") -public class EventSubscriptionEndpoint { - private static final Log log = LogFactory.getLog(EventSubscriptionEndpoint.class); - - private static final EventSubscriptionServiceHandler eventSubscriptionServiceHandler = EventSubscriptionUtils. - getEventSubscriptionServiceHandler(); - - /** - * Register an Event Notification Subscription. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - @POST - @Path("/") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - @ApiOperation(value = "Create Subscriptions", tags = {" Create Subscriptions"}) - public Response registerSubscription(@Context HttpServletRequest request, @Context HttpServletResponse response) { - - EventSubscriptionDTO eventSubscriptionDTO = new EventSubscriptionDTO(); - - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - eventSubscriptionDTO.setClientId(request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID)); - - // extract the payload from the request - try { - JSONObject requestData = EventSubscriptionUtils.getJSONObjectPayload(request); - if (requestData != null) { - eventSubscriptionDTO.setRequestData(requestData); - } else { - log.error("Subscription request payload is missing"); - return Response.status(Response.Status.BAD_REQUEST). - entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.MISSING_JSON_REQUEST_PAYLOAD)).build(); - } - } catch (IOException e) { - log.error("Invalid Payload received", e); - return Response.status(Response.Status.BAD_REQUEST). - entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR)).build(); - } catch (ParseException e) { - log.error("Failed to parse the payload", e); - return Response.status(Response.Status.BAD_REQUEST). - entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.ERROR_PAYLOAD_PARSE)).build(); - } - EventSubscriptionResponse eventSubscriptionResponse = eventSubscriptionServiceHandler. - createEventSubscription(eventSubscriptionDTO); - return EventSubscriptionUtils.mapEventSubscriptionServiceResponse(eventSubscriptionResponse); - } - - /** - * Retrieve a Single Event Subscription. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - @GET - @Path("/{subscriptionId}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response retrieveSubscription(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - - EventSubscriptionResponse eventSubscriptionResponse = eventSubscriptionServiceHandler. - getEventSubscription(clientId, uriInfo.getPathParameters().getFirst("subscriptionId")); - return EventSubscriptionUtils.mapEventSubscriptionServiceResponse(eventSubscriptionResponse); - } - - /** - * Retrieve All Events Subscriptions of a Client. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - @GET - @Path("/") - @Produces({"application/json; charset=utf-8"}) - public Response retrieveAllSubscriptions(@Context HttpServletRequest request, - @Context HttpServletResponse response) { - - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - - EventSubscriptionResponse eventSubscriptionResponse = eventSubscriptionServiceHandler. - getAllEventSubscriptions(clientId); - return EventSubscriptionUtils.mapEventSubscriptionServiceResponse(eventSubscriptionResponse); - } - - /** - * Retrieve All Events Subscriptions by an event type. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - @GET - @Path("/type/{eventType}") - @Produces({"application/json; charset=utf-8"}) - public Response retrieveAllSubscriptionsByEventType(@Context HttpServletRequest request, - @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - - EventSubscriptionResponse eventSubscriptionResponse = eventSubscriptionServiceHandler. - getEventSubscriptionsByEventType(clientId, uriInfo.getPathParameters().getFirst("eventType")); - return EventSubscriptionUtils.mapEventSubscriptionServiceResponse(eventSubscriptionResponse); - } - - /** - * Update an Event Subscription. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - @PUT - @Path("/{subscriptionId}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response updateSubscription(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - EventSubscriptionDTO eventSubscriptionDTO = new EventSubscriptionDTO(); - - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - eventSubscriptionDTO.setClientId(request.getHeader(EventNotificationConstants.X_WSO2_CLIENT_ID)); - - // extract the payload from the request - try { - JSONObject requestData = EventSubscriptionUtils.getJSONObjectPayload(request); - if (requestData != null) { - eventSubscriptionDTO.setRequestData(requestData); - } else { - log.error("Subscription request payload is missing"); - return Response.status(Response.Status.BAD_REQUEST). - entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.MISSING_JSON_REQUEST_PAYLOAD)).build(); - } - } catch (IOException e) { - log.error("Invalid Payload received", e); - return Response.status(Response.Status.BAD_REQUEST). - entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.REQUEST_PAYLOAD_ERROR)).build(); - } catch (ParseException e) { - return Response.status(Response.Status.BAD_REQUEST). - entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST_PAYLOAD, - EventNotificationEndPointConstants.ERROR_PAYLOAD_PARSE)).build(); - } - - eventSubscriptionDTO.setSubscriptionId(uriInfo.getPathParameters().getFirst("subscriptionId")); - EventSubscriptionResponse eventSubscriptionResponse = eventSubscriptionServiceHandler. - updateEventSubscription(eventSubscriptionDTO); - return EventSubscriptionUtils.mapEventSubscriptionServiceResponse(eventSubscriptionResponse); - } - - /** - * Delete an Event Subscription. - */ - @SuppressFBWarnings({"JAXRS_ENDPOINT", "SERVLET_HEADER"}) - @DELETE - @Path("/{subscriptionId}") - @Consumes({"application/json; charset=utf-8"}) - @Produces({"application/json; charset=utf-8"}) - public Response deleteSubscription(@Context HttpServletRequest request, @Context HttpServletResponse response, - @Context UriInfo uriInfo) { - //check if the client id is present in the header - String clientId = request.getHeader(EventNotificationEndPointConstants.X_WSO2_CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils. - getErrorDTO(EventNotificationEndPointConstants.MISSING_REQUEST_HEADER, - EventNotificationConstants.MISSING_HEADER_PARAM_CLIENT_ID)).build(); - } - - EventSubscriptionResponse eventSubscriptionResponse = eventSubscriptionServiceHandler. - deleteEventSubscription(clientId, uriInfo.getPathParameters().getFirst("subscriptionId")); - return EventSubscriptionUtils.mapEventSubscriptionServiceResponse(eventSubscriptionResponse); - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/constants/EventNotificationEndPointConstants.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/constants/EventNotificationEndPointConstants.java deleted file mode 100644 index 90530c99..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/constants/EventNotificationEndPointConstants.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.endpoint.constants; - -/** - * Constants in Endpoint. - */ -public class EventNotificationEndPointConstants { - public static final String X_WSO2_CLIENT_ID = "x-wso2-client_id"; - public static final String X_WSO2_RESOURCE_ID = "x-wso2-resource_id"; - public static final String REQUEST = "request"; - public static final String NOT_FOUND_RESPONSE = "No OPEN notifications founds for the given clientID"; - public static final String POLLING_ERROR_RESPONSE = "OB Event Notification Polling error"; - public static final String EVENT_CREATION_ERROR_RESPONSE = "OB Event Notification Creation error"; - public static final String REQUEST_PAYLOAD_ERROR = "Error in the request payload"; - public static final String EMPTY_REQ_PAYLOAD = "Request payload cannot be empty"; - public static final String INVALID_REQUEST = "invalid_request"; - public static final String INVALID_REQUEST_PAYLOAD = "invalid_request_payload"; - public static final String MISSING_REQUEST_PAYLOAD = "missing_request_payload"; - public static final String MISSING_JSON_REQUEST_PAYLOAD = "missing_Json_request_payload"; - public static final String INVALID_REQUEST_HEADER = "invalid_request_header"; - public static final String MISSING_REQUEST_HEADER = "missing_request_header"; - public static final String ERROR_PAYLOAD_PARSE = "Error while parsing payload"; - public static final String NOTIFICATIONS_NOT_FOUND = "notification_not_found"; -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/util/EventNotificationUtils.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/util/EventNotificationUtils.java deleted file mode 100644 index 9f7c038d..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/util/EventNotificationUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.endpoint.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.event.notifications.endpoint.constants.EventNotificationEndPointConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.dto.EventNotificationErrorDTO; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventCreationServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventPollingServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventCreationResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventPollingResponse; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.ws.rs.core.Response; - -/** - * This class will have util methods needed for event notifcations. - */ -public class EventNotificationUtils { - - private static final Log log = LogFactory.getLog(EventNotificationUtils.class); - - /** - * This method is to get the event creation service handler as per the config. - * @return - */ - public static EventCreationServiceHandler getEventNotificationCreationServiceHandler() { - - EventCreationServiceHandler eventCreationServiceHandler = (EventCreationServiceHandler) - OpenBankingUtils.getClassInstanceFromFQN(OpenBankingConfigParser.getInstance(). - getConfiguration().get(OpenBankingConstants.EVENT_CREATION_HANDLER).toString()); - - return eventCreationServiceHandler; - } - - /** - * This method is to get the event polling service handler as per the config. - * @return - */ - public static EventPollingServiceHandler getEventPollingServiceHandler() { - - EventPollingServiceHandler eventPollingServiceHandler = (EventPollingServiceHandler) - OpenBankingUtils.getClassInstanceFromFQN(OpenBankingConfigParser.getInstance(). - getConfiguration().get(OpenBankingConstants.EVENT_POLLING_HANDLER).toString()); - - return eventPollingServiceHandler; - } - - /** - * Method to map the Event Creation Service Response to API response. - * @param eventCreationResponse - * @return - */ - public static Response mapEventCreationServiceResponse(EventCreationResponse eventCreationResponse) { - - if (EventNotificationConstants.CREATED.equals(eventCreationResponse.getStatus())) { - - return Response.status(Response.Status.CREATED).entity(eventCreationResponse.getResponseBody()).build(); - - } else if (EventNotificationConstants.BAD_REQUEST.equals(eventCreationResponse.getStatus())) { - - return Response.status(Response.Status.BAD_REQUEST).entity(EventNotificationUtils.getErrorDTO( - EventNotificationEndPointConstants.INVALID_REQUEST, - eventCreationResponse.getErrorResponse())).build(); - } - - return Response.status(Response.Status.BAD_REQUEST).entity(getErrorDTO( - EventNotificationEndPointConstants.INVALID_REQUEST, - EventNotificationEndPointConstants.EVENT_CREATION_ERROR_RESPONSE)).build(); - } - - /** - * Method to map Event Polling Service to API response. - * @param eventPollingResponse - * @return - */ - public static Response mapEventPollingServiceResponse(EventPollingResponse eventPollingResponse) { - - if (EventNotificationConstants.OK.equals(eventPollingResponse.getStatus())) { - return Response.status(Response.Status.OK).entity(eventPollingResponse.getResponseBody()).build(); - } else if (EventNotificationConstants.NOT_FOUND.equals(eventPollingResponse.getStatus())) { - return Response.status(Response.Status.NOT_FOUND).entity(eventPollingResponse.getResponseBody()).build(); - } else { - if (eventPollingResponse.getErrorResponse() instanceof String) { - return Response.status(getErrorResponseStatus(eventPollingResponse.getStatus())) - .entity(EventNotificationUtils.getErrorDTO(EventNotificationEndPointConstants.INVALID_REQUEST, - eventPollingResponse.getErrorResponse().toString())).build(); - } else { - return Response.status(getErrorResponseStatus(eventPollingResponse.getStatus())) - .entity(eventPollingResponse.getErrorResponse()) - .build(); - } - } - } - - /** - * Method to map Event Polling Service error to API response. - * @return EventNotificationErrorDTO - */ - public static EventNotificationErrorDTO getErrorDTO(String error, String errorDescription) { - EventNotificationErrorDTO eventNotificationErrorDTO = new EventNotificationErrorDTO(); - eventNotificationErrorDTO.setError(error); - eventNotificationErrorDTO.setErrorDescription(errorDescription); - return eventNotificationErrorDTO; - } - - /** - * Get mapped Response.Status for the given status value. - * @param status status value - * @return Mapped Response.Status - */ - private static Response.Status getErrorResponseStatus(String status) { - - if (EventNotificationConstants.NOT_FOUND.equals(status)) { - return Response.Status.NOT_FOUND; - } else if (EventNotificationConstants.BAD_REQUEST.equals(status)) { - return Response.Status.BAD_REQUEST; - } else { - return Response.Status.INTERNAL_SERVER_ERROR; - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/util/EventSubscriptionUtils.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/util/EventSubscriptionUtils.java deleted file mode 100644 index 0b621b44..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/java/com/wso2/openbanking/accelerator/event/notifications/endpoint/util/EventSubscriptionUtils.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.event.notifications.endpoint.util; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.common.util.OpenBankingUtils; -import com.wso2.openbanking.accelerator.event.notifications.service.constants.EventNotificationConstants; -import com.wso2.openbanking.accelerator.event.notifications.service.handler.EventSubscriptionServiceHandler; -import com.wso2.openbanking.accelerator.event.notifications.service.response.EventSubscriptionResponse; -import com.wso2.openbanking.accelerator.event.notifications.service.util.EventNotificationServiceUtil; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpStatus; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - - -/** - * Events Notification Subscription API Utils. - */ -public class EventSubscriptionUtils { - - /** - * Extract string payload from request object. - */ - public static EventSubscriptionServiceHandler getEventSubscriptionServiceHandler() { - - EventSubscriptionServiceHandler eventSubscriptionServiceHandler = (EventSubscriptionServiceHandler) - OpenBankingUtils.getClassInstanceFromFQN(OpenBankingConfigParser.getInstance().getConfiguration(). - get(OpenBankingConstants.EVENT_SUBSCRIPTION_HANDLER).toString()); - return eventSubscriptionServiceHandler; - } - - /** - * Extract string payload from request object. - * - * @param request The request object - * @return String payload - */ - public static JSONObject getJSONObjectPayload(HttpServletRequest request) throws IOException, ParseException { - Object payload = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(IOUtils. - toString(request.getInputStream())); - if (payload == null || !(payload instanceof JSONObject)) { - return null; - } - return (JSONObject) payload; - } - - /** - * Method to map the Event Creation Service Response to API response. - * - * @param eventSubscriptionResponse - * @return Response - */ - public static Response mapEventSubscriptionServiceResponse(EventSubscriptionResponse eventSubscriptionResponse) { - int status = eventSubscriptionResponse.getStatus(); - if (HttpStatus.SC_NO_CONTENT == status) { - return Response.status(status) - .build(); - } else if (eventSubscriptionResponse.getErrorResponse() == null) { - if (eventSubscriptionResponse.getResponseBody() != null) { - return Response.status(status) - .entity(eventSubscriptionResponse.getResponseBody()) - .build(); - } else { - return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity(EventNotificationServiceUtil.getErrorDTO(EventNotificationConstants.INVALID_REQUEST, - EventNotificationConstants.ERROR_HANDLING_EVENT_SUBSCRIPTION)) - .build(); - } - } else { - return Response.status(status) - .entity(eventSubscriptionResponse.getErrorResponse()) - .build(); - } - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index b212826c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index 97e65a79..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 3f2f9dab..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.event.notifications.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - WSO2 Open Banking - Event Notifications API - WSO2 Open Banking - Event Notifications API - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/pom.xml deleted file mode 100644 index 79a0f7fb..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/pom.xml +++ /dev/null @@ -1,122 +0,0 @@ - - - - - 4.0.0 - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - - - com.wso2.openbanking.accelerator.push.authorization.endpoint - WSO2 Open Banking - Push Authorization - war - - - - io.swagger - swagger-jaxrs - - - javax.ws.rs - jsr311-api - - - com.google.guava - guava - - - org.yaml - snakeyaml - - - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.runtime.identity.authn.filter - provided - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.client.authn.filter - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - true - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-include.xml - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/webapp - - - api#openbanking#push-authorization - WEB-INF/lib/slf4j-api-*.jar - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/java/com/wso2/openbanking/accelerator/push/authorization/endpoint/api/PushAuthorisationEndpoint.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/java/com/wso2/openbanking/accelerator/push/authorization/endpoint/api/PushAuthorisationEndpoint.java deleted file mode 100644 index df7b39ee..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/java/com/wso2/openbanking/accelerator/push/authorization/endpoint/api/PushAuthorisationEndpoint.java +++ /dev/null @@ -1,185 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.push.authorization.endpoint.api; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigurationService; -import com.wso2.openbanking.accelerator.common.constant.OpenBankingConstants; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.PushAuthRequestValidator; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.exception.PushAuthRequestValidatorException; -import com.wso2.openbanking.accelerator.identity.push.auth.extension.request.validator.model.PushAuthErrorResponse; -import com.wso2.openbanking.accelerator.push.authorization.endpoint.model.PushAuthorisationResponse; -import com.wso2.openbanking.accelerator.runtime.identity.authn.filter.OBOAuthClientAuthenticatorProxy; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.cxf.interceptor.InInterceptors; -import org.apache.http.HttpStatus; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth.cache.SessionDataCache; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; -import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; - -import java.time.Instant; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -/** - * Pushed Authorization Requests API - * - *

This specification defines the pushed authorization request endpoint, which allows clients to push the payload of - * an OAuth 2.0 authorization request to the authorization server via a direct request and provides them with a request - * URI that is used as reference to the data in a subsequent authorization request. - * Life cycle : - * This endpoint creates and returns request_uri to the user. The request object is stored in IDN_AUTH_SESSION_STORE - * DB fronted by IS SessionDataCache. During auth call, request_uri is resolved using - * DefaultOBRequestUriRequestObjectBuilder extension implementation. - * Finally when the request_uri is used once, it should be removed from cache in consent-authorize-steps. - */ -@Path("/") -@InInterceptors(classes = OBOAuthClientAuthenticatorProxy.class) -public class PushAuthorisationEndpoint { - - private static final String REQUEST = "request"; - public static final String CLIENT_AUTHENTICATION_CONTEXT = "oauth.client.authentication.context"; - private OpenBankingConfigurationService openBankingConfigurationService; - - /** - * Push an OAuth authorisation request object in exchange for a request_uri. - *

- * Endpoint maybe secured with basic auth in base 64 - */ - @SuppressFBWarnings("JAXRS_ENDPOINT") - // Suppressed content - Endpoint - // Suppression reason - False Positive : This endpoint is secured with access control lists in the configuration - // Suppressed warning count - 1 - @POST - @Path("/par") - @Consumes({"application/x-www-form-urlencoded"}) - @Produces({"application/json"}) - public Response parPost(@Context HttpServletRequest request, @Context HttpServletResponse response, - MultivaluedMap parameterMap) { - - PushAuthRequestValidator pushAuthRequestValidator = PushAuthRequestValidator.getPushAuthRequestValidator(); - - Map paramMap; - String requestJWT = StringUtils.EMPTY; - - OAuthClientAuthnContext clientAuthnContext = (OAuthClientAuthnContext) - request.getAttribute(CLIENT_AUTHENTICATION_CONTEXT); - - // Check if the client authentication is successful - if (!clientAuthnContext.isAuthenticated()) { - // create error response - PushAuthErrorResponse errorResponse = pushAuthRequestValidator - .createErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, - clientAuthnContext.getErrorCode(), clientAuthnContext.getErrorMessage()); - return Response.status(errorResponse.getHttpStatusCode()) - .entity(errorResponse.getPayload()).build(); - } - - try { - paramMap = pushAuthRequestValidator.validateParams(request, (Map>) parameterMap); - } catch (PushAuthRequestValidatorException exception) { - // create error response - PushAuthErrorResponse errorResponse = pushAuthRequestValidator - .createErrorResponse(exception.getHttpStatusCode(), exception.getErrorCode(), - exception.getErrorDescription()); - return Response.status(errorResponse.getHttpStatusCode() != 0 ? - errorResponse.getHttpStatusCode() : exception.getHttpStatusCode()) - .entity(errorResponse.getPayload()).build(); - } - - if (!paramMap.isEmpty() && paramMap.containsKey(REQUEST)) { - - requestJWT = paramMap.get(REQUEST).toString(); - } - - // Generate a urn with cryptographically strong pseudo random algorithm - String urn = RandomStringUtils.randomAlphanumeric(32); - - OpenBankingConfigurationService openBankingConfigurationService = getOBConfigService(); - - int expiryTime = Integer.parseInt(openBankingConfigurationService.getConfigurations() - .get(OpenBankingConstants.PUSH_AUTH_EXPIRY_TIME).toString()); - - // Add to auth cache - addToIdnOAuthCache(requestJWT, urn, expiryTime); - - return Response.status(HttpStatus.SC_CREATED) - .entity(getSuccessResponse("urn" + ":" + openBankingConfigurationService.getConfigurations() - .get(OpenBankingConstants.PUSH_AUTH_REQUEST_URI_SUBSTRING).toString() + ":" + urn, expiryTime)) - .build(); - - } - - /** - * Add Request Object to Session-Key Cache (Database). Validation is set as one minute. - */ - private static void addToIdnOAuthCache(String requestJWT, String sessionKey, int expiry) { - - SessionDataCacheKey cacheKey = new SessionDataCacheKey(sessionKey); - SessionDataCacheEntry sessionDataCacheEntry = new SessionDataCacheEntry(); - OAuth2Parameters oAuth2Parameters = new OAuth2Parameters(); - long expiryTimestamp = Instant.now().getEpochSecond() + expiry; - oAuth2Parameters.setEssentialClaims(requestJWT + ":" + expiryTimestamp); - sessionDataCacheEntry.setoAuth2Parameters(oAuth2Parameters); - - SessionDataCache.getInstance().addToCache(cacheKey, sessionDataCacheEntry); - } - - /** - * Create success response. - */ - private static PushAuthorisationResponse getSuccessResponse(String requestUri, int expiry) { - - PushAuthorisationResponse pushAuthorisationResponse = new PushAuthorisationResponse(); - - pushAuthorisationResponse.setRequestUri(requestUri); - pushAuthorisationResponse.setExpiresIn(expiry); - return pushAuthorisationResponse; - } - - /** - * Retrieve Open Banking configuration service. - */ - private OpenBankingConfigurationService getOBConfigService() { - - if (this.openBankingConfigurationService == null) { - OpenBankingConfigurationService openBankingConfigurationService = - (OpenBankingConfigurationService) PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(OpenBankingConfigurationService.class, null); - if (openBankingConfigurationService != null) { - this.openBankingConfigurationService = openBankingConfigurationService; - } - } - return this.openBankingConfigurationService; - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/java/com/wso2/openbanking/accelerator/push/authorization/endpoint/model/PushAuthorisationResponse.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/java/com/wso2/openbanking/accelerator/push/authorization/endpoint/model/PushAuthorisationResponse.java deleted file mode 100644 index 09270eb1..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/java/com/wso2/openbanking/accelerator/push/authorization/endpoint/model/PushAuthorisationResponse.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.push.authorization.endpoint.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model class for push authorisation response. - */ -public class PushAuthorisationResponse { - - private String requestUri = null; - private Integer expiresIn = null; - - @JsonProperty("request_uri") - public String getRequest_uri() { - - return requestUri; - } - - public void setRequestUri(String requestUri) { - - this.requestUri = requestUri; - } - - public PushAuthorisationResponse requestUri(String requestUri) { - - this.requestUri = requestUri; - return this; - } - - @JsonProperty("expires_in") - public Integer getExpires_in() { - - return expiresIn; - } - - public void setExpiresIn(Integer expiresIn) { - - this.expiresIn = expiresIn; - } - - public PushAuthorisationResponse expiresIn(Integer expiresIn) { - - this.expiresIn = expiresIn; - return this; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class PushAuthorisationResponse {\n"); - - sb.append(" requestUri: ").append(toIndentedString(requestUri)).append("\n"); - sb.append(" expiresIn: ").append(toIndentedString(expiresIn)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private static String toIndentedString(Object object) { - if (object == null) { - return "null"; - } - return object.toString().replace("\n", "\n "); - } -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/META-INF/MANIFEST.mf b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/META-INF/MANIFEST.mf deleted file mode 100644 index 9d885be5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/META-INF/MANIFEST.mf +++ /dev/null @@ -1 +0,0 @@ -Manifest-Version: 1.0 diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index b212826c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - false - - - Carbon,CXF3 - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/WEB-INF/beans.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index ef5176c5..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index baf0a570..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.accelerator.push.authorization.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - WSO2 Open Banking - Push Auth API - WSO2 Open Banking - Push Auth API - - - contextConfigLocation - WEB-INF/beans.xml - - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - - org.springframework.web.context.ContextLoaderListener - - - - - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - - CXFServlet - /* - - - - 60 - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/pom.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/pom.xml deleted file mode 100644 index 3f5c2a2c..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/pom.xml +++ /dev/null @@ -1,190 +0,0 @@ - - - - - - open-banking-accelerator - com.wso2.openbanking.accelerator - 3.2.11-SNAPSHOT - ../../../pom.xml - - 4.0.0 - - com.wso2.openbanking.authentication.webapp - war - WSO2 Open Banking - Authentication Webapp - - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.identity - provided - - - com.wso2.openbanking.accelerator - com.wso2.openbanking.accelerator.consent.extensions - provided - - - javax.servlet - jstl - - - org.testng - testng - test - - - org.mockito - mockito-all - test - - - org.jacoco - org.jacoco.agent - runtime - test - - - org.springframework - spring-test - test - - - org.springframework - spring-core - provided - - - org.wso2.orbit.org.owasp.encoder - encoder - ${encoder.wso2.version} - - - - - - maven-war-plugin - ${maven-war-plugin.version} - - - - - src/main/resources/ - - - ob#authenticationendpoint - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.jacoco - jacoco-maven-plugin - - - **/*Constants.class - - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - default-check - - check - - - - - **/*OBDefaultAuthServletImpl.class - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - - - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - - Max - Low - true - false - ${project.build.directory}/spotbugs - ${project.basedir}/src/main/resources/findbugs-exclude.xml - ${project.basedir}/src/main/resources/findbugs-include.xml - false - - - com.h3xstream.findsecbugs - findsecbugs-plugin - ${com.h3xstream.findsecbugs.version} - - - - - - analyze-compile - compile - - check - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/OBConsentConfirmServlet.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/OBConsentConfirmServlet.java deleted file mode 100644 index 4b4edf01..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/OBConsentConfirmServlet.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.webapp; - -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.model.OBAuthServletInterface; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.HttpURLConnection; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -/** - * The servlet responsible for the confirm page in auth web flow. - */ -public class OBConsentConfirmServlet extends HttpServlet { - - static OBAuthServletInterface obAuthServletTK; - private static final long serialVersionUID = 6106269597832678046L; - private static Logger log = LoggerFactory.getLogger(OBConsentConfirmServlet.class); - - @SuppressFBWarnings("COOKIE_USAGE") - // Suppressed content - browserCookies.put(cookie.getName(), cookie.getValue()) - // Suppression reason - False Positive : The cookie values are only read and here. No sensitive info is added to - // the cookie in this step. - // Suppressed warning count - 1 - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - - setAuthExtension(); - - HttpSession session = request.getSession(); - Map metadata = new HashMap<>(); - Map browserCookies = new HashMap<>(); - JSONObject consentData = new JSONObject(); - - //retrieve commonAuthId to be stored for co-relation of consent Id and access token issued - Cookie[] cookies = request.getCookies(); - for (Cookie cookie : cookies) { - browserCookies.put(cookie.getName(), cookie.getValue()); - } - consentData.put("cookies", browserCookies); - - // Add authorisationId if available - String authorisationId = request.getParameter("authorisationId"); - if (StringUtils.isNotEmpty(authorisationId)) { - metadata.put("authorisationId", authorisationId); - } - - consentData.put("type", request.getParameter("type")); - consentData.put("approval", request.getParameter("consent")); - consentData.put("userId", session.getAttribute("username")); - - // add TK data - if (obAuthServletTK != null) { - Map updatedMetadata = obAuthServletTK.updateConsentMetaData(request); - if (updatedMetadata != null) { - updatedMetadata.forEach(metadata::put); - } - - Map updatedConsentData = obAuthServletTK.updateConsentData(request); - if (updatedConsentData != null) { - updatedConsentData.forEach(consentData::put); - } - } - - consentData.put("metadata", metadata); - - String redirectURL = persistConsentData( - consentData, request.getParameter("sessionDataKeyConsent"), getServletContext()); - - // Invoke authorize flow - if (redirectURL != null) { - response.sendRedirect(redirectURL); - - } else { - session.invalidate(); - response.sendRedirect("retry.do?status=Error&statusMsg=Error while persisting consent"); - } - - } - - @Generated(message = "Contains the tested code of HTTPClient") - String persistConsentData(JSONObject consentData, String sessionDataKey, ServletContext servletContext) { - - String persistenceBaseURL = servletContext.getInitParameter("persistenceBaseURL"); - String persistenceUrl = persistenceBaseURL + "/" + sessionDataKey; - - try (CloseableHttpClient client = HttpClientBuilder.create().build()) { - HttpPatch dataRequest = new HttpPatch(persistenceUrl); - dataRequest.addHeader("accept", "application/json"); - dataRequest.addHeader("Authorization", "Basic " + OBConsentServlet.getConsentApiCredentials()); - StringEntity body = new StringEntity(consentData.toString(), ContentType.APPLICATION_JSON); - dataRequest.setEntity(body); - HttpResponse dataResponse = client.execute(dataRequest); - - if (dataResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { - return null; - } else { - return dataResponse.getLastHeader("Location").getValue(); - } - } catch (IOException e) { - log.error("Exception while calling persistence endpoint", e); - return null; - } - } - /** - * Retrieve the config. - */ - void setAuthExtension() { - try { - obAuthServletTK = (OBAuthServletInterface) Class.forName(OpenBankingConfigParser.getInstance() - .getAuthServletExtension()).getDeclaredConstructor().newInstance(); - } catch (InstantiationException | IllegalAccessException | - InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { - log.error("Webapp extension not found", e); - } - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/OBConsentServlet.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/OBConsentServlet.java deleted file mode 100644 index 0bbafe9d..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/OBConsentServlet.java +++ /dev/null @@ -1,290 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.webapp; - -import com.wso2.openbanking.accelerator.authentication.webapp.util.Constants; -import com.wso2.openbanking.accelerator.common.config.OpenBankingConfigParser; -import com.wso2.openbanking.accelerator.common.util.Generated; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.ConsentMgrAuthServletImpl; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.ISDefaultAuthServletImpl; -import com.wso2.openbanking.accelerator.consent.extensions.authservlet.model.OBAuthServletInterface; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.json.JSONObject; -import org.owasp.encoder.Encode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.ResourceBundle; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import static com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Utils.i18n; - -/** - * The servlet responsible for displaying the consent details in the auth UI flow. - */ -public class OBConsentServlet extends HttpServlet { - - static OBAuthServletInterface obAuthServletTK; - private static final long serialVersionUID = 6106269076132678046L; - private static Logger log = LoggerFactory.getLogger(OBConsentServlet.class); - private static final String BUNDLE = "com.wso2.openbanking.authentication.webapp.i18n"; - - @SuppressFBWarnings({"REQUESTDISPATCHER_FILE_DISCLOSURE", "TRUST_BOUNDARY_VIOLATION"}) - // Suppressed content - obAuthServlet.getJSPPath() - // Suppression reason - False Positive : JSP path is hard coded and does not accept any user inputs, therefore it - // can be trusted - // Suppressed content - Encode.forJava(sessionDataKey) - // Suppression reason - False positive : sessionDataKey is encoded for Java which escapes untrusted characters - // Suppressed warning count - 2 - @Override - public void doGet(HttpServletRequest originalRequest, HttpServletResponse response) - throws IOException, ServletException { - HttpServletRequest request = originalRequest; - setAuthExtension(); - - // get consent data - String sessionDataKey = request.getParameter("sessionDataKeyConsent"); - HttpResponse consentDataResponse = getConsentDataWithKey(sessionDataKey, getServletContext()); - JSONObject dataSet = new JSONObject(); - log.debug("HTTP response for consent retrieval" + consentDataResponse.toString()); - try { - if (consentDataResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_TEMP && - consentDataResponse.getLastHeader("Location") != null) { - response.sendRedirect(consentDataResponse.getLastHeader("Location").getValue()); - return; - } else { - String retrievalResponse = IOUtils.toString(consentDataResponse.getEntity().getContent(), - String.valueOf(StandardCharsets.UTF_8)); - JSONObject data = new JSONObject(retrievalResponse); - String errorResponse = getErrorResponseForRedirectURL(data); - if (data.has(Constants.REDIRECT_URI) && StringUtils.isNotEmpty(errorResponse)) { - URI errorURI = new URI(data.get(Constants.REDIRECT_URI).toString().concat(errorResponse)); - response.sendRedirect(errorURI.toString()); - return; - } else { - dataSet = createConsentDataset(data, consentDataResponse.getStatusLine().getStatusCode()); - } - } - } catch (IOException e) { - dataSet.put(Constants.IS_ERROR, "Exception occurred while retrieving consent data"); - } catch (URISyntaxException e) { - dataSet.put(Constants.IS_ERROR, "Error while constructing URI for redirection"); - - } - if (dataSet.has(Constants.IS_ERROR)) { - String isError = (String) dataSet.get(Constants.IS_ERROR); - request.getSession().invalidate(); - response.sendRedirect("retry.do?status=Error&statusMsg=" + isError); - return; - } - - // set variables to session - HttpSession session = request.getSession(); - - session.setAttribute(Constants.SESSION_DATA_KEY_CONSENT, Encode.forJava(sessionDataKey)); - session.setAttribute("displayScopes", - Boolean.parseBoolean(getServletContext().getInitParameter("displayScopes"))); - - // set strings to request - ResourceBundle resourceBundle = getResourceBundle(request.getLocale()); - - originalRequest.setAttribute("privacyDescription", i18n(resourceBundle, - "privacy.policy.privacy.short.description.approving")); - originalRequest.setAttribute("privacyGeneral", i18n(resourceBundle, "privacy.policy.general")); - - // bottom.jsp - originalRequest.setAttribute("ok", i18n(resourceBundle, "ok")); - originalRequest.setAttribute("requestedScopes", i18n(resourceBundle, "requested.scopes")); - - originalRequest.setAttribute("app", dataSet.getString("application")); - - // Get servlet extension - OBAuthServletInterface obAuthServlet; - if (Constants.DEFAULT.equals(dataSet.getString("type"))) { - // get default auth servlet extension - obAuthServlet = new ISDefaultAuthServletImpl(); - } else if (Constants.CONSENT_MGT.equals(dataSet.getString("type"))) { - // get consent manager auth servlet extension - obAuthServlet = new ConsentMgrAuthServletImpl(); - } else { - // get auth servlet toolkit implementation - if (obAuthServletTK == null) { - request.getSession().invalidate(); - response.sendRedirect("retry.do?status=Error&statusMsg=Error while processing request"); - log.error("Unable to find OB auth servlet extension implementation. Returning error."); - return; - } - obAuthServlet = obAuthServletTK; - } - - Map updatedValues; - - updatedValues = obAuthServlet.updateRequestAttribute(request, dataSet, resourceBundle); - updatedValues.forEach(originalRequest::setAttribute); - - // update session - updatedValues = obAuthServlet.updateSessionAttribute(request, dataSet, resourceBundle); - updatedValues.forEach(originalRequest.getSession()::setAttribute); - - // dispatch - RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(obAuthServlet.getJSPPath()); - dispatcher.forward(originalRequest, response); - - } - - HttpResponse getConsentDataWithKey(String sessionDataKeyConsent, ServletContext servletContext) throws IOException { - - String retrievalBaseURL = servletContext.getInitParameter("retrievalBaseURL"); - String retrieveUrl = (retrievalBaseURL.endsWith("/")) ? retrievalBaseURL + sessionDataKeyConsent : - retrievalBaseURL + "/" + sessionDataKeyConsent; - - CloseableHttpClient client = HttpClientBuilder.create().build(); - HttpGet dataRequest = new HttpGet(retrieveUrl); - dataRequest.addHeader("Authorization", "Basic " + getConsentApiCredentials()); - HttpResponse dataResponse = client.execute(dataRequest); - - return dataResponse; - - } - - JSONObject createConsentDataset(JSONObject consentResponse, int statusCode) throws IOException { - - JSONObject errorObject = new JSONObject(); - if (statusCode != HttpURLConnection.HTTP_OK) { - if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { - if (consentResponse.has("description")) { - errorObject.put(Constants.IS_ERROR, consentResponse.get("description")); - } - } else { - errorObject.put(Constants.IS_ERROR, "Retrieving consent data failed"); - } - return errorObject; - } else { - return consentResponse; - } - } - - /** - * Retrieve the config. - */ - void setAuthExtension() { - - try { - obAuthServletTK = (OBAuthServletInterface) Class.forName(OpenBankingConfigParser.getInstance(). - getAuthServletExtension()).getDeclaredConstructor().newInstance(); - } catch (InstantiationException | IllegalAccessException | - InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { - log.error("Webapp extension not found", e); - } - } - - @Generated(message = "Encapsulated method for unit test") - ResourceBundle getResourceBundle(Locale locale) { - - return ResourceBundle.getBundle(BUNDLE, locale); - } - - /** - * @param data error response received from consent data retrieval endpoint - * @return formatted error response to be send to call back uri - */ - String getErrorResponseForRedirectURL(JSONObject data) { - - String errorResponse = ""; - try { - if (data.has(Constants.ERROR)) { - errorResponse = errorResponse.concat(Constants.ERROR_URI_FRAGMENT) - .concat(URLEncoder.encode(data.get(Constants.ERROR).toString(), - StandardCharsets.UTF_8.toString())); - } - if (data.has(Constants.ERROR_DESCRIPTION)) { - errorResponse = errorResponse.concat(Constants.ERROR_DESCRIPTION_PARAMETER) - .concat(URLEncoder.encode(data.get(Constants.ERROR_DESCRIPTION).toString(), - StandardCharsets.UTF_8.toString())); - } - if (data.has(Constants.STATE)) { - errorResponse = errorResponse.concat(Constants.STATE_PARAMETER) - .concat(URLEncoder.encode(data.get(Constants.STATE).toString(), - StandardCharsets.UTF_8.toString())); - } - - } catch (UnsupportedEncodingException e) { - log.error("Error while building error response", e); - } - return errorResponse; - } - - /** - * Retrieve admin credentials in Base64 format from webapp properties or OB configs. - */ - static String getConsentApiCredentials () { - String username, password; - try { - InputStream configurations = OBConsentConfirmServlet.class.getClassLoader() - .getResourceAsStream(Constants.CONFIG_FILE_NAME); - Properties configurationProperties = new Properties(); - configurationProperties.load(configurations); - Boolean isConfiguredInWebapp = Boolean.parseBoolean( - configurationProperties.getProperty(Constants.LOCATION_OF_CREDENTIALS)); - if (!isConfiguredInWebapp) { - username = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(Constants.USERNAME_IN_OB_CONFIGS); - password = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(Constants.PASSWORD_IN_OB_CONFIGS); - } else { - username = configurationProperties.getProperty(Constants.USERNAME_IN_WEBAPP_CONFIGS); - password = configurationProperties.getProperty(Constants.PASSWORD_IN_WEBAPP_CONFIGS); - } - } catch (IOException | NullPointerException e) { - log.error("Error occurred while reading the webapp properties file. Therefore using OB configurations."); - username = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(Constants.USERNAME_IN_OB_CONFIGS); - password = (String) OpenBankingConfigParser.getInstance().getConfiguration() - .get(Constants.PASSWORD_IN_OB_CONFIGS); - } - return Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); - } - -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/util/Constants.java b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/util/Constants.java deleted file mode 100644 index 8eb1fe56..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/java/com/wso2/openbanking/accelerator/authentication/webapp/util/Constants.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.wso2.openbanking.accelerator.authentication.webapp.util; - -/** - * Constants required for auth webapp. - */ -public class Constants { - - public static final String IS_ERROR = "isError"; - public static final String REQUESTED_CLAIMS = "requestedClaims"; - public static final String MANDATORY_CLAIMS = "mandatoryClaims"; - public static final String CLAIM_SEPARATOR = ","; - public static final String USER_CLAIMS_CONSENT_ONLY = "userClaimsConsentOnly"; - public static final String SESSION_DATA_KEY_CONSENT = "sessionDataKeyConsent"; - public static final String DEFAULT = "default"; - public static final String CONSENT_MGT = "consentmgt"; - public static final String COMMONAUTH_ID = "commonAuthId"; - public static final String OIDC_SCOPES = "OIDCScopes"; - public static final String REDIRECT_URI = "redirect_uri"; - public static final String ERROR = "error"; - public static final String ERROR_DESCRIPTION = "error_description"; - public static final String STATE = "state"; - public static final String ERROR_URI_FRAGMENT = "#error="; - public static final String ERROR_DESCRIPTION_PARAMETER = "&error_description="; - public static final String STATE_PARAMETER = "&state="; - public static final String CONFIG_FILE_NAME = "configurations.properties"; - public static final String LOCATION_OF_CREDENTIALS = "ConsentAPICredentials.IsConfiguredInWebapp"; - public static final String USERNAME_IN_WEBAPP_CONFIGS = "ConsentAPICredentials.Username"; - public static final String PASSWORD_IN_WEBAPP_CONFIGS = "ConsentAPICredentials.Password"; - public static final String USERNAME_IN_OB_CONFIGS = "Consent.ConsentAPICredentials.Username"; - public static final String PASSWORD_IN_OB_CONFIGS = "Consent.ConsentAPICredentials.Password"; -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/com/wso2/openbanking/authentication/webapp/i18n.properties b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/com/wso2/openbanking/authentication/webapp/i18n.properties deleted file mode 100644 index ad04e6c8..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/com/wso2/openbanking/authentication/webapp/i18n.properties +++ /dev/null @@ -1,125 +0,0 @@ - # Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - # - # WSO2 LLC. licenses this file to you under the Apache License, - # Version 2.0 (the "License"); you may not use this file except - # in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - # KIND, either express or implied. See the License for the - # specific language governing permissions and limitations - # under the License. - -login=Sign In -username=User Name -password=Password -login.fail.message=Login failed! Please recheck the username and password and try again. -recaptcha.fail.message=reCaptcha validation is required for user. -account.confirmation.pending=Account is unverified. An account activation link has been sent to your registered email address, please check your inbox. -password.reset.pending=Password reset is required. A password reset link has been sent to your registered email address, please check your inbox. -account.resend.email.success=Email sent successfully. -account.resend.email.fail=Email sent fail. -user.tenant.domain.mismatch.message=Application you are trying to access does not allow users from your organization. -remember.me=Remember me on this computer -signin.to.authenticate1=Please sign in to authenticate to -signin.to.authenticate2=as -profile=Profile : -cancel=Cancel -approve=Approve -deny=Deny -approve.always=Approve Always -request.access.scope=requests access to -request.access.profile=requests access to your profile information -saml.sso=SAML 2.0 based Single Sign-On -tenantListLabel=Tenant -select.tenant.dropdown.display.name=Select Tenant -super.tenant.display.name=Super Tenant -super.tenant=carbon.super -domain.unknown=domain.unknown -confirm.password=Confirm Password -email=Email -continue=Continue -forgot.username.password=Forgot -forgot.username.password.or=or -forgot.password=Password -forgot.username=Username -no.account=Don't have an account? -have.account=Already have an account? -register.now=Register Now -register=Register -no.confirmation.mail=Not received confirmation email? -resend.mail=Re-Send -openid=Open ID -openid.user.claims=OpenID User Claims -username.or.password.invalid=Username or Password is Invalid -create.an.account=Create an account -unauthorized.to.login=You are not authorized to login -domain.cannot.be.identified=Domain cannot be identified! Please retry. -wso2.open.banking=WSO2 Open Banking -open.banking=Open Banking -domain=Domain -submit=Submit -inc=Inc -all.rights.reserved=All rights reserved -verification=Verification -touch.your.u2f.device=Touch your U2F device to Proceed -authentication.error=Authentication Error! -something.went.wrong.during.authentication=Something went wrong during the authentication process.Please try signing in again. -attention=Attention -provide.mandatory.details=Provide Mandatory Details -requested.claims.recommendation= application,that you are trying to login to needs following information filled in the user profile. You can fill those below and proceed with the authentication. But it is advised to fill these information in your Identity Provider profile in order to avoid this step every time you login -logged.out=You have successfully logged out. -authorize=Authorize -invalid.request=Invalid Request -oauth.processing.error.msg=OAuth Processing Error Message -openid.connect.logout=OpenID connect logout -do.you.want.to.logout=Do you want to logout? -yes=Yes -no=No -openid2.profile=OpenID2.0 Profile -claim.uri=Claim URI -claim.value=Claim Value -internal.error.occurred=Internal Error Occurred -information=Information -user.details.submitted=User details successfully submitted -close=Close -other.login.options=Other login options -sign.in.with=Sign In With -domain.name=Domain Name -go=Go -please.select.recaptcha=Please select recaptcha -error.when.processing.authentication.request=Error when processing authentication request! -please.try.login.again=Please try login again! -you.are.redirected.back.to=You are now redirected back to, -if.the.redirection.fails.please.click=If the redirection fails, please click the -post=POST -enter.required.fields.to.complete.registration=Enter required fields to complete registration -first.name=First Name -last.name=Last Name -password.mismatch=Passwords did not match. Please try again -user.exists=User already exist -unknown.error=Unknown error occurred -authentication.failed.please.retry=Authentication Failed! Please Retry -user.consents=User Consents -mandatory.claims.recommendation=Mandatory claims are marked with an asterisk -mandatory.claims.warning.msg.1=You need to provide consent for -mandatory.claims.warning.msg.2=all the mandatory claims -mandatory.claims.warning.msg.3=in order to proceed -privacy.policy.cookies=Cookie Policy -privacy.policy.cookies.short.description=After a successful sign in, we use a cookie in your browser to track your session. You can refer our -privacy.policy.general=Privacy Policy -privacy.policy.privacy.short.description=By signing in, you agree to our -privacy.policy.privacy.short.description.approving=By approving, you agree to our -privacy.policy.for.more.details=for more details. -under.construction=This page is under construction -by.selecting.following.attributes=By selecting following attributes I agree to share them with the above service provider. -select.all=Select All -requested.scopes=Requested scopes -requested.attributes=Requested attributes -please.select.approve.always=Please select either "Approve Always" or "Approve" to provide consent to requested scopes to continue -ok=Ok -mandatory.claims=Mandatory claims diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/configurations.properties b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/configurations.properties deleted file mode 100644 index c118c4de..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/configurations.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). -# -# WSO2 LLC. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -ConsentAPICredentials.IsConfiguredInWebapp = false -ConsentAPICredentials.Username = null -ConsentAPICredentials.Password = null diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/findbugs-exclude.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/findbugs-exclude.xml deleted file mode 100644 index d7392112..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/findbugs-exclude.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/findbugs-include.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/findbugs-include.xml deleted file mode 100644 index 8932a22e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/resources/findbugs-include.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/WEB-INF/web.xml b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 59a41b2f..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - OBConsentServlet - com.wso2.openbanking.accelerator.authentication.webapp.OBConsentServlet - - - - OBConsentServlet - /oauth2_authz.do - - - - OBConsentServlet - /oauth2_consent.do - - - - retrievalBaseURL - https://localhost:9446/api/openbanking/consent/authorize/retrieve - - - - displayScopes - true - - - - - - OBConsentConfirmServlet - com.wso2.openbanking.accelerator.authentication.webapp.OBConsentConfirmServlet - - - - OBConsentConfirmServlet - /oauth2_authz_confirm.do - - - - persistenceBaseURL - https://localhost:9446/api/openbanking/consent/authorize/persist - - - - - - cookie_policy.do - /cookie_policy.jsp - - - - cookie_policy.do - /cookie_policy.do - - - - - - privacy_policy.do - /privacy_policy.jsp - - - - privacy_policy.do - /privacy_policy.do - - - - - - java.lang.Throwable - /generic-exception-response.jsp - - - - - - oauth2_authz_consent.do - /oauth2_authz_consent.do - - - - retry.do - /generic-exception-response.jsp - - - - oauth2_authz_consent.do - /oauth2_authz_displayconsent.jsp - - - - retry.do - /retry.do - - - \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/img/glyphicons-halflings-white.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/img/glyphicons-halflings-white.png deleted file mode 100644 index 3bf6484a..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/img/glyphicons-halflings-white.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/img/glyphicons-halflings.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/img/glyphicons-halflings.png deleted file mode 100644 index 79bc568c..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/img/glyphicons-halflings.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/js/html5.js b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/js/html5.js deleted file mode 100644 index 560aa942..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/assets/js/html5.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! HTML5 Shiv vpre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed - Uncompressed source: https://github.com/aFarkas/html5shiv */ -(function(a,b){function h(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function i(){var a=l.elements;return typeof a=="string"?a.split(" "):a}function j(a){var b={},c=a.createElement,f=a.createDocumentFragment,g=f();a.createElement=function(a){if(!l.shivMethods)return c(a);var f;return b[a]?f=b[a].cloneNode():e.test(a)?f=(b[a]=c(a)).cloneNode():f=c(a),f.canHaveChildren&&!d.test(a)?g.appendChild(f):f},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+i().join().replace(/\w+/g,function(a){return c(a),g.createElement(a),'c("'+a+'")'})+");return n}")(l,g)}function k(a){var b;return a.documentShived?a:(l.shivCSS&&!f&&(b=!!h(a,"article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}mark{background:#FF0;color:#000}")),g||(b=!j(a)),b&&(a.documentShived=b),a)}var c=a.html5||{},d=/^<|^(?:button|form|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^<|^(?:a|b|button|code|div|fieldset|form|h1|h2|h3|h4|h5|h6|i|iframe|img|input|label|li|link|ol|option|p|param|q|script|select|span|strong|style|table|tbody|td|textarea|tfoot|th|thead|tr|ul)$/i,f,g;(function(){var c=b.createElement("a");c.innerHTML="",f="hidden"in c,f&&typeof injectElementWithStyles=="function"&&injectElementWithStyles("#modernizr{}",function(b){b.hidden=!0,f=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle).display=="none"}),g=c.childNodes.length==1||function(){try{b.createElement("a")}catch(a){return!0}var c=b.createDocumentFragment();return typeof c.cloneNode=="undefined"||typeof c.createDocumentFragment=="undefined"||typeof c.createElement=="undefined"}()})();var l={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:k};a.html5=l,k(b)})(this,document) \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/cookie_policy.jsp b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/cookie_policy.jsp deleted file mode 100644 index e141abad..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/cookie_policy.jsp +++ /dev/null @@ -1,240 +0,0 @@ -<%@ page import="static com.wso2.openbanking.accelerator.consent.extensions.authservlet.impl.util.Utils.i18n" %><%-- - ~ Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - ~ - ~ WSO2 LLC. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@include file="includes/localize.jsp" %> - - - - - - - - - -

-
-
- - - -
-
-
- -
- - -
-
-
-
-
-
-

- <%=i18n(resourceBundle, "wso2.open.banking")%> - <%=i18n(resourceBundle, "privacy.policy.cookies")%> -

-
- -
-
-

About WSO2 Open Banking Solution

-

WSO2 Open Banking Solution (referred to as “WSO2 Open Banking” within this policy) is a comprehensive Open Banking Solution that is supporting PSD2 compliance along with more value added features.

-
- -
- -

WSO2 Open Banking uses cookies so that it can provide the best user experience for you and identify you for security purposes. If you disable cookies, some of the services will (most probably) be inaccessible to you.

-
- -
-

How does WSO2 Open Banking process cookies?

-

WSO2 Open Banking stores and retrieves information on your browser using cookies. This information is used to provide a better experience. Some cookies serve the primary purposes of allowing a user to log in to the system, maintaining sessions, and keeping track of activities you do within the login session.

-

The primary purpose of some cookies used in WSO2 Open Banking is to personally identify you as required by the functionality of WSO2 Open Banking. However the cookie lifetime ends once your session ends i.e., after you log-out, or after the session expiry time has elapsed.

-

Some cookies are simply used to give you a more personalised web experience and these cookies can not be used to personally identify you or your activities.

-

This cookie policy is part of the WSO2 Open Banking Privacy Policy.

-
- -
- -

A browser cookie is a small piece of data that is stored on your device to help websites and mobile apps remember things about you. Other technologies, including web storage and identifiers associated with your device, may be used for similar purposes. In this policy, we use the term “cookies” to discuss all of these technologies.

-
- -
-

What does WSO2 Open Banking use cookies for?

-

Cookies are used for two purposes in WSO2 Open Banking.

-
    -
  1. To identify you and provide security (as this is the main function of WSO2 IS).
  2. -
  3. To provide a satisfying user experience.
  4. -
-
- -
-

WSO2 Open Banking uses cookies for the following purposes listed below.

-

Preferences

-

WSO2 Open Banking uses these cookies to remember your settings and preferences, and to auto-fill the form fields to make your interactions with the site easier.

-

These cookies can not be used to personally identify you.

-

Security

-
    -
  • WSO2 Open Banking uses selected cookies to identify and prevent security risks. - For example, WSO2 Open Banking may use these cookies to store your session information in order to prevent others from changing your password without your username and password.
  • -
  • WSO2 Open Banking uses session cookies to maintain your active session.
  • -
  • WSO2 Open Banking may use temporary cookies when performing multi-factor authentication and federated authentication.
  • -
  • WSO2 Open Banking may use permanent cookies to detect that you have previously used the same device to log in. This is to to calculate the “risk level” associated with your current login attempt. This is primarily to protect you and your account from possible attack.
  • -
-

Performance

-

WSO2 Open Banking may use cookies to allow “Remember Me” functionalities.

-
- -
-

Analytics

-

WSO2 Open Banking as a product does not use cookies for analytical purposes.

-
- -
-

Third party cookies

-

Using WSO2 Open Banking may cause some third-party cookies to be set in your browser. WSO2 Open Banking has no control over how any of them operate. The third-party cookies that may be set include:

-
    -
  • Any social login sites. For example, third-party cookies may be set when WSO2 Open Banking is configured to use “social” or “federated” login, and you opt to login with your “Social Account”.
  • -
  • Any third party federated login.
  • -
-

WSO2 strongly advises you to refer the respective cookie policy of such sites carefully as WSO2 has no knowledge or use on these cookies.

-
- -
-

What type of cookies does WSO2 Open Banking use?

-

WSO2 Open Banking uses persistent cookies and session cookies. A persistent cookie helps WSO2 Open Banking to recognize you as an existing user so that it is easier to return to WSO2 or interact with WSO2 Open Banking without signing in again. After you sign in, a persistent cookie stays in your browser and will be read by WSO2 Open Banking when you return to WSO2 Open Banking.

-

A session cookie is a cookie that is erased when the user closes the web browser. The session cookie is stored in temporary memory and is not retained after the browser is closed. Session cookies do not collect information from the user's computer.

-
- -
-

How do I control my cookies?

-

Most browsers allow you to control cookies through their settings preferences. However, if you limit the given ability for websites to set cookies, you may worsen your overall user experience since it will no longer be personalized to you. It may also stop you from saving customized settings like login information.

-

Most likely, disabling cookies will make you unable to use authentication and authorization functionalities offered by WSO2 Open Banking.

-

If you have any questions or concerns regarding the use of cookies, please contact the entity or individuals (or their data protection officer, if applicable) of the organization running this WSO2 Open Banking instance.

-
- -
-

What are the cookies used?

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Cookie Name

-
-

Purpose

-
-

Retention

-
-

JSESSIONID

-
-

To keep your session data in order to give you a good user experience.

-
-

Session

-
-

MSG##########

-
-

To keep some messages that are shown to you in order to give you a good user experience.

-

The “##########” reference in this coookie represents a random number e.g., MSG324935932.

-
-

Session

-
-

requestedURI

-
-

The URI you are accessing.

-
-

Session

-
-

current-breadcrumb

-
-

To keep your active page in session in order to give you a good user experience.

-
-

Session

-
-
- -
-

Disclaimer

-
    -
  1. This cookie policy is only for the illustrative purposes of the product WSO2 Open Banking. The content in the policy is technically correct at the time of the product shipment. The organization which runs this WSO2 Open Banking instance has full authority and responsibility with regard to the effective Cookie Policy.

  2. -
  3. WSO2, its employees, partners, and affiliates do not have access to and do not require, store, process or control any of the data, including personal data contained in WSO2 Open Banking. All data, including personal data is controlled and processed by the entity or individual running WSO2 Open Banking. WSO2, its employees partners and affiliates are not a data processor or a data controller within the meaning of any data privacy regulations. WSO2 does not provide any warranties or undertake any responsibility or liability in connection with the lawfulness or the manner and purposes for which WSO2 Open Banking is used by such entities or persons.
  4. -
-
-
- -
-
- - -
- - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/Roboto.css b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/Roboto.css deleted file mode 100644 index 558ee634..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/Roboto.css +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -@font-face { - font-family: 'Roboto'; - src: url('../fonts/Roboto/Roboto-Black-webfont.woff') format('woff'), - url('../fonts/Roboto/Roboto-Black-webfont.ttf') format('truetype'), - url('../fonts/Roboto/Roboto-Black-webfont.svg') format('svg'); - font-weight: 100; - font-style: normal; -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/custom-common.css b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/custom-common.css deleted file mode 100644 index c6eb9257..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/custom-common.css +++ /dev/null @@ -1,597 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -html { - position: relative; - height: 100%; - overflow-y: auto; - overflow-x: hidden; - width: 100%; -} - -body { - background: #efefef; - font-family: "Open Sans", "Helvetica", "Arial", sans-serif; -} - -body.sticky-footer { - padding-bottom: 40px; -} - -header { - background: transparent; - min-height: 150px; - position: relative; -} - -header .brand a { - min-height: 24px; -} - -header .brand img.logo { - height: 24px; -} - -header .brand h1 { - margin: 0 0 0 5px; - display: inline-block; - line-height: 1; -} - -header .brand h1 em { - font-weight: 500; - font-size: 17px; - margin: 0; - color: #ffffff; - padding: 3px 0 0 0; - font-style: normal; - text-transform: uppercase; -} - -header .brand img.logo { - height: 45px; -} - -header .brand { - margin-top: 35px; - margin-left: 25px; - width: 181px; -} - -footer { - position: absolute; - bottom: 0; - width: 100%; - min-height: 40px; - overflow: hidden; - color: rgba(0, 0, 0, 0.87); - background: #efefef; - text-align: center; -} - -footer .icon { - font-size: 37px; - vertical-align: middle; - color: rgba(0, 0, 0, 0.87); -} - -footer > .container, -footer > .container-fluid { - padding-right: 15px; - padding-left: 15px; -} - -footer > .container p, -footer > .container-fluid p { - line-height: 40px; - margin-bottom: 0; -} - -footer a, -footer a:hover { - text-decoration: none; - color: #cbcbcb; -} - -body.sticky-footer footer { - position: absolute; - bottom: 0; - z-index: 1000; -} - -.form-control { - border-radius: 0; - background-color: #1A1F28; - color: #efefef; - border: 1px solid #1A1F28; -} - -.form-control:focus { - border-color: #00B4FF; - outline: 0; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px #00B4FF; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px #00B4FF; -} - -.col-centered { - float: none; - margin: 0 auto; -} - -.boarder-bottom-blue { - border-bottom: 2px solid #006596; -} - -.white { - color: #FFF; -} - -.blue-bg { - background-color: #3a9ecf !important; -} - -.green-bg { - background-color: #87ad1c !important; -} - -.uppercase { - text-transform: uppercase; -} - -.brand-container { - padding-top: 26px; -} - -@media (min-width: 1200px) { - .pull-right-lg { - float: right !important; - } -} - -.well { - background-color: #2f3e54; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; - border: none; - padding-bottom: 10px; - padding-left: initial; -} - -.data-container { - margin: 3rem 0; - background-image: linear-gradient(to bottom, #1a1f28 0%, #2e3b41 100%); - background-image: url(../images/login-back.svg), linear-gradient(to bottom, #1a1f28 0%, #2e3b41 100%); - background-repeat: no-repeat; - background-position: left bottom; - background-size: contain; - border: 1px solid #000; - border-radius: 10px; - color: '#fff'; -} - -.data-container.error { - border-left: 3px solid #00B4FF; -} - -.data-container form h3 { - margin-top: 10px; -} - -.input-group-addon { - background: #2f3e54; - color: #fff; - border: none; - border-radius: 0 !important; -} - -.input-group-lg > .form-control, -.input-group-lg > .input-group-addon, -.input-group-lg > .input-group-btn > .btn { - border-radius: 0 !important; -} - -@media (min-width: 991px) { - .data-container h3 { - font-size: 1.8em; - } -} - -.font-large { - font-size: 16px; -} - -.wr-input-control { - margin-bottom: 20px; -} - -.wr-login { - padding-top: 50px; - -} - -.wr-login input[type=text], -.wr-login input[type=password] { - border: 1px #d2d2d2 solid; - width: 100%; - padding: 6px 10px; - z-index: 1; - -webkit-appearance: none; - line-height: 30px; - border-radius: 0px; -} - -.btn-primary, -.btn-primary:focus, -.btn-primary:active { - color: #fff; - background-color: #87ad1c; - border: 1px solid #18184c; - transition: all .2s ease-in-out; - border-radius: 0; -} - -.btn-primary:hover { - background-color: #87ad1c; - color: #fff; - border: 1px solid #18184c; -} - -.btn-secondary, -.btn-secondary:focus, -.btn-secondary:active { - color: #fff; - background-color: transparent; - transition: all .2s ease-in-out; - border-radius: 0; - font-size: 17px; - font-weight: 600; -} - -.btn-secondary:hover { - background-color: transparent; - color: #fff; -} - -.wr-btn { - font-weight: normal; - font-size: 13px; - color: #fff; - background: #5d81d2; - padding: 10px 10px; - display: inline-block; - border: none; -} - -button.grey-bg:hover { - background-color: #3A9ECF; -} - -.wr-btn:hover { - text-decoration: none; - color: #ffffff; - background-color: #6b94f1; -} - -button.grey-bg { - background-color: #222222; -} - -button.font-extra-large { - font-size: 20px; -} - -img.idp-image { - padding: 3px 2px; -} - - -.padding-left { - padding-left: 10px; -} - -.padding-right { - padding-right: 10px; -} - -.padding-top { - padding-top: 10px; -} - -.padding-bottom { - padding-bottom: 10px; -} - -.padding { - padding: 10px; - margin-bottom: 0px; -} - -.padding-none { - padding: 0px !important; -} - -.padding-left-double { - padding-left: 20px; -} - -.padding-right-double { - padding-right: 20px; -} - -.padding-top-double { - padding-top: 20px; -} - -.padding-bottom-double { - padding-bottom: 20px; -} - -.padding-double { - padding: 20px; -} - -.margin-left { - margin-left: 10px; -} - -.margin-right { - margin-right: 10px; -} - -.margin-top { - margin-top: 10px; -} - -.margin-bottom { - margin-bottom: 10px; -} - -.margin { - margin: 10px; -} - -.margin-none { - margin: 0px !important; -} - -.margin-left-double { - margin-left: 20px; -} - -.margin-right-double { - margin-right: 20px; -} - -.margin-top-double { - margin-top: 20px; -} - -.margin-bottom-double { - margin-bottom: 20px; -} - -.margin-double { - margin: 20px; -} - -.font-small { - font-size: 12px; -} - -.font-medium { - font-size: 16px; -} - -.font-large { - font-size: 1.3em; -} - -.font-extra-large { - font-size: 20px !important; -} - -.error-alert { - background-color: #FFE7E8; -} - -.form-group.required .control-label:after { - content: " *"; - color: red; -} - -@media (min-width: 991px) { - .login-form-wrapper { - padding-top: 5%; - } -} - -.login-form .scope { - font-size: 1.5em; -} - -a, -a:hover, -a:active, -a:focus, -.data-container a, -.login a { - color: #00b4ff; - text-decoration: none; -} - -.policy-info-message { - margin-bottom: 0; - margin-top: 10px; -} - -.static-page { - padding-right: 40px; - padding-left: 40px; -} - -.table-of-contents ul { - padding-left: 20px; - font-size: 14px; -} - -.table-of-contents h4 { - color: #fff; -} - -.table-of-contents ul a { - color: #b7c0cd; -} - -.table-of-contents ul a:hover { - color: #fff; -} - -.table-of-contents ul li.sub { - margin-left: 25px; -} - -.policies-wrapper section { - margin-bottom: 50px; -} - -.policies-wrapper section h2, -.policies-wrapper section h3 { - color: #fff; -} - -.login-logo { - margin: auto; - width: 20%; -} - -h3.ui.header { - font-weight: 300; - color: #efefef; - font-family: -apple-system, BlinkMacSystemFont, Segoe WPC, Segoe UI, HelveticaNeue-Light, Ubuntu, Droid Sans, sans-serif, font-wso2, 'Helvetica Neue', Arial, Helvetica, sans-serif; -} - -h4.ui.header { - font-weight: 280; - color: #efefef; - font-family: -apple-system, BlinkMacSystemFont, Segoe WPC, Segoe UI, HelveticaNeue-Light, Ubuntu, Droid Sans, sans-serif, font-wso2, 'Helvetica Neue', Arial, Helvetica, sans-serif; -} - -div.ui.body { - color: #efefef; - font-size: 12px; - margin-top: 1em; -} - -h5.ui.body { - color: #efefef; - font-size: 1.2em; -} - -div.ui.form { - margin: auto; - color: #efefef; -} - -.ui.primary.button, .ui.primary.button:hover { - background: #18184c; - color: #ffffff; - font-family: -apple-system, BlinkMacSystemFont, Segoe WPC, Segoe UI, HelveticaNeue-Light, Ubuntu, Droid Sans, sans-serif, font-wso2, 'Helvetica Neue', Arial, Helvetica, sans-serif; - font-size: 17px; - font-weight: 500; -} - -.ui.primary.button:hover { - background: #070749; -} - -div.well.policy-info-message { - margin-bottom: 1em; -} - -select.ui.select { - opacity: 0.8; - background-image: linear-gradient(to right, #2a363d 0%, #25405d 100%); -} - -.well { - background-color: transparent; - padding-left: initial; -} - -div.ui.box { - padding-left: 40px; - padding-right: 40px; - padding-top: 20px; -} - -div.ui.subheading { - font-size: 1.2em; -} - -.h4 { - font-size: 1.7em; -} - -div.ui.form.select { - padding-right: 25px; - padding-left: 25px; -} - -div.ui.body.text { - padding-left: unset; -} - -div.ui.form.row { - padding-left: 25px; - padding-right: 25px; -} - -div.section.heading { - color: #159cfa; - padding-top: inherit; -} - -.privacy-policy-product-title { - background: #fff; - padding-left: 15em; - padding-bottom: 1em; - padding-top: 1em; -} - -.ui.segment.toc { - background: #fff; - box-shadow: 0 1px 2px 0 rgba(34,36,38,.15); - padding-right: 1.5rem; - padding-left: 1.5rem; - border-radius: 3px; - border: 1px solid rgba(34,36,38,.15); -} - -ui.segment.toc.h4 { - color: #000; -} - -li.sub { - list-style: none; -} - -li.sub::before { - content: "\2192"; - margin-left: -1em; -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/localstyles-ie7.css b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/localstyles-ie7.css deleted file mode 100644 index 04f8b280..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/localstyles-ie7.css +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -.form-horizontal .controls{ - margin-left:0; -} \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/localstyles.css b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/localstyles.css deleted file mode 100644 index 1e225726..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/localstyles.css +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -body, p, div, a, span, h1, h2, h3, h4 { - font-family: 'helvetica neue', helvetica, arial, 'lucida grande', sans-serif; -} - -body { - background: #999 url(../images/body-back.png) no-repeat center 10px; -} - -.header-strip { - background: #5e5e5e; - height: 10px; -} - -.header-back { - background: transparent url(../images/repeat.jpg) repeat-x left top; - height: 85px; -} - -.header-text { - background: #000; - color: #cccccc; - font-size: 13px; - text-align: center; -} - -.header-text strong { - color: #fff; - font-size: 14px; -} - -.logo { - background: transparent url(../images/logo.png) no-repeat left top; - width: 424px; - height: 85px; - display: block; - cursor: pointer; -} - -.content-section { - text-align: left; - padding: 10px 0 0 0; -} - -.content-section form.well { - text-align: left; -} - -.btn-primary { - background-color: #316a90; - *background-color: #316a90; - background-image: -ms-linear-gradient(top, #316a90, #4583ac); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#316a90), to(#4583ac)); - background-image: -webkit-linear-gradient(top, #316a90, #4583ac); - background-image: -o-linear-gradient(top, #316a90, #4583ac); - background-image: -moz-linear-gradient(top, #316a90, #4583ac); - background-image: linear-gradient(top, #316a90, #4583ac); - background-repeat: repeat-x; - border-color: #0055cc #0055cc #003580; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#316a90', endColorstr='#4583ac', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.login-header { - background: #e86d1f; - color: #fff; - padding: 5px; - - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; - - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; - - margin-top: 10px; -} - -.form-horizontal .control-label { - width: 80px; -} - -.form-horizontal .controls { - margin-left: 100px; -} - -.form-horizontal .form-actions { - padding-left: 100px; - padding-bottom: 0; - margin-bottom: 0; -} - -h1 { - margin-top: 20px; - color: #fff; - font-weight: normal; - font-size: 30px; -} - -.different-login-container { - background: #F5F5F5; - padding: 10px; - -webkit-box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); - -moz-box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); - box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); -} - -.main-login-container { - background: transparent url(../images/container-back.png) repeat left top; - padding: 20px 10px; - margin-bottom: 20px; - -webkit-box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); - -moz-box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); - box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); -} - -.vertical-slitter { - border-right: solid 1px #fff; -} - -.form-actions { - border-top: none; - background: transparent; -} - -.btn-primary.active { - color: rgba(255, 255, 255, 0.75); -} - -.btn-primary { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background: #45484d; /* Old browsers */ - background: -moz-linear-gradient(top, #45484d 0%, #000000 100%); /* FF3.6+ */ - background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #45484d), color-stop(100%, #000000)); /* Chrome,Safari4+ */ - background: -webkit-linear-gradient(top, #45484d 0%, #000000 100%); /* Chrome10+,Safari5.1+ */ - background: -o-linear-gradient(top, #45484d 0%, #000000 100%); /* Opera 11.10+ */ - background: -ms-linear-gradient(top, #45484d 0%, #000000 100%); /* IE10+ */ - background: linear-gradient(to bottom, #45484d 0%, #000000 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#45484d', endColorstr='#000000', GradientType=0); /* IE6-9 */ - padding: 5px 10px; - -} - -.btn-primary:hover, -.btn-primary:focus, -.btn-primary:active, -.btn-primary.active, -.btn-primary.disabled, -.btn-primary[disabled] { - color: #ffffff; - - background: #45484d; /* Old browsers */ - background: -moz-linear-gradient(top, #45484d 0%, #000000 100%); /* FF3.6+ */ - background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #45484d), color-stop(100%, #000000)); /* Chrome,Safari4+ */ - background: -webkit-linear-gradient(top, #45484d 0%, #000000 100%); /* Chrome10+,Safari5.1+ */ - background: -o-linear-gradient(top, #45484d 0%, #000000 100%); /* Opera 11.10+ */ - background: -ms-linear-gradient(top, #45484d 0%, #000000 100%); /* IE10+ */ - background: linear-gradient(to bottom, #45484d 0%, #000000 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#45484d', endColorstr='#000000', GradientType=0); /* IE6-9 */ - -} - -.btn-primary:active, -.btn-primary.active { - background-color: #003399 \9; -} - -.btn-primary-deny { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background: #C94135; /* Old browsers */ - background: -moz-linear-gradient(top, #C94135 0%, #4E0505 100%); /* FF3.6+ */ - background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #C94135), color-stop(100%, #4E0505)); /* Chrome,Safari4+ */ - background: -webkit-linear-gradient(top, #C94135 0%, #4E0505 100%); /* Chrome10+,Safari5.1+ */ - background: -o-linear-gradient(top, #C94135 0%, #4E0505 100%); /* Opera 11.10+ */ - background: -ms-linear-gradient(top, #C94135 0%, #4E0505 100%); /* IE10+ */ - background: linear-gradient(to bottom, #C94135 0%, #4E0505 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C94135', endColorstr='#4E0505', GradientType=0); /* IE6-9 */ - padding: 5px 10px; - -} - -.btn-primary-deny:hover, -.btn-primary-deny:focus, -.btn-primary-deny:active, -.btn-primary-deny.active, -.btn-primary-deny.disabled, -.btn-primary-deny[disabled] { - color: #ffffff; - - background: #C94135; /* Old browsers */ - background: -moz-linear-gradient(top, #C94135 0%, #4E0505 100%); /* FF3.6+ */ - background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #C94135), color-stop(100%, #4E0505)); /* Chrome,Safari4+ */ - background: -webkit-linear-gradient(top, #C94135 0%, #4E0505 100%); /* Chrome10+,Safari5.1+ */ - background: -o-linear-gradient(top, #C94135 0%, #4E0505 100%); /* Opera 11.10+ */ - background: -ms-linear-gradient(top, #C94135 0%, #4E0505 100%); /* IE10+ */ - background: linear-gradient(to bottom, #C94135 0%, #4E0505 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C94135', endColorstr='#4E0505', GradientType=0); /* IE6-9 */ - -} - -.btn-primary-deny:active, -.btn-primary-deny.active { - background-color: #CA1909 \9; -} - -.marL30 { - margin-left: 30% !important; -} - -.marL32 { - margin-left: 32% !important; -} - -h2 { - color: #ddd; - font-weight: normal; -} - -.different-login-container a.main-link { - display: block; - background: transparent url(../images/icon-default.png) no-repeat left top; - width: 75px; - height: 76px; - float: left; - margin-right: 10px; - padding-left: 74px; -} - -#claimed_id { - background: #fff url(../images/openid-input.gif) no-repeat left 4px; - padding-left: 20px; -} - -.slidePopper { - position: absolute; - margin-top: 70px; - padding: 10px; - background: #fff; - border: solid 1px #ccc; - border-radius: 5px; - z-index: 6; -} - -.slidePopper-cancel { - cursor: pointer; -} - -.overlay { - background: #ccc; - opacity: 0.5; - width: 500px; - height: 500px; - position: absolute; - top: 0; - left: 0; - z-index: 5; -} - -.go-btn { - margin-top: -8px; -} diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/openid-provider.css b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/openid-provider.css deleted file mode 100644 index e5678434..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/css/openid-provider.css +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -.card-box-top{ - background-image:url(../images/card-box02.jpg); - background-repeat:repeat-x; - background-position:0 0; -} -.card-box-left{ - background-image:url(../images/card-box08.jpg); - background-repeat:repeat-y; - background-position:0 0; - width:15px; -} -.card-box-right{ - background-image:url(../images/card-box04.jpg); - background-repeat:repeat-y; - background-position:0 0; - width:18px; -} -.card-box-bottom{ - background-image:url(../images/card-box06.jpg); - background-repeat:repeat-x; - background-position:0 0; -} -.card-box-mid{ - background-color:#ffffff; -} -.user-pic{ - margin-bottom:10px; -} -.card-box{ - width:400px; -} -.openid-box-top{ - background-image:url(../images/openid-box-back.gif); - background-position:0 0; - background-repeat:no-repeat; - width:812px; - height:123px; -} -.openid-box-05{ - background-image:url(../images/openid-box-05.gif); -} -.openid-box-07{ - background-image:url(../images/openid-box-07.gif); -} - -.openid-box-06{ - background-image:url(../images/openid-box-06.gif); - background-position:0 0; - background-repeat:repeat-x; -} -.openid-box-04{ - background-image:url(../images/openid-box-04.gif); - background-position:0 0; - background-repeat:repeat-y; - width:2px; -} -.openid-box-08{ - background-image:url(../images/openid-box-08.gif); - background-position:0 0; - background-repeat:repeat-y; - width:2px; -} -.openid-box-back{ - background-color:#e3e7ea; - padding-bottom:50px; - padding-left:50px; - font-size:20px; -} -.openid-box-05,.openid-box-07{ - background-position:0 0; - background-repeat:no-repeat; - width:19px; - height:31px; -} -.openid-box{ - width:812px; -} -.openid-box-username{ - color:#569643; -} - -.userClaimsTbl { - margin:0px;padding:0px; - width:100%; - border:1px solid #000000; - - -moz-border-radius-bottomleft:0px; - -webkit-border-bottom-left-radius:0px; - border-bottom-left-radius:0px; - - -moz-border-radius-bottomright:0px; - -webkit-border-bottom-right-radius:0px; - border-bottom-right-radius:0px; - - -moz-border-radius-topright:0px; - -webkit-border-top-right-radius:0px; - border-top-right-radius:0px; - - -moz-border-radius-topleft:0px; - -webkit-border-top-left-radius:0px; - border-top-left-radius:0px; -}.userClaimsTbl table{ - border-collapse: collapse; - border-spacing: 0; - width:100%; - height:100%; - margin:0px;padding:0px; -}.userClaimsTbl tr:last-child td:last-child { - -moz-border-radius-bottomright:0px; - -webkit-border-bottom-right-radius:0px; - border-bottom-right-radius:0px; -} -.userClaimsTbl table tr:first-child td:first-child { - -moz-border-radius-topleft:0px; - -webkit-border-top-left-radius:0px; - border-top-left-radius:0px; -} -.userClaimsTbl table tr:first-child td:last-child { - -moz-border-radius-topright:0px; - -webkit-border-top-right-radius:0px; - border-top-right-radius:0px; -}.userClaimsTbl tr:last-child td:first-child{ - -moz-border-radius-bottomleft:0px; - -webkit-border-bottom-left-radius:0px; - border-bottom-left-radius:0px; -}.userClaimsTbl tr:hover td{ - background-color:#ffffff; - - -} -.userClaimsTbl td{ - vertical-align:middle; - - background-color:#e5e5e5; - - border:1px solid #000000; - border-width:0px 1px 1px 0px; - text-align:left; - padding:7px; - font-size:12px; - font-family:Arial; - font-weight:normal; - color:#000000; -}.userClaimsTbl tr:last-child td{ - border-width:0px 1px 0px 0px; -}.userClaimsTbl tr td:last-child{ - border-width:0px 0px 1px 0px; -}.userClaimsTbl tr:last-child td:last-child{ - border-width:0px 0px 0px 0px; -} -.userClaimsTbl tr:first-child td{ - background:-o-linear-gradient(bottom, #cccccc 5%, #cccccc 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #cccccc) ); - background:-moz-linear-gradient( center top, #cccccc 5%, #cccccc 100% ); - filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#cccccc"); background: -o-linear-gradient(top,#cccccc,cccccc); - - background-color:#cccccc; - border:0px solid #000000; - text-align:center; - border-width:0px 0px 1px 1px; - font-size:14px; - font-family:Arial; - font-weight:bold; - color:#000000; -} -.userClaimsTbl tr:first-child:hover td{ - background:-o-linear-gradient(bottom, #cccccc 5%, #cccccc 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #cccccc) ); - background:-moz-linear-gradient( center top, #cccccc 5%, #cccccc 100% ); - filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#cccccc"); background: -o-linear-gradient(top,#cccccc,cccccc); - - background-color:#cccccc; -} -.userClaimsTbl tr:first-child td:first-child{ - border-width:0px 0px 1px 0px; -} -.userClaimsTbl tr:first-child td:last-child{ - border-width:0px 0px 1px 1px; -} \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/default_consent.jsp b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/default_consent.jsp deleted file mode 100644 index ff38a299..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/default_consent.jsp +++ /dev/null @@ -1,181 +0,0 @@ -<%-- - ~ Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - ~ - ~ WSO2 LLC. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=UTF-8" language="java" %> -<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> - - - -
- - - -
- - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/default_displayconsent.jsp b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/default_displayconsent.jsp deleted file mode 100644 index 2048c280..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/default_displayconsent.jsp +++ /dev/null @@ -1,143 +0,0 @@ -<%-- - ~ Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - ~ - ~ WSO2 LLC. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> -<%@ page import="java.util.List" %> -<%@ page import="java.util.Map" %> -<%@ page import="org.json.JSONArray" %> -<%@ page import="org.json.JSONObject" %> - -<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> - - -<% - session.setAttribute("configParamsMap", request.getAttribute("data_requested")); - Map> consentData = (Map>) request.getAttribute("data_requested"); -%> -
-
-
-
- diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.svg b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.svg deleted file mode 100644 index 43b5ed22..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.svg +++ /dev/null @@ -1,593 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.ttf b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.ttf deleted file mode 100644 index 1da72769..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.ttf and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.woff b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.woff deleted file mode 100644 index 0c699487..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/fonts/Roboto/Roboto-Bold-webfont.woff and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/generic-exception-response.jsp b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/generic-exception-response.jsp deleted file mode 100644 index 5d384318..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/generic-exception-response.jsp +++ /dev/null @@ -1,81 +0,0 @@ -<%-- - ~ Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - ~ - ~ WSO2 LLC. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - - - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ page import="org.owasp.encoder.Encode" %> -<% - String stat = request.getParameter("status"); - String statusMessage = request.getParameter("statusMsg"); - if (stat == null || statusMessage == null) { - stat = "Authentication Error !"; - statusMessage = "Something went wrong during the authentication process. Please try signing in again."; - } - session.invalidate(); -%> - - - - - - - -
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/U2F.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/U2F.png deleted file mode 100644 index c9d8f3a2..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/U2F.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/body-back.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/body-back.png deleted file mode 100644 index f2e7914b..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/body-back.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/container-back.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/container-back.png deleted file mode 100644 index 3c805492..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/container-back.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/favicon.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/favicon.png deleted file mode 100644 index 2ad073a9..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/favicon.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/icon-default.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/icon-default.png deleted file mode 100644 index 70a4834e..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/icon-default.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/login-back.svg b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/login-back.svg deleted file mode 100644 index 8c719e2b..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/login-back.svg +++ /dev/null @@ -1,147 +0,0 @@ - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/login-icon.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/login-icon.png deleted file mode 100644 index 6b43c768..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/login-icon.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo-dark.svg b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo-dark.svg deleted file mode 100755 index 9ea4358f..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo-dark.svg +++ /dev/null @@ -1,153 +0,0 @@ - - - - - - image/svg+xml - - OB-Publisher-logo-Dark-background - - - - - - - - OB-Publisher-logo-Dark-background - - - - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo-inverse.svg b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo-inverse.svg deleted file mode 100644 index 6e7f1d89..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo-inverse.svg +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo.png deleted file mode 100644 index 2de1612c..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/logo.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/openid-input.gif b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/openid-input.gif deleted file mode 100644 index cde836c8..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/openid-input.gif and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/repeat.jpg b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/repeat.jpg deleted file mode 100644 index 891eea01..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/repeat.jpg and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/wso2-open-banking-logo.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/wso2-open-banking-logo.png deleted file mode 100644 index ae180a42..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/wso2-open-banking-logo.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/wso2-open-banking-new.png b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/wso2-open-banking-new.png deleted file mode 100644 index 18d55b28..00000000 Binary files a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/images/wso2-open-banking-new.png and /dev/null differ diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/includes/consent_bottom.jsp b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/includes/consent_bottom.jsp deleted file mode 100644 index 8cbea3e7..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/includes/consent_bottom.jsp +++ /dev/null @@ -1,30 +0,0 @@ -<%-- - ~ Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - ~ - ~ WSO2 LLC. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=UTF-8" %> - -
- - - - - - - - - diff --git a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/includes/consent_top.jsp b/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/includes/consent_top.jsp deleted file mode 100644 index 15427d5e..00000000 --- a/open-banking-accelerator/internal-apis/internal-webapps/com.wso2.openbanking.authentication.webapp/src/main/webapp/includes/consent_top.jsp +++ /dev/null @@ -1,52 +0,0 @@ -<%-- - ~ Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - ~ - ~ WSO2 LLC. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=UTF-8" language="java" %> -<%@ page import="org.json.JSONArray" %> -<%@ page import="org.json.JSONObject" %> -<%@ page import="org.owasp.encoder.Encode" %> - -<%@ page import="java.util.List" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="org.apache.commons.lang.StringUtils" %> -<%@ page import="org.apache.commons.lang.ArrayUtils" %> -<%@ page import="java.util.stream.Stream" %> - -<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> - - - - - - - - - - -
-
-
-