From 075622410522072ced16a0b578cb4a8000115392 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Thu, 7 Nov 2024 11:39:23 +0530 Subject: [PATCH 01/34] Add PreUpdatePasswordAction class --- .../model/PreUpdatePasswordAction.java | 233 ++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java new file mode 100644 index 000000000000..78dcdee21ef8 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.model; + +import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; + +import java.util.Map; + +/** + * PreUpdatePasswordAction. + */ +public class PreUpdatePasswordAction extends Action { + + /** + * Password Format Enum. + * Defines the category of the password sharing types. + */ + public enum PasswordFormat { + + PLAIN_TEXT, + SHA256_HASHED; + } + + private final PasswordFormat passwordSharingFormat; + private final String certificate; + + public PreUpdatePasswordAction(ResponseBuilder responseBuilder) { + + super(responseBuilder); + this.passwordSharingFormat = responseBuilder.passwordSharingFormat; + this.certificate = responseBuilder.certificate; + } + + public PreUpdatePasswordAction(RequestBuilder requestBuilder) { + + super(requestBuilder); + this.passwordSharingFormat = requestBuilder.passwordSharingFormat; + this.certificate = requestBuilder.certificate; + } + + public PasswordFormat getPasswordSharingFormat() { + + return passwordSharingFormat; + } + + public String getCertificate() { + + return certificate; + } + + /** + * Retrieves a map of property names and values from the endpoint configuration, along with the password + * sharing format and certificate if they are set. + * + * @return A map containing the endpoint properties, password sharing format, and certificate. + */ + @Override + public Map getPropertiesMap() { + + Map propertiesMap = super.getPropertiesMap(); + if (getPasswordSharingFormat() != null) { + propertiesMap.put(ActionMgtConstants.PASSWORD_SHARING_FORMAT_PROPERTY, getPasswordSharingFormat().name()); + } + if (getCertificate() != null) { + propertiesMap.put(ActionMgtConstants.CERTIFICATE_PROPERTY, getCertificate()); + } + + return propertiesMap; + } + + /** + * Response Builder for PreUpdatePasswordAction. + */ + public static class ResponseBuilder extends ActionResponseBuilder { + + private PasswordFormat passwordSharingFormat; + private String certificate; + + public ResponseBuilder() { + } + + public ResponseBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat) { + + this.passwordSharingFormat = passwordSharingFormat; + return this; + } + + public ResponseBuilder certificate(String certificate) { + + this.certificate = certificate; + return this; + } + + @Override + public ResponseBuilder id(String id) { + + super.id(id); + return this; + } + + @Override + public ResponseBuilder type(ActionTypes type) { + + super.type(type); + return this; + } + + @Override + public ResponseBuilder name(String name) { + + super.name(name); + return this; + } + + @Override + public ResponseBuilder description(String description) { + + super.description(description); + return this; + } + + @Override + public ResponseBuilder status(Status status) { + + super.status(status); + return this; + } + + @Override + public ResponseBuilder endpoint(EndpointConfig endpoint) { + + super.endpoint(endpoint); + return this; + } + + /** + * Sets properties from a given map to the relevant attributes in the builder. + * Based on the provided properties, this method configures the {@link EndpointConfig} + * with the URI and the {@link Authentication} object. + * + * @param propertiesMap A map containing the endpoint URI, authentication type, and authentication properties. + * @return The current {@link ActionResponseBuilder} instance with the configured attributes. + */ + @Override + public ActionResponseBuilder setPropertiesToAttributes(Map propertiesMap) { + + if (propertiesMap.isEmpty()) { + return this; + } + + // Set the endpoint properties to the common attributes. + super.setPropertiesToAttributes(propertiesMap); + // Set other properties to the specific attributes of PRE_UPDATE_PASSWORD action type. + + return this.passwordSharingFormat(PasswordFormat + .valueOf(propertiesMap.get(ActionMgtConstants.PASSWORD_SHARING_FORMAT_PROPERTY))) + .certificate(propertiesMap.get(ActionMgtConstants.CERTIFICATE_PROPERTY)); + } + + @Override + public PreUpdatePasswordAction build() { + + return new PreUpdatePasswordAction(this); + } + } + + /** + * Request Builder for PreUpdatePasswordAction. + */ + public static class RequestBuilder extends ActionRequestBuilder { + + private PasswordFormat passwordSharingFormat; + private String certificate; + + public RequestBuilder() { + } + + public RequestBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat) { + + this.passwordSharingFormat = passwordSharingFormat; + return this; + } + + public RequestBuilder certificate(String certificate) { + + this.certificate = certificate; + return this; + } + + @Override + public RequestBuilder name(String name) { + + super.name(name); + return this; + } + + @Override + public RequestBuilder description(String description) { + + super.description(description); + return this; + } + + @Override + public RequestBuilder endpoint(EndpointConfig endpoint) { + + super.endpoint(endpoint); + return this; + } + + @Override + public PreUpdatePasswordAction build() { + + return new PreUpdatePasswordAction(this); + } + } +} From a3a61118a10f88ab441a6a37f17d2fd70c7e9b5d Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Sun, 10 Nov 2024 11:38:42 +0530 Subject: [PATCH 02/34] Improve action-mgt to handle action related properties --- .../pom.xml | 5 + .../management/ActionManagementService.java | 14 - .../ActionManagementServiceImpl.java | 79 +- .../constant/ActionMgtConstants.java | 25 +- .../management/dao/ActionManagementDAO.java | 28 - .../dao/impl/ActionManagementDAOImpl.java | 722 +++++++++++------- .../dao/impl/CacheBackedActionMgtDAO.java | 20 +- .../internal/ActionMgtServiceComponent.java | 24 + .../ActionMgtServiceComponentHolder.java | 22 + .../action/management/model/Action.java | 6 - .../model/PreUpdatePasswordAction.java | 60 +- .../ActionManagementServiceImplTest.java | 30 - .../dao/ActionManagementDAOImplTest.java | 69 +- 13 files changed, 530 insertions(+), 574 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index accda5a114c9..81e2620a3986 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -41,6 +41,10 @@ org.wso2.carbon.identity.framework org.wso2.carbon.identity.secret.mgt.core + + org.wso2.carbon.identity.framework + org.wso2.carbon.identity.certificate.management + org.json.wso2 json @@ -54,6 +58,7 @@ org.mockito mockito-core + test org.wso2.carbon.identity.framework diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java index fe1851cb1b13..fe3899c521a3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java @@ -20,7 +20,6 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.Authentication; import java.util.List; import java.util.Map; @@ -115,17 +114,4 @@ Action updateAction(String actionType, String actionId, Action action, String te * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. */ Action getActionByActionId(String actionType, String actionId, String tenantDomain) throws ActionMgtException; - - /** - * Update the authentication of the action endpoint. - * - * @param actionType Action Type. - * @param actionId Action ID. - * @param authentication Authentication Information to be updated. - * @param tenantDomain Tenant domain. - * @return Action response after update. - * @throws ActionMgtException If an error occurs while updating action endpoint authentication information. - */ - Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, - String tenantDomain) throws ActionMgtException; } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java index 33fd7ca6a465..632cfdd92ed9 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java @@ -27,7 +27,6 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; import org.wso2.carbon.identity.action.management.util.ActionValidator; @@ -237,32 +236,6 @@ public Action getActionByActionId(String actionType, String actionId, String ten IdentityTenantUtil.getTenantId(tenantDomain)); } - /** - * Update endpoint authentication of a given action. - * - * @param actionType Action type. - * @param actionId Action ID. - * @param authentication Authentication Information to be updated. - * @param tenantDomain Tenant domain. - * @return Updated action. - * @throws ActionMgtException if an error occurred while updating endpoint authentication information. - */ - @Override - public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, - String tenantDomain) throws ActionMgtException { - - String resolvedActionType = getActionTypeFromPath(actionType); - Action existingAction = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - doEndpointAuthenticationValidation(authentication); - if (existingAction.getEndpoint().getAuthentication().getType().equals(authentication.getType())) { - // Only need to update the properties since the authentication type is same. - return updateEndpointAuthenticationProperties(resolvedActionType, actionId, authentication, tenantDomain); - } else { - // Need to update the authentication type and properties. - return updateEndpoint(resolvedActionType, actionId, existingAction, authentication, tenantDomain); - } - } - /** * Get Action Type from path. * @@ -317,61 +290,11 @@ private Action checkIfActionExists(String actionType, String actionId, String te return action; } - /** - * Update the authentication type and properties of the action endpoint. - * - * @param actionType Action Type. - * @param actionId Action Id. - * @param existingAction Existing Action Information. - * @param authentication Authentication Information to be updated. - * @param tenantDomain Tenant Domain. - * @return Action response after update. - * @throws ActionMgtException If an error occurs while updating action endpoint authentication. - */ - private Action updateEndpoint(String actionType, String actionId, Action existingAction, - Authentication authentication, String tenantDomain) - throws ActionMgtException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Updating endpoint authentication of Action Type: %s " + - "and Action ID: %s to Authentication Type: %s", actionType, actionId, - authentication.getType().name())); - } - EndpointConfig endpoint = new EndpointConfig.EndpointConfigBuilder() - .uri(existingAction.getEndpoint().getUri()) - .authentication(authentication).build(); - return CACHE_BACKED_DAO.updateActionEndpoint(actionType, actionId, endpoint, - existingAction.getEndpoint().getAuthentication(), IdentityTenantUtil.getTenantId(tenantDomain)); - } - - /** - * Update the authentication properties of the action endpoint. - * - * @param actionType Action Type. - * @param actionId Action Id. - * @param authentication Authentication Information to be updated. - * @param tenantDomain Tenant domain. - * @return Action response after update. - * @throws ActionMgtException If an error occurs while updating action endpoint authentication properties. - */ - private Action updateEndpointAuthenticationProperties(String actionType, String actionId, - Authentication authentication, String tenantDomain) - throws ActionMgtException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Updating endpoint authentication properties of Action Type: %s " + - "Action ID: %s and Authentication Type: %s", actionType, actionId, - authentication.getType().name())); - } - return CACHE_BACKED_DAO.updateActionEndpointAuthProperties(actionType, actionId, authentication, - IdentityTenantUtil.getTenantId(tenantDomain)); - } - /** * Perform pre validations on action model when creating an action. * * @param action Action create model. - * @throws ActionMgtException if action model is invalid. + * @throws ActionMgtClientException if action model is invalid. */ private void doPreAddActionValidations(Action action) throws ActionMgtClientException { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index 5eff6fda6669..bd03dcd0ebda 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -23,8 +23,10 @@ */ public class ActionMgtConstants { - public static final String URI_ATTRIBUTE = "uri"; - public static final String AUTHN_TYPE_ATTRIBUTE = "authnType"; + public static final String URI_PROPERTY = "uri"; + public static final String AUTHN_TYPE_PROPERTY = "authnType"; + public static final String PASSWORD_SHARING_FORMAT_PROPERTY = "passwordSharingFormat"; + public static final String CERTIFICATE_ID_PROPERTY = "certificateId"; public static final String IDN_SECRET_TYPE_ACTION_SECRETS = "ACTION_API_ENDPOINT_AUTH_SECRETS"; public static final String ACTION_NAME_FIELD = "Action name"; @@ -57,11 +59,11 @@ public enum ErrorMessages { // Server errors. ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", "Error while persisting Action in the system."), - ERROR_WHILE_ADDING_ENDPOINT_PROPERTIES("65002", "Error while adding Endpoint properties", - "Error while persisting Action Endpoint properties in the system."), - ERROR_WHILE_RETRIEVING_ACTION_ENDPOINT_PROPERTIES("65003", - "Error while retrieving Action Endpoint properties", - "Error while retrieving Action Endpoint properties from the system."), + ERROR_WHILE_ADDING_ACTION_PROPERTIES("65002", "Error while adding Action properties", + "Error while persisting Action properties in the system."), + ERROR_WHILE_RETRIEVING_ACTION_PROPERTIES("65003", + "Error while retrieving Action properties", + "Error while retrieving Action properties from the system."), ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE("65004", "Error while retrieving Actions by Action Type", "Error while retrieving Actions by Action Type from the system."), @@ -84,11 +86,10 @@ public enum ErrorMessages { ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES("65012", "Error while decrypting Action Endpoint Authentication properties", "Error while decrypting Action Endpoint Authentication properties in the system."), - ERROR_NO_AUTHENTICATION_TYPE("65013", - "Error while retrieving Action Endpoint Authentication configurations", - "Authentication type is not defined for the Action Endpoint."), - ERROR_WHILE_UPDATING_ACTION_BASIC_INFO("65014", "Error while updating basic Action information", - "Error while updating basic Action information in the system."); + ERROR_WHILE_UPDATING_ACTION_BASIC_INFO("65013", "Error while updating basic Action information", + "Error while updating basic Action information in the system."), + ERROR_WHILE_BUILDING_ACTION_RESPONSE("65014", "Error while building Action response.", + "Error while building Action response object."),; private final String code; private final String message; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java index 9def55c4247b..ecb131d1adf6 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java @@ -20,8 +20,6 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; import java.util.List; import java.util.Map; @@ -118,30 +116,4 @@ Action updateAction(String actionType, String actionId, Action updatingAction, A * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. */ Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException; - - /** - * Update the endpoint authentication properties of an {@link Action} by given Action ID. - * - * @param actionId Action ID. - * @param authentication Authentication information to be updated. - * @param tenantId Tenant Id. - * @return Updated Action. - * @throws ActionMgtException If an error occurs while updating the Action endpoint authentication properties. - */ - Action updateActionEndpointAuthProperties(String actionType, String actionId, Authentication authentication, - int tenantId) throws ActionMgtException; - - /** - * Update the endpoint authentication properties of an {@link Action} by given Action ID. - * - * @param actionType Action Type. - * @param actionId Action ID. - * @param endpoint Endpoint information to be updated. - * @param currentAuthentication Current Action endpoint authentication information. - * @param tenantId Tenant Id. - * @return Updated Action. - * @throws ActionMgtException If an error occurs while updating the Action endpoint. - */ - Action updateActionEndpoint(String actionType, String actionId, EndpointConfig endpoint, - Authentication currentAuthentication, int tenantId) throws ActionMgtException; } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 43121fbb930d..cff0b1044e4c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -31,18 +31,29 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtRuntimeException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtException; +import org.wso2.carbon.identity.certificate.management.model.Certificate; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; + +import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.AUTHN_TYPE_PROPERTY; +import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.CERTIFICATE_ID_PROPERTY; +import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.PASSWORD_SHARING_FORMAT_PROPERTY; +import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.URI_PROPERTY; /** * This class implements the {@link ActionManagementDAO} interface. @@ -75,13 +86,8 @@ public Action addAction(String actionType, String actionId, Action action, Integ statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }, action, false); - // Encrypt secrets. - List encryptedAuthProperties = actionSecretProcessor - .encryptAssociatedSecrets(action.getEndpoint().getAuthentication(), actionId); - - // Add Endpoint configuration properties. - addEndpointProperties(actionId, getEndpointProperties(action.getEndpoint().getUri(), - action.getEndpoint().getAuthentication().getType().name(), encryptedAuthProperties), tenantId); + // Add action properties. + addActionProperties(actionType, actionId, action, tenantId); return null; }); @@ -102,27 +108,35 @@ public Action addAction(String actionType, String actionId, Action action, Integ public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + List actions = new ArrayList<>(); try { - return jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE, - (resultSet, rowNumber) -> new Action.ActionResponseBuilder() - .id(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_UUID)) - .type(Action.ActionTypes - .valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) - .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) - .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) - .status(Action.Status - .valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) - .endpoint(getActionEndpointConfigById( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_UUID), tenantId)) - .build(), + jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE, + (resultSet, rowNumber) -> { + String actionId = resultSet.getString(ActionMgtSQLConstants.Column.ACTION_UUID); + Action actionBasicInfo = new Action.ActionResponseBuilder() + .id(actionId) + .type(Action.ActionTypes + .valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) + .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) + .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) + .status(Action.Status.valueOf( + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) + .build(); + + Map actionProperties = getActionPropertiesById(actionId, tenantId); + actions.add(buildActionResponse(actionType, actionBasicInfo, actionProperties, tenantId)); + return null; + }, statement -> { statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); + + return actions; } catch (ActionMgtRuntimeException | DataAccessException e) { /** * Handling {@link ActionMgtRuntimeException}, which is intentionally thrown to represent underlying - * exceptions from the {@link #getActionEndpointConfigById(String, Integer)} method. + * exceptions from the {@link #buildActionResponse(String, Action, Map, Integer)} method. */ throw ActionManagementUtil.handleServerException( ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); @@ -138,8 +152,8 @@ public Action updateAction(String actionType, String actionId, Action updatingAc jdbcTemplate.withTransaction(template -> { // Update Basic Info. updateBasicInfo(actionType, actionId, updatingAction, existingAction, tenantId); - // Update Endpoint URI and Authentication. - updateEndpointUriAndAuthentication(actionId, updatingAction, existingAction, tenantId); + // Update Action Properties. + updateActionProperties(actionType, actionId, updatingAction, existingAction, tenantId); return null; }); @@ -171,6 +185,8 @@ public void deleteAction(String actionType, String actionId, Action action, Inte }); // Delete action endpoint authentication related secrets. actionSecretProcessor.deleteAssociatedSecrets(action.getEndpoint().getAuthentication(), actionId); + // Delete action type specific properties. + deleteActionTypeSpecificProperties(actionType, action, tenantId); return null; }); @@ -223,157 +239,127 @@ public Action getActionByActionId(String actionType, String actionId, Integer te try { Action action = getActionBasicInfoById(actionType, actionId, tenantId); if (action != null) { - action = new Action.ActionResponseBuilder() - .id(actionId) - .type(Action.ActionTypes.valueOf(actionType)) - .name(action.getName()) - .description(action.getDescription()) - .status(action.getStatus()) - .endpoint(getActionEndpointConfigById(actionId, tenantId)) - .build(); + Map actionProperties = getActionPropertiesById(actionId, tenantId); + action = buildActionResponse(actionType, action, actionProperties, tenantId); } return action; - } catch (ActionMgtException | ActionMgtRuntimeException e) { + } catch (ActionMgtException | ActionMgtRuntimeException | SQLException e) { /** * Handling {@link ActionMgtRuntimeException}, which is intentionally thrown to represent underlying - * exceptions from the {@link #getActionEndpointConfigById(String, Integer)} method. + * exceptions from the {@link #buildActionResponse(String, Action, Map, Integer)} method. */ throw ActionManagementUtil.handleServerException( ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); } } - @Override - public Action updateActionEndpointAuthProperties(String actionType, String actionId, Authentication authentication, - int tenantId) throws ActionMgtException { - - updateActionEndpointAuthProperties(actionId, authentication, tenantId); - return getActionByActionId(actionType, actionId, tenantId); - } - - @Override - public Action updateActionEndpoint(String actionType, String actionId, EndpointConfig endpoint, - Authentication currentAuthentication, int tenantId) - throws ActionMgtException { - - updateActionEndpoint(actionId, endpoint, currentAuthentication, tenantId); - return getActionByActionId(actionType, actionId, tenantId); - } - /** - * Update the endpoint authentication properties of an {@link Action} by given Action ID. + * Add Action properties. * - * @param actionId Action ID. - * @param authentication Authentication information to be updated. - * @param tenantId Tenant Id. - * @throws ActionMgtServerException If an error occurs while updating the Action endpoint authentication properties. + * @param actionType Type of the Action. + * @param actionId UUID of the created Action. + * @param action Properties of the Action. + * @param tenantId Tenant ID. + * @throws ActionMgtServerException If an error occurs while adding action properties to the database. */ - private void updateActionEndpointAuthProperties(String actionId, Authentication authentication, int tenantId) - throws ActionMgtServerException { + private void addActionProperties(String actionType, String actionId, Action action, + Integer tenantId) throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - Map nonSecretEndpointProperties = authentication.getProperties().stream() - .filter(property -> !property.getIsConfidential()) - .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + Map actionProperties = resolveEndpointProperties(actionId, action, null); + actionProperties.putAll(resolveActionTypeSpecificProperties(actionType, actionId, action, null, tenantId)); - jdbcTemplate.withTransaction(template -> { - // Update non-secret endpoint properties. - updateActionEndpointProperties(actionId, nonSecretEndpointProperties, tenantId); - // Encrypt and update secret endpoint properties. - actionSecretProcessor.encryptAssociatedSecrets(authentication, actionId); - return null; - }); - } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action Endpoint Authentication Properties of " + - "Auth type: %s and Action ID: %s in Tenant Domain: %s. Rolling back updated action" + - " endpoint authentication properties.", authentication.getType(), actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } + addActionPropertiesToDB(actionId, actionProperties, tenantId); + } catch (CertificateMgtException | SecretManagementException | TransactionException e) { throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); + ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION_PROPERTIES, e); } } /** - * Update the endpoint information of an {@link Action} by given Action ID. + * Add Action properties to the Database. * - * @param actionId Action ID. - * @param endpoint Endpoint information to be updated. - * @param currentAuthentication Current Action endpoint authentication information. - * @param tenantId Tenant Id. - * @throws ActionMgtServerException If an error occurs while updating the Action endpoint. + * @param actionId UUID of the created Action. + * @param actionProperties Properties of the Action. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while persisting action properties to the database. */ - private void updateActionEndpoint(String actionId, EndpointConfig endpoint, Authentication currentAuthentication, - int tenantId) throws ActionMgtServerException { + private void addActionPropertiesToDB(String actionId, Map actionProperties, Integer tenantId) + throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTIES, + jdbcTemplate.withTransaction(template -> { + template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT_PROPERTIES, statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + for (Map.Entry property : actionProperties.entrySet()) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + property.getKey()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, + property.getValue()); + statement.addBatch(); + } + }, null); + return null; + }); + } + + /** + * Update the properties of an {@link Action} by given Action ID. + * + * @param actionId Action ID. + * @param updatingAction Information to be updated. + * @param existingAction Existing Action information. + * @param tenantId Tenant ID. + * @throws ActionMgtServerException If an error occurs while updating the Action properties. + * @throws CertificateMgtException If an error occurs while updating the Action certificate. + * @throws SecretManagementException If an error occurs while updating the Authentication secrets. + */ + private void updateActionProperties(String actionType, String actionId, Action updatingAction, + Action existingAction, Integer tenantId) + throws ActionMgtServerException, CertificateMgtException, SecretManagementException { - // Add new Endpoint configuration properties. - Map propertiesMap = getEndpointProperties(endpoint.getUri(), - endpoint.getAuthentication().getType().name(), - endpoint.getAuthentication().getPropertiesWithSecretReferences(actionId)); - addEndpointProperties(actionId, propertiesMap, tenantId); - // Encrypt and add new endpoint properties secrets. - actionSecretProcessor.encryptAssociatedSecrets(endpoint.getAuthentication(), actionId); + Map actionProperties = resolveEndpointProperties(actionId, updatingAction, existingAction); + actionProperties.putAll(resolveActionTypeSpecificProperties(actionType, actionId, updatingAction, + existingAction, tenantId)); - // Delete old secrets. - actionSecretProcessor.deleteAssociatedSecrets(currentAuthentication, actionId); - return null; - }); - } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action Endpoint Authentication from Auth type: %s" + - " to Auth type: %s of Action ID: %s in Tenant Domain: %s. Rolling back updated" + - " action endpoint authentication.", currentAuthentication.getType(), - endpoint.getAuthentication().getType(), actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); - } + updateActionPropertiesInDB(actionId, actionProperties, tenantId); } /** - * Add Action Endpoint properties to the Database. + * Update the basic information of an {@link Action} by given Action ID. * * @param actionId UUID of the created Action. - * @param endpointProperties Endpoint properties of the Action. + * @param updatingProperties Action properties to be updated. * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while adding endpoint properties to the database. + * @throws ActionMgtServerException If an error occurs while updating the Action properties. */ - private void addEndpointProperties(String actionId, Map endpointProperties, Integer tenantId) - throws ActionMgtException { + private void updateActionPropertiesInDB(String actionId, Map updatingProperties, + Integer tenantId) throws ActionMgtServerException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT_PROPERTIES, - statement -> { - for (Map.Entry property : endpointProperties.entrySet()) { + template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTIES, + statement -> { statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, - property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, - property.getValue()); - statement.addBatch(); - } - }, null); + }); + + // Add updated action properties. + addActionPropertiesToDB(actionId, updatingProperties, tenantId); return null; }); } catch (TransactionException e) { + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Error while updating the Action properties of Action ID: %s in " + + "Tenant Domain: %s. Rolling back updated action endpoint authentication.", + actionId, IdentityTenantUtil.getTenantDomain(tenantId))); + } throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ENDPOINT_PROPERTIES, e); + ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); } } @@ -410,133 +396,35 @@ private Action getActionBasicInfoById(String actionType, String actionId, Intege } /** - * Get Action Endpoint properties by ID. + * Get Action properties by ID. * - * @param actionUUID UUID of the created Action. - * @param tenantId Tenant ID. - * @return Endpoint Configuration. - * @throws ActionMgtRuntimeException If an error occurs while retrieving endpoint properties from the database. + * @param actionId UUID of the created Action. + * @param tenantId Tenant ID. + * @return A map of action properties, including any additional data based on action type. + * @throws SQLException If an error occurs while retrieving action properties from the database. */ - private EndpointConfig getActionEndpointConfigById(String actionUUID, Integer tenantId) - throws ActionMgtRuntimeException { + private Map getActionPropertiesById(String actionId, Integer tenantId) + throws SQLException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + Map actionEndpointProperties = new HashMap<>(); try { - Map actionEndpointProperties = new HashMap<>(); jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_ENDPOINT_INFO_BY_ID, - (resultSet, rowNumber) -> { - actionEndpointProperties.put( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME), - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE)); - return null; - }, + (resultSet, rowNumber) -> { + actionEndpointProperties.put( + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME), + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE)); + return null; + }, statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionUUID); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - - Authentication authentication = null; - if (actionEndpointProperties.containsKey(ActionMgtConstants.AUTHN_TYPE_ATTRIBUTE)) { - Authentication.Type authnType = Authentication.Type.valueOf( - actionEndpointProperties.get(ActionMgtConstants.AUTHN_TYPE_ATTRIBUTE)); - switch (authnType) { - case BASIC: - authentication = new Authentication.BasicAuthBuilder( - actionEndpointProperties.get(Authentication.Property.USERNAME.getName()), - actionEndpointProperties.get(Authentication.Property.PASSWORD.getName())).build(); - break; - case BEARER: - authentication = new Authentication.BearerAuthBuilder( - actionEndpointProperties.get(Authentication.Property.ACCESS_TOKEN.getName())).build(); - break; - case API_KEY: - authentication = new Authentication.APIKeyAuthBuilder( - actionEndpointProperties.get(Authentication.Property.HEADER.getName()), - actionEndpointProperties.get(Authentication.Property.VALUE.getName())).build(); - break; - case NONE: - authentication = new Authentication.NoneAuthBuilder().build(); - break; - default: - break; - } - } else { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_NO_AUTHENTICATION_TYPE, null); - } - - return new EndpointConfig.EndpointConfigBuilder() - .uri(actionEndpointProperties.get(ActionMgtConstants.URI_ATTRIBUTE)) - .authentication(authentication).build(); - } catch (ActionMgtServerException | DataAccessException e) { - /** - * Throwing a runtime exception because {@link ActionMgtServerException} and {@link DataAccessException} - * is not handled in {@link org.wso2.carbon.database.utils.jdbc.RowMapper} of - * {@link NamedJdbcTemplate#executeQuery(String, org.wso2.carbon.database.utils.jdbc.RowMapper, - * org.wso2.carbon.database.utils.jdbc.NamedQueryFilter)} - */ - throw ActionManagementUtil.handleRuntimeException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_ENDPOINT_PROPERTIES.getMessage(), e); - } - } - - /** - * Get Action Endpoint properties Map. - * - * @param endpointUri Endpoint URI of the Action. - * @param authType Authentication Type of the Action. - * @param authProperties Authentication Properties of the Endpoint. - * @return Endpoint Properties Map. - */ - private Map getEndpointProperties(String endpointUri, String authType, - List authProperties) { - - Map endpointProperties = new HashMap<>(); - if (endpointUri != null) { - endpointProperties.put(ActionMgtConstants.URI_ATTRIBUTE, endpointUri); - } - if (authType != null) { - endpointProperties.put(ActionMgtConstants.AUTHN_TYPE_ATTRIBUTE, authType); - } - if (authProperties != null) { - for (AuthProperty property : authProperties) { - endpointProperties.put(property.getName(), property.getValue()); - } - } - - return endpointProperties; - } - - /** - * Update Action Endpoint properties. - * - * @param actionId UUID of the created Action. - * @param endpointProperties Endpoint Properties to be updated. - * @param tenantId Tenant ID. - */ - private void updateActionEndpointProperties(String actionId, Map endpointProperties, - Integer tenantId) throws ActionMgtException { + }); - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_ENDPOINT_PROPERTIES, - statement -> { - for (Map.Entry property : endpointProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, - property.getValue()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, - property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - statement.addBatch(); - } - }, null); - return null; - }); - } catch (TransactionException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); + return actionEndpointProperties; + } catch (DataAccessException e) { + throw new SQLException(ActionMgtConstants.ErrorMessages + .ERROR_WHILE_RETRIEVING_ACTION_PROPERTIES.getMessage(), e); } } @@ -606,48 +494,330 @@ private void updateBasicInfo(String actionType, String actionId, Action updating } /** - * Update the endpoint URI and authentication properties of an {@link Action} by given Action ID. + * Resolves the endpoint properties for an action, supporting both addAction and updateAction scenarios. + * This method ensures that authentication secrets are handled appropriately, and the URI is resolved + * based on the provided or existing endpoint configurations. + * When the updating action does not contain endpoint configuration, it uses the existing endpoint's properties. * * @param actionId Action ID. - * @param updatingAction Information to be updated. - * @param existingAction Existing Action information. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action endpoint. + * @param updatingAction Action to update. + * @param existingAction Existing Action. + * @return A map containing the resolved endpoint properties to be stored. + * @throws SecretManagementException If an error occurs while updating the authentication secrets. */ - private void updateEndpointUriAndAuthentication(String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { + private Map resolveEndpointProperties(String actionId, Action updatingAction, Action existingAction) + throws SecretManagementException { EndpointConfig updatingEndpoint = updatingAction.getEndpoint(); - if (updatingEndpoint == null) { - // No update needed if there's no endpoint configuration in the updating action. - return; + EndpointConfig existingEndpoint = existingAction != null ? existingAction.getEndpoint() : null; + + Map resolvedEndpointProperties = + resolveEndpointAuthenticationProperties(actionId, updatingEndpoint, existingEndpoint); + + if (updatingEndpoint != null && updatingEndpoint.getUri() != null) { + resolvedEndpointProperties.put(URI_PROPERTY, updatingEndpoint.getUri()); + } else if (existingEndpoint != null) { + resolvedEndpointProperties.put(URI_PROPERTY, existingEndpoint.getUri()); + } else { + throw new IllegalArgumentException("Both existing and input endpoint cannot be null."); } - Authentication updatingAuthentication = updatingEndpoint.getAuthentication(); - if (updatingAuthentication == null) { - // When updating action, updates the URI only. - updateActionEndpointProperties(actionId, getEndpointProperties(updatingEndpoint.getUri(), null, - null), tenantId); - return; + return resolvedEndpointProperties; + } + + /** + * Resolves the authentication properties for an endpoint, handling both addAction and updateAction scenarios. + * In addAction, the method generates new secrets based on the provided endpoint configuration. + * In updateAction, it deletes existing secrets and updates them with new properties as necessary. + * When the updating endpoint does not contain authentication, it uses the existing endpoint's properties. + * + * @param actionId Action ID. + * @param updatingEndpoint Endpoint configurations to be updated. + * @param existingEndpoint Existing Endpoint configurations. + * @return A map containing the resolved endpoint authentication properties to be stored. + * @throws SecretManagementException If an error occurs while updating the authentication secrets. + */ + private Map resolveEndpointAuthenticationProperties(String actionId, + EndpointConfig updatingEndpoint, + EndpointConfig existingEndpoint) + throws SecretManagementException { + + Authentication updatingAuthentication = updatingEndpoint != null ? updatingEndpoint.getAuthentication() : null; + Authentication existingAuthentication = existingEndpoint != null ? existingEndpoint.getAuthentication() : null; + + Map authentication = new HashMap<>(); + Authentication.Type resolvedAuthType; + List resolvedAuthProperties; + + if (updatingAuthentication != null) { + if (existingAuthentication != null) { + // Delete existing secrets. + actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, actionId); + } + // Add new secrets. + resolvedAuthProperties = actionSecretProcessor.encryptAssociatedSecrets(updatingAuthentication, actionId); + resolvedAuthType = updatingAuthentication.getType(); + } else if (existingAuthentication != null) { + // Use existing properties if updating authentication is not provided. + resolvedAuthType = existingAuthentication.getType(); + resolvedAuthProperties = existingAuthentication.getProperties(); + } else { + throw new IllegalArgumentException("Both existing and input authentication cannot be null."); + } + + authentication.put(AUTHN_TYPE_PROPERTY, resolvedAuthType.getName()); + resolvedAuthProperties.forEach(property -> authentication.put(property.getName(), property.getValue())); + + return authentication; + } + + /** + * Resolve the action type specific properties for creating or updating an action. + * + * @param actionType Action Type. + * @param actionId Action ID. + * @param inputAction A map containing the properties for the new or updated action. + * @param existingAction A map containing the existing properties. + * @param tenantId Tenant ID. + * @return A map containing the resolved action type specific properties. + * @throws CertificateMgtException If an error occurs while handling the certificate changes. + */ + private Map resolveActionTypeSpecificProperties(String actionType, String actionId, + Action inputAction, + Action existingAction, + Integer tenantId) throws CertificateMgtException { + + Map actionTypeSpecificProperties = new HashMap<>(); + switch (Action.ActionTypes.valueOf(actionType)) { + case PRE_UPDATE_PASSWORD: + PreUpdatePasswordAction inputPreUpdatePasswordAction = (PreUpdatePasswordAction) inputAction; + PreUpdatePasswordAction existingPreUpdatePasswordAction = (PreUpdatePasswordAction) existingAction; + + if (inputPreUpdatePasswordAction.getPasswordSharingFormat() != null) { + actionTypeSpecificProperties.put(PASSWORD_SHARING_FORMAT_PROPERTY, + inputPreUpdatePasswordAction.getPasswordSharingFormat().name()); + } else { + actionTypeSpecificProperties.put(PASSWORD_SHARING_FORMAT_PROPERTY, + existingPreUpdatePasswordAction.getPasswordSharingFormat().name()); + } + + // Handle certificate changes. + String certId = handleCertificateChanges(actionId, inputPreUpdatePasswordAction, + existingPreUpdatePasswordAction, tenantId); + if (StringUtils.isNotEmpty(certId)) { + actionTypeSpecificProperties.put(CERTIFICATE_ID_PROPERTY, certId); + } + + break; + case PRE_ISSUE_ACCESS_TOKEN: + default: + break; + } + + return actionTypeSpecificProperties; + } + + /** + * Deletes action type-specific properties associated with the provided action. + * + * @param actionType Type of the Action. + * @param action Action information. + * @param tenantId Tenant Id. + * @throws CertificateMgtException If an error occurs while deleting the certificate. + */ + private void deleteActionTypeSpecificProperties(String actionType, Action action, Integer tenantId) + throws CertificateMgtException { + + switch (Action.ActionTypes.valueOf(actionType)) { + case PRE_UPDATE_PASSWORD: + String certificateId = ((PreUpdatePasswordAction) action).getCertificate().getId(); + if (certificateId != null) { + deleteCertificate(certificateId, tenantId); + } + break; + case PRE_ISSUE_ACCESS_TOKEN: + default: + break; } + } - Authentication existingAuthentication = existingAction.getEndpoint().getAuthentication(); - if (updatingAuthentication.getType().equals(existingAuthentication.getType())) { - // When updating action, updates the URI and the authentication properties only. - if (updatingEndpoint.getUri() != null) { - updateActionEndpointProperties(actionId, getEndpointProperties(updatingEndpoint.getUri(), null, - null), tenantId); + /** + * Updates the certificate associated with an action based on the provided updating properties. + * If a new certificate is provided, it persists the certificate and returns its ID. + * If the existing certificate is being removed (empty value), it deletes the certificate and returns null. + * If the existing certificate is being updated, it updates the certificate and returns its existing ID. + * + * @param actionId Action ID. + * @param inputAction A map containing the properties to update, including the certificate. + * @param existingAction A map containing the existing properties, including the current certificate ID. + * @param tenantId Tenant ID. + * @return The updated certificate ID, or null if the certificate was deleted. + * @throws CertificateMgtException If an error occurs while updating the certificate. + */ + private String handleCertificateChanges(String actionId, PreUpdatePasswordAction inputAction, + PreUpdatePasswordAction existingAction, Integer tenantId) + throws CertificateMgtException { + + String updatingCertificate = inputAction.getCertificate() != null ? + inputAction.getCertificate().getCertificateContent() : null; + String updatingCertificateId = existingAction.getCertificate() != null + ? existingAction.getCertificate().getId() : null; + + if (updatingCertificate != null) { + if (updatingCertificateId == null) { + // Add the new certificate. + updatingCertificateId = addCertificate(actionId, updatingCertificate, tenantId); + } else if (updatingCertificate.isEmpty()) { + // Delete the existing certificate. + deleteCertificate(updatingCertificateId, tenantId); + updatingCertificateId = null; + } else { + // Update the existing certificate. + updateCertificate(updatingCertificateId, updatingCertificate, tenantId); } - updateActionEndpointAuthProperties(actionId, updatingAuthentication, tenantId); - return; } - // When updating action, updates the entire endpoint. - updatingEndpoint = StringUtils.isNotEmpty(updatingEndpoint.getUri()) ? updatingEndpoint : - new EndpointConfig.EndpointConfigBuilder() - .uri(existingAction.getEndpoint().getUri()) - .authentication(updatingAuthentication) + return updatingCertificateId; + } + + /** + * Add the certificate in the database. + * + * @param actionId UUID of the created Action. + * @param certificateContent Certificate to be added. + * @param tenantId Tenant ID. + * @throws CertificateMgtException If an error occurs while adding the certificate. + * @returns Certificate ID. + */ + private String addCertificate(String actionId, String certificateContent, Integer tenantId) + throws CertificateMgtException { + + Certificate certificate = new Certificate.Builder() + .name("ACTIONS:" + actionId) + .certificateContent(certificateContent) + .build(); + return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .addCertificate(certificate, IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Get the certificate content by certificate ID. + * + * @param certificateId Certificate ID. + * @param tenantId Tenant ID. + * @return Certificate information. + * @throws CertificateMgtException If an error occurs while retrieving the certificate from the database. + */ + private Certificate getCertificate(String certificateId, Integer tenantId) throws CertificateMgtException { + + return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .getCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Update the certificate by certificate ID. + * + * @param certificateId Certificate ID. + * @param updatingCertificate Certificate to be updated. + * @param tenantId Tenant ID. + * @throws CertificateMgtException If an error occurs while updating the certificate in the database. + */ + private void updateCertificate(String certificateId, String updatingCertificate, Integer tenantId) + throws CertificateMgtException { + + ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .updateCertificateContent(certificateId, updatingCertificate, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Delete the certificate by certificate ID. + * + * @param certificateId Certificate ID. + * @param tenantId Tenant ID. + * @throws CertificateMgtException If an error occurs while deleting the certificate in the database. + */ + private void deleteCertificate(String certificateId, Integer tenantId) throws CertificateMgtException { + + ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .deleteCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Build the Action Response Object according to the actionType. + * + * @param actionType Action Type. + * @param action Action basic information. + * @param actionProperties Action Properties. + * @param tenantId Tenant Id. + * @return Action Response. + * @throws ActionMgtRuntimeException If an error occurs while retrieving the certificate. + */ + private Action buildActionResponse(String actionType, Action action, Map actionProperties, + Integer tenantId) { + + Action.ActionResponseBuilder actionResponseBuilder; + try { + switch (Action.ActionTypes.valueOf(actionType)) { + case PRE_UPDATE_PASSWORD: + actionResponseBuilder = new PreUpdatePasswordAction.ResponseBuilder() + .certificate(getCertificate(actionProperties.get(CERTIFICATE_ID_PROPERTY), tenantId)) + .passwordSharingFormat(PreUpdatePasswordAction.PasswordFormat.valueOf( + actionProperties.get(PASSWORD_SHARING_FORMAT_PROPERTY))); + break; + case PRE_ISSUE_ACCESS_TOKEN: + default: + actionResponseBuilder = new Action.ActionResponseBuilder(); + break; + } + + Authentication authentication = null; + Authentication.Type authnType = + Authentication.Type.valueOf(actionProperties.get(ActionMgtConstants.AUTHN_TYPE_PROPERTY)); + switch (authnType) { + case BASIC: + authentication = new Authentication.BasicAuthBuilder( + actionProperties.get(Authentication.Property.USERNAME.getName()), + actionProperties.get(Authentication.Property.PASSWORD.getName())).build(); + break; + case BEARER: + authentication = new Authentication.BearerAuthBuilder( + actionProperties.get(Authentication.Property.ACCESS_TOKEN.getName())).build(); + break; + case API_KEY: + authentication = new Authentication.APIKeyAuthBuilder( + actionProperties.get(Authentication.Property.HEADER.getName()), + actionProperties.get(Authentication.Property.VALUE.getName())).build(); + break; + case NONE: + authentication = new Authentication.NoneAuthBuilder().build(); + break; + default: + break; + } + + EndpointConfig endpointConfig = new EndpointConfig.EndpointConfigBuilder() + .uri(actionProperties.get(ActionMgtConstants.URI_PROPERTY)) + .authentication(authentication) .build(); - updateActionEndpoint(actionId, updatingEndpoint, existingAuthentication, tenantId); + + return actionResponseBuilder + .id(action.getId()) + .type(Action.ActionTypes.valueOf(actionType)) + .name(action.getName()) + .description(action.getDescription()) + .status(action.getStatus()) + .endpoint(endpointConfig) + .build(); + } catch (CertificateMgtException e) { + /** + * Throwing a runtime exception because {@link CertificateMgtException} is not handled in + * {@link org.wso2.carbon.database.utils.jdbc.RowMapper} of {@link NamedJdbcTemplate#executeQuery(String, + * org.wso2.carbon.database.utils.jdbc.RowMapper,org.wso2.carbon.database.utils.jdbc.NamedQueryFilter)} + * in {@link #getActionsByActionType(String, Integer)} + */ + throw ActionManagementUtil.handleRuntimeException( + ActionMgtConstants.ErrorMessages.ERROR_WHILE_BUILDING_ACTION_RESPONSE.getMessage(), e); + } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java index 1ef2ff2d3ca3..bfb0f5f613d3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java @@ -18,6 +18,7 @@ package org.wso2.carbon.identity.action.management.dao.impl; +//import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -27,8 +28,6 @@ import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; import java.util.List; import java.util.Map; @@ -157,23 +156,6 @@ public Action getActionByActionId(String actionType, String actionId, Integer te return action; } - @Override - public Action updateActionEndpointAuthProperties(String actionType, String actionId, Authentication authentication, - int tenantId) throws ActionMgtException { - - return actionManagementDAO.updateActionEndpointAuthProperties(actionType, actionId, authentication, tenantId); - } - - @Override - public Action updateActionEndpoint(String actionType, String actionId, EndpointConfig endpoint, - Authentication currentAuthentication, int tenantId) - throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.updateActionEndpoint(actionType, actionId, endpoint, currentAuthentication, - tenantId); - } - private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheKey cacheKey, int tenantId) { if (LOG.isDebugEnabled()) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index 44fe7f894eac..ff34ec5b3259 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -30,6 +30,7 @@ import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.identity.action.management.ActionManagementService; import org.wso2.carbon.identity.action.management.ActionManagementServiceImpl; +import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -78,11 +79,13 @@ protected void deactivate(ComponentContext context) { private void setSecretManager(SecretManager secretManager) { ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + LOG.debug("SecretManager set in ActionMgtServiceComponentHolder bundle."); } private void unsetSecretManager(SecretManager secretManager) { ActionMgtServiceComponentHolder.getInstance().setSecretManager(null); + LOG.debug("SecretManager unset in ActionMgtServiceComponentHolder bundle."); } @Reference( @@ -95,10 +98,31 @@ private void unsetSecretManager(SecretManager secretManager) { private void setSecretResolveManager(SecretResolveManager secretResolveManager) { ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(secretResolveManager); + LOG.debug("SecretResolveManager set in ActionMgtServiceComponentHolder bundle."); } private void unsetSecretResolveManager(SecretResolveManager secretResolveManager) { ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(null); + LOG.debug("SecretResolveManager unset in ActionMgtServiceComponentHolder bundle."); + } + + @Reference( + name = "org.wso2.carbon.identity.certificate.management.service.CertificateManagementService", + service = CertificateManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetCertificateManagementService" + ) + private void setCertificateManagementService(CertificateManagementService certificateManagementService) { + + ActionMgtServiceComponentHolder.getInstance().setCertificateManagementService(certificateManagementService); + LOG.debug("CertificateManagementService set in ActionMgtServiceComponentHolder bundle."); + } + + private void unsetCertificateManagementService(CertificateManagementService certificateManagementService) { + + ActionMgtServiceComponentHolder.getInstance().setCertificateManagementService(null); + LOG.debug("CertificateManagementService unset in ActionMgtServiceComponentHolder bundle."); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java index 5866841fdbaa..d921157e0af1 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java @@ -18,6 +18,7 @@ package org.wso2.carbon.identity.action.management.internal; +import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -28,6 +29,7 @@ public class ActionMgtServiceComponentHolder { private SecretManager secretManager; private SecretResolveManager secretResolveManager; + private CertificateManagementService certificateMgtService; public static final ActionMgtServiceComponentHolder INSTANCE = new ActionMgtServiceComponentHolder(); @@ -84,4 +86,24 @@ public void setSecretResolveManager(SecretResolveManager secretResolveManager) { this.secretResolveManager = secretResolveManager; } + + /** + * Get the CertificateManagementService. + * + * @return CertificateManagementService instance. + */ + public CertificateManagementService getCertificateManagementService() { + + return certificateMgtService; + } + + /** + * Set the CertificateManagementService. + * + * @param certificateMgtService CertificateManagementService instance. + */ + public void setCertificateManagementService(CertificateManagementService certificateMgtService) { + + this.certificateMgtService = certificateMgtService; + } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java index 99fa95aee93d..ff9783787a7c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java @@ -147,7 +147,6 @@ public static Status fromValue(String value) { } } - private String id; private ActionTypes type; private String name; @@ -205,11 +204,6 @@ public EndpointConfig getEndpoint() { return endpointConfig; } - public void setEndpoint(EndpointConfig endpointConfig) { - - this.endpointConfig = endpointConfig; - } - /** * ActionResponseBuilder. */ diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java index 78dcdee21ef8..7bfbc43ea455 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java @@ -18,9 +18,7 @@ package org.wso2.carbon.identity.action.management.model; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; - -import java.util.Map; +import org.wso2.carbon.identity.certificate.management.model.Certificate; /** * PreUpdatePasswordAction. @@ -38,7 +36,7 @@ public enum PasswordFormat { } private final PasswordFormat passwordSharingFormat; - private final String certificate; + private final Certificate certificate; public PreUpdatePasswordAction(ResponseBuilder responseBuilder) { @@ -59,38 +57,18 @@ public PasswordFormat getPasswordSharingFormat() { return passwordSharingFormat; } - public String getCertificate() { + public Certificate getCertificate() { return certificate; } - /** - * Retrieves a map of property names and values from the endpoint configuration, along with the password - * sharing format and certificate if they are set. - * - * @return A map containing the endpoint properties, password sharing format, and certificate. - */ - @Override - public Map getPropertiesMap() { - - Map propertiesMap = super.getPropertiesMap(); - if (getPasswordSharingFormat() != null) { - propertiesMap.put(ActionMgtConstants.PASSWORD_SHARING_FORMAT_PROPERTY, getPasswordSharingFormat().name()); - } - if (getCertificate() != null) { - propertiesMap.put(ActionMgtConstants.CERTIFICATE_PROPERTY, getCertificate()); - } - - return propertiesMap; - } - /** * Response Builder for PreUpdatePasswordAction. */ public static class ResponseBuilder extends ActionResponseBuilder { private PasswordFormat passwordSharingFormat; - private String certificate; + private Certificate certificate; public ResponseBuilder() { } @@ -101,7 +79,7 @@ public ResponseBuilder passwordSharingFormat(PasswordFormat passwordSharingForma return this; } - public ResponseBuilder certificate(String certificate) { + public ResponseBuilder certificate(Certificate certificate) { this.certificate = certificate; return this; @@ -149,30 +127,6 @@ public ResponseBuilder endpoint(EndpointConfig endpoint) { return this; } - /** - * Sets properties from a given map to the relevant attributes in the builder. - * Based on the provided properties, this method configures the {@link EndpointConfig} - * with the URI and the {@link Authentication} object. - * - * @param propertiesMap A map containing the endpoint URI, authentication type, and authentication properties. - * @return The current {@link ActionResponseBuilder} instance with the configured attributes. - */ - @Override - public ActionResponseBuilder setPropertiesToAttributes(Map propertiesMap) { - - if (propertiesMap.isEmpty()) { - return this; - } - - // Set the endpoint properties to the common attributes. - super.setPropertiesToAttributes(propertiesMap); - // Set other properties to the specific attributes of PRE_UPDATE_PASSWORD action type. - - return this.passwordSharingFormat(PasswordFormat - .valueOf(propertiesMap.get(ActionMgtConstants.PASSWORD_SHARING_FORMAT_PROPERTY))) - .certificate(propertiesMap.get(ActionMgtConstants.CERTIFICATE_PROPERTY)); - } - @Override public PreUpdatePasswordAction build() { @@ -186,7 +140,7 @@ public PreUpdatePasswordAction build() { public static class RequestBuilder extends ActionRequestBuilder { private PasswordFormat passwordSharingFormat; - private String certificate; + private Certificate certificate; public RequestBuilder() { } @@ -197,7 +151,7 @@ public RequestBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat return this; } - public RequestBuilder certificate(String certificate) { + public RequestBuilder certificate(Certificate certificate) { this.certificate = certificate; return this; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java index 949efc721833..6b0300fc7f41 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java @@ -281,36 +281,6 @@ public void testGetActionsCountPerType() throws ActionMgtException { } @Test(priority = 12) - public void testUpdateEndpointConfigWithSameAuthenticationType() - throws ActionMgtException, SecretManagementException { - - Authentication authentication = buildMockAPIKeyAuthentication("newheader", "newvalue"); - Action result = serviceImpl.updateActionEndpointAuthentication( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), authentication, tenantDomain); - Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(authentication.getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), - secretProperties.get(Authentication.Property.VALUE.getName())); - } - - @Test(priority = 13) - public void testUpdateEndpointConfigWithDifferentAuthenticationType() - throws ActionMgtException, SecretManagementException { - - Authentication authentication = buildMockBearerAuthentication(ACCESS_TOKEN); - Action result = serviceImpl.updateActionEndpointAuthentication( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), authentication, tenantDomain); - Assert.assertEquals(Authentication.Type.BEARER, result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), - secretProperties.get(Authentication.Property.ACCESS_TOKEN.getName())); - } - - @Test(priority = 14) public void testDeleteAction() throws ActionMgtException { serviceImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index 2c3a5237ee5a..5ca08718eebe 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -37,6 +37,7 @@ import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; +import java.util.List; import java.util.Map; import java.util.UUID; @@ -117,11 +118,12 @@ public void testAddActionWithoutName() throws ActionMgtException { this.action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), action, TENANT_ID); } - @Test(priority = 3) + @Test(priority = 3, dependsOnMethods = "testAddAction") public void testGetActionsByActionType() throws ActionMgtException { - Assert.assertEquals(1, daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, TENANT_ID).size()); - Action result = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, TENANT_ID).get(0); + List actionList = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, TENANT_ID); + Assert.assertEquals(1, actionList.size()); + Action result = actionList.get(0); Assert.assertEquals(action.getId(), result.getId()); Assert.assertEquals(action.getName(), result.getName()); Assert.assertEquals(action.getDescription(), result.getDescription()); @@ -239,21 +241,6 @@ public void testUpdateActionWithNameAndDescription() throws ActionMgtException { } @Test(priority = 10) - public void testUpdateActionEndpointAuthSecretProperties() throws ActionMgtException { - - Authentication authentication = buildMockBasicAuthentication("newadmin", "newadmin"); - Action result = daoImpl.updateActionEndpointAuthProperties(PRE_ISSUE_ACCESS_TOKEN, action.getId(), - authentication, TENANT_ID); - Assert.assertEquals(Authentication.Type.BASIC, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue()); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue()); - } - - @Test(priority = 11) public void testUpdateActionWithoutEndpointUri() throws ActionMgtException { // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if Uri is null. @@ -274,7 +261,7 @@ public void testUpdateActionWithoutEndpointUri() throws ActionMgtException { result.getEndpoint().getAuthentication().getType()); } - @Test(priority = 12) + @Test(priority = 11) public void testUpdateActionWithAuthType() throws ActionMgtException { Action updatingAction = buildMockAction( @@ -294,7 +281,7 @@ public void testUpdateActionWithAuthType() throws ActionMgtException { action = result; } - @Test(priority = 13) + @Test(priority = 12) public void testUpdateActionWithUri() throws ActionMgtException { // TODO: 'Name','AuthenticationType' and 'AuthProperties' are required attributes. Thus, DAO layer should throw @@ -317,7 +304,7 @@ public void testUpdateActionWithUri() throws ActionMgtException { action = result; } - @Test(priority = 14) + @Test(priority = 13) public void testUpdateActionWithAuthTypeWithoutUri() throws ActionMgtException { // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if uri is null. @@ -338,28 +325,7 @@ public void testUpdateActionWithAuthTypeWithoutUri() throws ActionMgtException { result.getEndpoint().getAuthentication().getType()); } - @Test(priority = 15) - public void testUpdateActionEndpointAuthNonSecretProperties() throws ActionMgtException { - - Action sampleAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - "https://sample.com", - buildMockAPIKeyAuthentication("header", "value")); - Action updatingAction = daoImpl.updateAction( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), sampleAction, action, TENANT_ID); - Authentication authentication = buildMockAPIKeyAuthentication("updatingheader", "updatingvalue"); - Action result = daoImpl.updateActionEndpointAuthProperties(PRE_ISSUE_ACCESS_TOKEN, updatingAction.getId(), - authentication, TENANT_ID); - Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(authentication.getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue()); - } - - @Test(priority = 16) + @Test(priority = 14) public void testDeactivateAction() throws ActionMgtException { Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); @@ -367,27 +333,14 @@ public void testDeactivateAction() throws ActionMgtException { Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); } - @Test(priority = 17) + @Test(priority = 15) public void testActivateAction() throws ActionMgtException { Action result = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); } - @Test(priority = 18) - public void testUpdateActionEndpoint() throws ActionMgtException { - - EndpointConfig endpointConfig = buildMockEndpointConfig("https://template.com", - buildMockBearerAuthentication("c7fce95f-3f5b-4cda-8bb1-4cb7b3990f83")); - Action result = daoImpl.updateActionEndpoint( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), endpointConfig, action.getEndpoint() - .getAuthentication(), TENANT_ID); - Assert.assertNotEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(Authentication.Type.BEARER.getName(), - result.getEndpoint().getAuthentication().getType().getName()); - } - - @Test(priority = 19) + @Test(priority = 16) public void testGetActionsCountPerType() throws ActionMgtException { Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); From 891c883e66632aa743e996c06da37a1e9d3fc0f2 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Sun, 10 Nov 2024 20:30:29 +0530 Subject: [PATCH 03/34] Improve unit tests for DAO --- .../pom.xml | 4 +- .../constant/ActionMgtConstants.java | 13 +- .../dao/impl/ActionManagementDAOImpl.java | 214 ++++---- .../exception/ActionMgtClientException.java | 5 + .../management/util/ActionManagementUtil.java | 12 + .../dao/ActionManagementDAOImplTest.java | 288 +++++----- ...tePasswordActionManagementDAOImplTest.java | 497 ++++++++++++++++++ .../action/management/util/TestUtil.java | 100 ++++ .../src/test/resources/testng.xml | 1 + 9 files changed, 890 insertions(+), 244 deletions(-) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index 81e2620a3986..8f491781611a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -183,14 +183,14 @@ - 0.70 + 0.78 COMPLEXITY COVEREDRATIO - 0.60 + 0.68 diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index bd03dcd0ebda..e2fa57c31ec9 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -55,6 +55,7 @@ public enum ErrorMessages { "%s is empty."), ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", "%s is invalid."), + ERROR_INVALID_ACTION_CERTIFICATE("60006", "Invalid request.", "Provided certificate is invalid."), // Server errors. ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", @@ -67,7 +68,7 @@ public enum ErrorMessages { ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE("65004", "Error while retrieving Actions by Action Type", "Error while retrieving Actions by Action Type from the system."), - ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES("65005", + ERROR_WHILE_UPDATING_ACTION_PROPERTIES("65005", "Error while updating Action Endpoint properties", "Error while updating Action Endpoint properties in the system."), ERROR_WHILE_UPDATING_ACTION("65006", "Error while updating Action.", @@ -89,7 +90,15 @@ public enum ErrorMessages { ERROR_WHILE_UPDATING_ACTION_BASIC_INFO("65013", "Error while updating basic Action information", "Error while updating basic Action information in the system."), ERROR_WHILE_BUILDING_ACTION_RESPONSE("65014", "Error while building Action response.", - "Error while building Action response object."),; + "Error while building Action response object."), + ERROR_WHILE_ADDING_ACTION_CERTIFICATE("65015", "Error while adding action certificate.", + "Error while persisting certificate in the system."), + ERROR_WHILE_RETRIEVING_ACTION_CERTIFICATE("65016", "Error while retrieving action certificate.", + "Error while retrieving certificate from the system."), + ERROR_WHILE_UPDATING_ACTION_CERTIFICATE("65016", "Error while updating action certificate.", + "Error while updating certificate in the system."), + ERROR_WHILE_DELETING_ACTION_CERTIFICATE("65016", "Error while deleting action certificate.", + "Error while deleting certificate from the system."); private final String code; private final String message; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index cff0b1044e4c..b9b55f62ed07 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -28,9 +28,9 @@ import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.constant.ActionMgtSQLConstants; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtRuntimeException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; @@ -38,6 +38,7 @@ import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtClientException; import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtException; import org.wso2.carbon.identity.certificate.management.model.Certificate; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; @@ -94,6 +95,9 @@ public Action addAction(String actionType, String actionId, Action action, Integ return getActionByActionId(actionType, actionId, tenantId); } catch (TransactionException e) { + if (e.getCause() instanceof ActionMgtClientException) { + throw (ActionMgtClientException) e.getCause(); + } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Error while creating the Action of Action Type: %s in Tenant Domain: %s." + " Rolling back created action information and deleting added secrets.", actionType, @@ -160,6 +164,9 @@ public Action updateAction(String actionType, String actionId, Action updatingAc return getActionByActionId(actionType, actionId, tenantId); } catch (TransactionException e) { + if (e.getCause() instanceof ActionMgtClientException) { + throw (ActionMgtClientException) e.getCause(); + } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Error while updating the Action of Action Type: %s and Action ID: %s in" + " Tenant Domain: %s. Rolling back updated action information.", actionType, actionId, @@ -261,17 +268,29 @@ public Action getActionByActionId(String actionType, String actionId, Integer te * @param actionId UUID of the created Action. * @param action Properties of the Action. * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while adding action properties to the database. + * @throws ActionMgtException If an error occurs while adding action properties to the database. */ private void addActionProperties(String actionType, String actionId, Action action, Integer tenantId) throws ActionMgtException { try { - Map actionProperties = resolveEndpointProperties(actionId, action, null); - actionProperties.putAll(resolveActionTypeSpecificProperties(actionType, actionId, action, null, tenantId)); + Map actionProperties = + resolveActionTypeSpecificProperties(actionType, actionId, action, null, tenantId); + + EndpointConfig endpoint = action.getEndpoint(); + // Encrypt the authentication secrets. + List authProperties = + actionSecretProcessor.encryptAssociatedSecrets(endpoint.getAuthentication(), actionId); + + actionProperties.put(URI_PROPERTY, endpoint.getUri()); + actionProperties.put(AUTHN_TYPE_PROPERTY, endpoint.getAuthentication().getType().name()); + authProperties.forEach(authProperty -> actionProperties.put(authProperty.getName(), + authProperty.getValue())); addActionPropertiesToDB(actionId, actionProperties, tenantId); - } catch (CertificateMgtException | SecretManagementException | TransactionException e) { + } catch (ActionMgtClientException e) { + throw e; + } catch (ActionMgtException | SecretManagementException | TransactionException e) { throw ActionManagementUtil.handleServerException( ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION_PROPERTIES, e); } @@ -313,19 +332,23 @@ private void addActionPropertiesToDB(String actionId, Map action * @param updatingAction Information to be updated. * @param existingAction Existing Action information. * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while updating the Action properties. - * @throws CertificateMgtException If an error occurs while updating the Action certificate. - * @throws SecretManagementException If an error occurs while updating the Authentication secrets. + * @throws ActionMgtException If an error occurs while updating the Action properties. */ private void updateActionProperties(String actionType, String actionId, Action updatingAction, - Action existingAction, Integer tenantId) - throws ActionMgtServerException, CertificateMgtException, SecretManagementException { + Action existingAction, Integer tenantId) throws ActionMgtException { - Map actionProperties = resolveEndpointProperties(actionId, updatingAction, existingAction); - actionProperties.putAll(resolveActionTypeSpecificProperties(actionType, actionId, updatingAction, - existingAction, tenantId)); - - updateActionPropertiesInDB(actionId, actionProperties, tenantId); + try { + Map actionProperties = resolveEndpointProperties(actionId, updatingAction, existingAction); + actionProperties.putAll(resolveActionTypeSpecificProperties(actionType, actionId, updatingAction, + existingAction, tenantId)); + + updateActionPropertiesInDB(actionId, actionProperties, tenantId); + } catch (ActionMgtClientException e) { + throw e; + } catch (ActionMgtException | SecretManagementException | TransactionException e) { + throw ActionManagementUtil.handleServerException( + ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_PROPERTIES, e); + } } /** @@ -334,33 +357,23 @@ private void updateActionProperties(String actionType, String actionId, Action u * @param actionId UUID of the created Action. * @param updatingProperties Action properties to be updated. * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while updating the Action properties. + * @throws TransactionException If an error occurs while updating the Action properties. */ private void updateActionPropertiesInDB(String actionId, Map updatingProperties, - Integer tenantId) throws ActionMgtServerException { + Integer tenantId) throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTIES, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + jdbcTemplate.withTransaction(template -> { + template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTIES, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }); - // Add updated action properties. - addActionPropertiesToDB(actionId, updatingProperties, tenantId); - return null; - }); - } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action properties of Action ID: %s in " + - "Tenant Domain: %s. Rolling back updated action endpoint authentication.", - actionId, IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); - } + // Add updated action properties. + addActionPropertiesToDB(actionId, updatingProperties, tenantId); + return null; + }); } /** @@ -465,10 +478,10 @@ private Action changeActionStatus(String actionType, String actionId, String sta * @param updatingAction Information to be updated. * @param existingAction Existing Action information. * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while updating the Action basic information. + * @throws ActionMgtException If an error occurs while updating the Action basic information. */ private void updateBasicInfo(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtServerException { + Integer tenantId) throws ActionMgtException { if (updatingAction.getName() == null && updatingAction.getDescription() == null) { return; @@ -509,17 +522,15 @@ private Map resolveEndpointProperties(String actionId, Action up throws SecretManagementException { EndpointConfig updatingEndpoint = updatingAction.getEndpoint(); - EndpointConfig existingEndpoint = existingAction != null ? existingAction.getEndpoint() : null; + EndpointConfig existingEndpoint = existingAction.getEndpoint(); Map resolvedEndpointProperties = resolveEndpointAuthenticationProperties(actionId, updatingEndpoint, existingEndpoint); if (updatingEndpoint != null && updatingEndpoint.getUri() != null) { resolvedEndpointProperties.put(URI_PROPERTY, updatingEndpoint.getUri()); - } else if (existingEndpoint != null) { - resolvedEndpointProperties.put(URI_PROPERTY, existingEndpoint.getUri()); } else { - throw new IllegalArgumentException("Both existing and input endpoint cannot be null."); + resolvedEndpointProperties.put(URI_PROPERTY, existingEndpoint.getUri()); } return resolvedEndpointProperties; @@ -543,26 +554,18 @@ private Map resolveEndpointAuthenticationProperties(String actio throws SecretManagementException { Authentication updatingAuthentication = updatingEndpoint != null ? updatingEndpoint.getAuthentication() : null; - Authentication existingAuthentication = existingEndpoint != null ? existingEndpoint.getAuthentication() : null; + Authentication existingAuthentication = existingEndpoint.getAuthentication(); Map authentication = new HashMap<>(); - Authentication.Type resolvedAuthType; - List resolvedAuthProperties; + Authentication.Type resolvedAuthType = existingAuthentication.getType();; + List resolvedAuthProperties = existingAuthentication.getProperties();; if (updatingAuthentication != null) { - if (existingAuthentication != null) { - // Delete existing secrets. - actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, actionId); - } + // Delete existing secrets. + actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, actionId); // Add new secrets. resolvedAuthProperties = actionSecretProcessor.encryptAssociatedSecrets(updatingAuthentication, actionId); resolvedAuthType = updatingAuthentication.getType(); - } else if (existingAuthentication != null) { - // Use existing properties if updating authentication is not provided. - resolvedAuthType = existingAuthentication.getType(); - resolvedAuthProperties = existingAuthentication.getProperties(); - } else { - throw new IllegalArgumentException("Both existing and input authentication cannot be null."); } authentication.put(AUTHN_TYPE_PROPERTY, resolvedAuthType.getName()); @@ -580,12 +583,12 @@ private Map resolveEndpointAuthenticationProperties(String actio * @param existingAction A map containing the existing properties. * @param tenantId Tenant ID. * @return A map containing the resolved action type specific properties. - * @throws CertificateMgtException If an error occurs while handling the certificate changes. + * @throws ActionMgtException If an error occurs while handling action type specific properties. */ private Map resolveActionTypeSpecificProperties(String actionType, String actionId, Action inputAction, Action existingAction, - Integer tenantId) throws CertificateMgtException { + Integer tenantId) throws ActionMgtException { Map actionTypeSpecificProperties = new HashMap<>(); switch (Action.ActionTypes.valueOf(actionType)) { @@ -623,16 +626,16 @@ private Map resolveActionTypeSpecificProperties(String actionTyp * @param actionType Type of the Action. * @param action Action information. * @param tenantId Tenant Id. - * @throws CertificateMgtException If an error occurs while deleting the certificate. + * @throws ActionMgtException If an error occurs while deleting action type specific properties. */ private void deleteActionTypeSpecificProperties(String actionType, Action action, Integer tenantId) - throws CertificateMgtException { + throws ActionMgtException { switch (Action.ActionTypes.valueOf(actionType)) { case PRE_UPDATE_PASSWORD: - String certificateId = ((PreUpdatePasswordAction) action).getCertificate().getId(); - if (certificateId != null) { - deleteCertificate(certificateId, tenantId); + Certificate certificate = ((PreUpdatePasswordAction) action).getCertificate(); + if (certificate != null) { + deleteCertificate(certificate.getId(), tenantId); } break; case PRE_ISSUE_ACCESS_TOKEN: @@ -652,15 +655,15 @@ private void deleteActionTypeSpecificProperties(String actionType, Action action * @param existingAction A map containing the existing properties, including the current certificate ID. * @param tenantId Tenant ID. * @return The updated certificate ID, or null if the certificate was deleted. - * @throws CertificateMgtException If an error occurs while updating the certificate. + * @throws ActionMgtException If an error occurs while updating the certificate. */ private String handleCertificateChanges(String actionId, PreUpdatePasswordAction inputAction, PreUpdatePasswordAction existingAction, Integer tenantId) - throws CertificateMgtException { + throws ActionMgtException { String updatingCertificate = inputAction.getCertificate() != null ? inputAction.getCertificate().getCertificateContent() : null; - String updatingCertificateId = existingAction.getCertificate() != null + String updatingCertificateId = existingAction != null && existingAction.getCertificate() != null ? existingAction.getCertificate().getId() : null; if (updatingCertificate != null) { @@ -686,18 +689,25 @@ private String handleCertificateChanges(String actionId, PreUpdatePasswordAction * @param actionId UUID of the created Action. * @param certificateContent Certificate to be added. * @param tenantId Tenant ID. - * @throws CertificateMgtException If an error occurs while adding the certificate. + * @throws ActionMgtException If an error occurs while adding the certificate. * @returns Certificate ID. */ private String addCertificate(String actionId, String certificateContent, Integer tenantId) - throws CertificateMgtException { - - Certificate certificate = new Certificate.Builder() - .name("ACTIONS:" + actionId) - .certificateContent(certificateContent) - .build(); - return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .addCertificate(certificate, IdentityTenantUtil.getTenantDomain(tenantId)); + throws ActionMgtException { + try { + Certificate certificate = new Certificate.Builder() + .name("ACTIONS:" + actionId) + .certificateContent(certificateContent) + .build(); + return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .addCertificate(certificate, IdentityTenantUtil.getTenantDomain(tenantId)); + } catch (CertificateMgtClientException e) { + throw ActionManagementUtil.handleClientException( + ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE, e); + } catch (CertificateMgtException e) { + throw ActionManagementUtil.handleServerException( + ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION_CERTIFICATE, e); + } } /** @@ -706,12 +716,18 @@ private String addCertificate(String actionId, String certificateContent, Intege * @param certificateId Certificate ID. * @param tenantId Tenant ID. * @return Certificate information. - * @throws CertificateMgtException If an error occurs while retrieving the certificate from the database. + * @throws ActionMgtException If an error occurs while retrieving the certificate from the database. */ - private Certificate getCertificate(String certificateId, Integer tenantId) throws CertificateMgtException { + private Certificate getCertificate(String certificateId, Integer tenantId) + throws ActionMgtException { - return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .getCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); + try { + return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .getCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); + } catch (CertificateMgtException e) { + throw ActionManagementUtil.handleServerException( + ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_CERTIFICATE, e); + } } /** @@ -720,14 +736,22 @@ private Certificate getCertificate(String certificateId, Integer tenantId) throw * @param certificateId Certificate ID. * @param updatingCertificate Certificate to be updated. * @param tenantId Tenant ID. - * @throws CertificateMgtException If an error occurs while updating the certificate in the database. + * @throws ActionMgtException If an error occurs while updating the certificate in the database. */ private void updateCertificate(String certificateId, String updatingCertificate, Integer tenantId) - throws CertificateMgtException { + throws ActionMgtException { - ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .updateCertificateContent(certificateId, updatingCertificate, - IdentityTenantUtil.getTenantDomain(tenantId)); + try { + ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .updateCertificateContent(certificateId, updatingCertificate, + IdentityTenantUtil.getTenantDomain(tenantId)); + } catch (CertificateMgtClientException e) { + throw ActionManagementUtil.handleClientException( + ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE, e); + } catch (CertificateMgtException e) { + throw ActionManagementUtil.handleServerException( + ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_CERTIFICATE, e); + } } /** @@ -735,12 +759,17 @@ private void updateCertificate(String certificateId, String updatingCertificate, * * @param certificateId Certificate ID. * @param tenantId Tenant ID. - * @throws CertificateMgtException If an error occurs while deleting the certificate in the database. + * @throws ActionMgtException If an error occurs while deleting the certificate in the database. */ - private void deleteCertificate(String certificateId, Integer tenantId) throws CertificateMgtException { + private void deleteCertificate(String certificateId, Integer tenantId) throws ActionMgtException { - ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .deleteCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); + try { + ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() + .deleteCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); + } catch (CertificateMgtException e) { + throw ActionManagementUtil.handleServerException( + ActionMgtConstants.ErrorMessages.ERROR_WHILE_DELETING_ACTION_CERTIFICATE, e); + } } /** @@ -760,8 +789,11 @@ private Action buildActionResponse(String actionType, Action action, Map identityTenantUtil; - private static final String PRE_ISSUE_ACCESS_TOKEN = "PRE_ISSUE_ACCESS_TOKEN"; - private static final int TENANT_ID = 2; - private Action action; + private Action createdAction; @BeforeClass public void setUpClass() { @@ -89,112 +91,117 @@ public void tearDown() { @Test(priority = 1) public void testAddAction() throws ActionMgtException { - String id = String.valueOf(UUID.randomUUID()); - Action creatingAction = buildMockAction( + Action creatingAction = TestUtil.buildMockAction( "PreIssueAccessToken", "To configure PreIssueAccessToken", "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, id, creatingAction, TENANT_ID); - Assert.assertEquals(id, action.getId()); - Assert.assertEquals(creatingAction.getName(), action.getName()); - Assert.assertEquals(creatingAction.getDescription(), action.getDescription()); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN, action.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), action.getEndpoint().getUri()); + TestUtil.buildMockBasicAuthentication("admin", "admin")); + + createdAction = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, creatingAction, + TENANT_ID); + Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, createdAction.getId()); + Assert.assertEquals(creatingAction.getName(), createdAction.getName()); + Assert.assertEquals(creatingAction.getDescription(), createdAction.getDescription()); + Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getType().getActionType()); + Assert.assertEquals(Action.Status.ACTIVE, createdAction.getStatus()); + Assert.assertEquals(creatingAction.getEndpoint().getUri(), createdAction.getEndpoint().getUri()); Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - action.getEndpoint().getAuthentication().getType()); + createdAction.getEndpoint().getAuthentication().getType()); } @Test(priority = 2, expectedExceptions = ActionMgtException.class, expectedExceptionsMessageRegExp = "Error while adding Action.") public void testAddActionWithoutName() throws ActionMgtException { - Action action = buildMockAction( + Action action = TestUtil.buildMockAction( null, "To configure PreIssueAccessToken", "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - this.action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), action, TENANT_ID); + TestUtil.buildMockBasicAuthentication("admin", "admin")); + + daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, String.valueOf(UUID.randomUUID()), action, TENANT_ID); } @Test(priority = 3, dependsOnMethods = "testAddAction") public void testGetActionsByActionType() throws ActionMgtException { - List actionList = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, TENANT_ID); + List actionList = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_TYPE, TENANT_ID); Assert.assertEquals(1, actionList.size()); Action result = actionList.get(0); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Assert.assertEquals(createdAction.getId(), result.getId()); + Assert.assertEquals(createdAction.getName(), result.getName()); + Assert.assertEquals(createdAction.getDescription(), result.getDescription()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); + Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); } @Test(priority = 4) public void testGetActionByActionId() throws ActionMgtException { - Action result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Action result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); + Assert.assertEquals(createdAction.getName(), result.getName()); + Assert.assertEquals(createdAction.getDescription(), result.getDescription()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); + Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); } @Test(priority = 5) public void testDeleteAction() throws ActionMgtException { - daoImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), action, TENANT_ID); - Assert.assertNull(daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID)); + daoImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, createdAction, TENANT_ID); + Assert.assertNull(daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID)); } @Test(priority = 6) public void testAddActionWithoutDescription() throws ActionMgtException { String id = String.valueOf(UUID.randomUUID()); - Action creatingAction = buildMockAction( + Action creatingAction = TestUtil.buildMockAction( "PreIssueAccessToken", null, "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, id, creatingAction, TENANT_ID); - Assert.assertEquals(id, action.getId()); - Assert.assertEquals(creatingAction.getName(), action.getName()); - Assert.assertNull(null, action.getDescription()); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN, action.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), action.getEndpoint().getUri()); + TestUtil.buildMockBasicAuthentication("admin", "admin")); + createdAction = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, id, creatingAction, TENANT_ID); + Assert.assertEquals(id, createdAction.getId()); + Assert.assertEquals(creatingAction.getName(), createdAction.getName()); + Assert.assertNull(null, createdAction.getDescription()); + Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getType().getActionType()); + Assert.assertEquals(Action.Status.ACTIVE, createdAction.getStatus()); + Assert.assertEquals(creatingAction.getEndpoint().getUri(), createdAction.getEndpoint().getUri()); Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - action.getEndpoint().getAuthentication().getType()); + createdAction.getEndpoint().getAuthentication().getType()); } @Test(priority = 7, dependsOnMethods = "testAddActionWithoutDescription") public void testUpdateAction() throws ActionMgtException { - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( "Pre Issue Access Token", "To configure pre issue access token", "https://sample.com", - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); + TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); Assert.assertEquals(updatingAction.getName(), result.getName()); Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); Assert.assertEquals( updatingAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType() ); - action = result; + createdAction = result; } @Test(priority = 8) @@ -202,17 +209,18 @@ public void testUpdateActionWithoutNameAndDescription() throws ActionMgtExceptio // TODO: 'Name' is a required attribute. Thus, DAO layer should throw an exception if name is null. // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( null, null, "https://sample.com", - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); + TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); + Assert.assertEquals(createdAction.getName(), result.getName()); + Assert.assertEquals(createdAction.getDescription(), result.getDescription()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); @@ -224,19 +232,20 @@ public void testUpdateActionWithNameAndDescription() throws ActionMgtException { // TODO: 'Uri','AuthenticationType','AuthProperties' are required attributes. Thus, DAO layer should throw an // exception if those attributes are null. This should be fixed in DAO layer and test case needs to be updated // accordingly. - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( "Pre Issue Access Token", "To configure pre issue access token", null, null); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); Assert.assertEquals(updatingAction.getName(), result.getName()); Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); + Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); } @@ -245,18 +254,19 @@ public void testUpdateActionWithoutEndpointUri() throws ActionMgtException { // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if Uri is null. // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( "Pre Issue Access Token", "To configure pre issue access token", null, - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); + TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); Assert.assertEquals(updatingAction.getName(), result.getName()); Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); + Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); } @@ -264,21 +274,22 @@ public void testUpdateActionWithoutEndpointUri() throws ActionMgtException { @Test(priority = 11) public void testUpdateActionWithAuthType() throws ActionMgtException { - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( "Pre Issue Access Token", "To configure pre issue access token", "https://sample.com", - buildMockBearerAuthentication("57c7df90-cacc-4f56-9b0a-f14bfbff3076")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); + TestUtil.buildMockBearerAuthentication("57c7df90-cacc-4f56-9b0a-f14bfbff3076")); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); + Assert.assertEquals(createdAction.getName(), result.getName()); + Assert.assertEquals(createdAction.getDescription(), result.getDescription()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); - action = result; + createdAction = result; } @Test(priority = 12) @@ -287,21 +298,22 @@ public void testUpdateActionWithUri() throws ActionMgtException { // TODO: 'Name','AuthenticationType' and 'AuthProperties' are required attributes. Thus, DAO layer should throw // an exception if those attributes are null. This should be fixed in DAO layer and test case needs to be // updated accordingly. - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( null, null, "https://sample.com", null); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); + Assert.assertEquals(createdAction.getName(), result.getName()); + Assert.assertEquals(createdAction.getDescription(), result.getDescription()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); - action = result; + createdAction = result; } @Test(priority = 13) @@ -309,18 +321,19 @@ public void testUpdateActionWithAuthTypeWithoutUri() throws ActionMgtException { // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if uri is null. // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( "Pre Issue Access Token", "To configure pre issue access token", null, - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); + TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); + Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, + createdAction, TENANT_ID); + Assert.assertEquals(createdAction.getId(), result.getId()); Assert.assertEquals(updatingAction.getName(), result.getName()); Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(createdAction.getType(), result.getType()); + Assert.assertEquals(createdAction.getStatus(), result.getStatus()); + Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); } @@ -328,64 +341,41 @@ public void testUpdateActionWithAuthTypeWithoutUri() throws ActionMgtException { @Test(priority = 14) public void testDeactivateAction() throws ActionMgtException { - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Action deactivatedAction = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); + Assert.assertEquals(Action.Status.ACTIVE, createdAction.getStatus()); + Action deactivatedAction = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), + TENANT_ID); Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); } @Test(priority = 15) public void testActivateAction() throws ActionMgtException { - Action result = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); + Action result = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), TENANT_ID); Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); } @Test(priority = 16) public void testGetActionsCountPerType() throws ActionMgtException { - Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); - for (Map.Entry entry: actionMap.entrySet()) { - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN, entry.getKey()); - Assert.assertEquals(1, entry.getValue().intValue()); - } - } - - private Authentication buildMockBasicAuthentication(String username, String password) { - - return new Authentication.BasicAuthBuilder(username, password).build(); - } - - private Authentication buildMockBearerAuthentication(String accessToken) { - - return new Authentication.BearerAuthBuilder(accessToken).build(); - } - - private Authentication buildMockAPIKeyAuthentication(String header, String value) { - - return new Authentication.APIKeyAuthBuilder(header, value).build(); - } - - private EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { - - if (uri == null && authentication == null) { - return null; - } - - return new EndpointConfig.EndpointConfigBuilder() - .uri(uri) - .authentication(authentication) - .build(); - } - - private Action buildMockAction(String name, - String description, - String uri, - Authentication authentication) { + PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( + "PreUpdatePassword", + "To configure PreUpdatePassword", + "https://example.com", + TestUtil.buildMockBasicAuthentication("admin", "admin"), + PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, + null); - return new Action.ActionRequestBuilder() - .name(name) - .description(description) - .endpoint(buildMockEndpointConfig(uri, authentication)) - .build(); + Action preUpdatePasswordAction = daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, + actionModel, TENANT_ID); + + Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); + Assert.assertTrue(actionMap.containsKey(PRE_ISSUE_ACCESS_TOKEN_TYPE)); + Assert.assertEquals(1, actionMap.get(PRE_ISSUE_ACCESS_TOKEN_TYPE).intValue()); + Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); + Assert.assertEquals(1, actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue()); + + daoImpl.deleteAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction, + TENANT_ID); + daoImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, createdAction, TENANT_ID); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java new file mode 100644 index 000000000000..62fb1100565c --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java @@ -0,0 +1,497 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.dao; + +import org.apache.commons.lang.StringUtils; +import org.junit.Assert; +import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; +import org.wso2.carbon.identity.action.management.util.TestUtil; +import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtClientException; +import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtException; +import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtServerException; +import org.wso2.carbon.identity.certificate.management.model.Certificate; +import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; +import org.wso2.carbon.identity.common.testng.WithH2Database; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.UPDATED_CERTIFICATE; +import static org.wso2.carbon.identity.certificate.management.constant.CertificateMgtErrors.ERROR_INVALID_CERTIFICATE_CONTENT; + +/** + * This class is a test suite for the ActionManagementDAOImpl class. + * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOImpl class + * for PRE_UPDATE_PASSWORD action type. + */ +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithCarbonHome +public class PreUpdatePasswordActionManagementDAOImplTest { + + private ActionManagementDAOImpl daoImpl; + private MockedStatic identityTenantUtil; + private PreUpdatePasswordAction preUpdatePasswordAction; + + private CertificateManagementService certificateManagementService; + private Certificate certificate; + private CertificateMgtServerException serverException; + private CertificateMgtClientException clientException; + + @BeforeClass + public void setUpClass() { + + daoImpl = new ActionManagementDAOImpl(); + } + + @BeforeMethod + public void setUp() throws SecretManagementException { + + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + identityTenantUtil.when(()-> IdentityTenantUtil.getTenantId(anyString())).thenReturn(TENANT_ID); + identityTenantUtil.when(()-> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(TENANT_DOMAIN); + when(secretType.getId()).thenReturn("secretId"); + when(secretManager.getSecretType(any())).thenReturn(secretType); + + certificateManagementService = mock(CertificateManagementService.class); + ActionMgtServiceComponentHolder.getInstance() + .setCertificateManagementService(certificateManagementService); + + serverException = new CertificateMgtServerException("server_error_message", "server_error_description", "65030", + new Throwable()); + clientException = new CertificateMgtClientException(ERROR_INVALID_CERTIFICATE_CONTENT.getMessage(), + ERROR_INVALID_CERTIFICATE_CONTENT.getDescription(), ERROR_INVALID_CERTIFICATE_CONTENT.getCode()); + } + + @AfterMethod + public void tearDown() { + + identityTenantUtil.close(); + } + + @Test(priority = 1) + public void testAddPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { + + PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( + "PreUpdatePassword", + "To configure PreUpdatePassword", + "https://example.com", + TestUtil.buildMockBasicAuthentication("admin", "admin"), + PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, + CERTIFICATE); + certificate = new Certificate.Builder() + .id(String.valueOf(CERTIFICATE_ID)) + .name(CERTIFICATE_NAME) + .certificateContent(CERTIFICATE) + .build(); + + doReturn(CERTIFICATE_ID).when(certificateManagementService).addCertificate(any(), any()); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); + preUpdatePasswordAction = (PreUpdatePasswordAction) daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, + PRE_UPDATE_PASSWORD_ACTION_ID, actionModel, TENANT_ID); + + Assert.assertEquals(PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction.getId()); + Assert.assertEquals(actionModel.getName(), preUpdatePasswordAction.getName()); + Assert.assertEquals(actionModel.getDescription(), preUpdatePasswordAction.getDescription()); + Assert.assertEquals(PRE_UPDATE_PASSWORD_TYPE, preUpdatePasswordAction.getType().getActionType()); + Assert.assertEquals(Action.Status.ACTIVE, preUpdatePasswordAction.getStatus()); + Assert.assertEquals(actionModel.getEndpoint().getUri(), preUpdatePasswordAction.getEndpoint().getUri()); + Assert.assertEquals(actionModel.getEndpoint().getAuthentication().getType(), + preUpdatePasswordAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(actionModel.getPasswordSharingFormat(), preUpdatePasswordAction.getPasswordSharingFormat()); + Assert.assertNotNull(preUpdatePasswordAction.getCertificate()); + Assert.assertEquals(CERTIFICATE_ID, preUpdatePasswordAction.getCertificate().getId()); + Assert.assertEquals(CERTIFICATE_NAME, preUpdatePasswordAction.getCertificate().getName()); + } + + @Test(priority = 2, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testGetPreUpdatePasswordActionsByActionType() throws ActionMgtException, CertificateMgtException { + + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); + List preUpdatePasswordActionList = daoImpl.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); + + Assert.assertEquals(1, preUpdatePasswordActionList.size()); + PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) preUpdatePasswordActionList.get(0); + Assert.assertEquals(preUpdatePasswordAction.getId(), fetchedAction.getId()); + Assert.assertEquals(preUpdatePasswordAction.getName(), fetchedAction.getName()); + Assert.assertEquals(preUpdatePasswordAction.getDescription(), fetchedAction.getDescription()); + Assert.assertEquals(preUpdatePasswordAction.getType(), fetchedAction.getType()); + Assert.assertEquals(preUpdatePasswordAction.getStatus(), fetchedAction.getStatus()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), fetchedAction.getEndpoint().getUri()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), + fetchedAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals( + preUpdatePasswordAction.getPasswordSharingFormat(), fetchedAction.getPasswordSharingFormat()); + Assert.assertNotNull(fetchedAction.getCertificate()); + Assert.assertEquals(preUpdatePasswordAction.getCertificate().getId(), fetchedAction.getCertificate().getId()); + Assert.assertEquals( + preUpdatePasswordAction.getCertificate().getName(), fetchedAction.getCertificate().getName()); + + } + + @Test(priority = 3, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testGetPreUpdatePasswordActionByActionId() throws ActionMgtException, CertificateMgtException { + + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); + PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) + daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); + + Assert.assertEquals(preUpdatePasswordAction.getId(), fetchedAction.getId()); + Assert.assertEquals(preUpdatePasswordAction.getName(), fetchedAction.getName()); + Assert.assertEquals(preUpdatePasswordAction.getDescription(), fetchedAction.getDescription()); + Assert.assertEquals(preUpdatePasswordAction.getType(), fetchedAction.getType()); + Assert.assertEquals(preUpdatePasswordAction.getStatus(), fetchedAction.getStatus()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), fetchedAction.getEndpoint().getUri()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), + fetchedAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals( + preUpdatePasswordAction.getPasswordSharingFormat(), fetchedAction.getPasswordSharingFormat()); + Assert.assertNotNull(fetchedAction.getCertificate()); + Assert.assertEquals(preUpdatePasswordAction.getCertificate().getId(), fetchedAction.getCertificate().getId()); + Assert.assertEquals( + preUpdatePasswordAction.getCertificate().getName(), fetchedAction.getCertificate().getName()); + } + + @Test(priority = 4, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testGetPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { + + doThrow(serverException).when(certificateManagementService).getCertificate(anyString(), anyString()); + try { + daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); + Assert.fail("Successful retrieval of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtServerException.class); + Assert.assertEquals(e.getMessage(), + ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtServerException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } + + @Test(priority = 5, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testUpdatePreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { + + PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( + "Updated PreUpdatePassword Action", + "To configure PreUpdatePassword of wso2.com organization", + "https://my-extension.com/pre-update-password", + TestUtil.buildMockNoneAuthentication(), + PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, + UPDATED_CERTIFICATE); + + certificate = new Certificate.Builder() + .id(String.valueOf(CERTIFICATE_ID)) + .name(CERTIFICATE_NAME) + .certificateContent(UPDATED_CERTIFICATE) + .build(); + + doNothing().when(certificateManagementService).updateCertificateContent(anyString(), anyString(), anyString()); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); + + PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) daoImpl.updateAction( + PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, + preUpdatePasswordAction, TENANT_ID); + + Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); + Assert.assertEquals(updateActionModel.getName(), updatedAction.getName()); + Assert.assertEquals(updateActionModel.getDescription(), updatedAction.getDescription()); + Assert.assertEquals(preUpdatePasswordAction.getType(), updatedAction.getType()); + Assert.assertEquals(preUpdatePasswordAction.getStatus(), updatedAction.getStatus()); + Assert.assertEquals(updateActionModel.getEndpoint().getUri(), updatedAction.getEndpoint().getUri()); + Assert.assertEquals(updateActionModel.getEndpoint().getAuthentication().getType(), + updatedAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updateActionModel.getPasswordSharingFormat(), updatedAction.getPasswordSharingFormat()); + Assert.assertNotNull(updatedAction.getCertificate()); + Assert.assertEquals(certificate.getId(), updatedAction.getCertificate().getId()); + Assert.assertEquals(certificate.getName(), updatedAction.getCertificate().getName()); + Assert.assertEquals(certificate.getCertificateContent(), + updatedAction.getCertificate().getCertificateContent()); + + preUpdatePasswordAction = updatedAction; + } + + @Test(priority = 6, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testUpdatePreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { + + PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( + "Updated PreUpdatePassword Action", + "To configure PreUpdatePassword of wso2.com organization", + "https://my-extension.com/pre-update-password", + TestUtil.buildMockNoneAuthentication(), + PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, + CERTIFICATE); + + doThrow(serverException).when(certificateManagementService).updateCertificateContent(any(), any(), any()); + try { + daoImpl.updateAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, + preUpdatePasswordAction, TENANT_ID); + Assert.fail("Successful update of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(ActionMgtServerException.class, e.getClass()); + Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION.getMessage(), + e.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtServerException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } + + @Test(priority = 7, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testUpdatePreUpdatePasswordActionWithClientErrorFromCertificate() throws CertificateMgtException { + + PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( + "Updated PreUpdatePassword Action", + "To configure PreUpdatePassword of wso2.com organization", + "https://my-extension.com/pre-update-password", + TestUtil.buildMockNoneAuthentication(), + PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, + CERTIFICATE); + + doThrow(clientException).when(certificateManagementService).updateCertificateContent(any(), any(), any()); + try { + daoImpl.updateAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, + preUpdatePasswordAction, TENANT_ID); + Assert.fail("Successful update of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(ActionMgtClientException.class, e.getClass()); + Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE.getMessage(), + e.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtClientException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtClientException was not found in the exception chain"); + } + } + + @Test(priority = 8, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testDeleteCertificateOfPreUpdatePasswordActionWithServerError() throws CertificateMgtException { + + PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, + null, null, null, StringUtils.EMPTY); + + doThrow(serverException).when(certificateManagementService).deleteCertificate(any(), any()); + try { + daoImpl.updateAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, + preUpdatePasswordAction, TENANT_ID); + Assert.fail("Successful update of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(ActionMgtServerException.class, e.getClass()); + Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION.getMessage(), + e.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtServerException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } + + @Test(priority = 9, dependsOnMethods = "testUpdatePreUpdatePasswordAction") + public void testDeleteCertificateOfPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { + + PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, + null, null, null, StringUtils.EMPTY); + + doNothing().when(certificateManagementService).deleteCertificate(anyString(), anyString()); + + PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) daoImpl.updateAction( + PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, + preUpdatePasswordAction, TENANT_ID); + + Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); + Assert.assertEquals(preUpdatePasswordAction.getName(), updatedAction.getName()); + Assert.assertEquals(preUpdatePasswordAction.getDescription(), updatedAction.getDescription()); + Assert.assertEquals(preUpdatePasswordAction.getType(), updatedAction.getType()); + Assert.assertEquals(preUpdatePasswordAction.getStatus(), updatedAction.getStatus()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), updatedAction.getEndpoint().getUri()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), + updatedAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(preUpdatePasswordAction.getPasswordSharingFormat(), + updatedAction.getPasswordSharingFormat()); + Assert.assertNull(updatedAction.getCertificate()); + + preUpdatePasswordAction = updatedAction; + } + + @Test(priority = 10, dependsOnMethods = "testUpdatePreUpdatePasswordAction") + public void testAddCertificateOfPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { + + PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, + null, null, null, CERTIFICATE); + + doReturn(CERTIFICATE_ID).when(certificateManagementService).addCertificate(any(), anyString()); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); + + PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) daoImpl.updateAction( + PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, + preUpdatePasswordAction, TENANT_ID); + + Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); + Assert.assertEquals(preUpdatePasswordAction.getName(), updatedAction.getName()); + Assert.assertEquals(preUpdatePasswordAction.getDescription(), updatedAction.getDescription()); + Assert.assertEquals(preUpdatePasswordAction.getType(), updatedAction.getType()); + Assert.assertEquals(preUpdatePasswordAction.getStatus(), updatedAction.getStatus()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), updatedAction.getEndpoint().getUri()); + Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), + updatedAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(preUpdatePasswordAction.getPasswordSharingFormat(), + updatedAction.getPasswordSharingFormat()); + + Assert.assertNotNull(updatedAction.getCertificate()); + Assert.assertEquals(certificate.getId(), updatedAction.getCertificate().getId()); + Assert.assertEquals(certificate.getName(), updatedAction.getCertificate().getName()); + Assert.assertEquals(certificate.getCertificateContent(), + updatedAction.getCertificate().getCertificateContent()); + + preUpdatePasswordAction = updatedAction; + } + + @Test(priority = 8, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testDeletePreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { + + doThrow(serverException).when(certificateManagementService).deleteCertificate(any(), any()); + try { + daoImpl.deleteAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction, + TENANT_ID); + Assert.fail("Successful deletion of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(ActionMgtServerException.class, e.getClass()); + Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_DELETING_ACTION.getMessage(), + e.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtServerException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } + + @Test(priority = 11) + public void testDeletePreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { + + doNothing().when(certificateManagementService).deleteCertificate(anyString(), anyString()); + + daoImpl.deleteAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction, + TENANT_ID); + + Assert.assertNull(daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, + TENANT_ID)); + } + + @Test(priority = 12, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testAddPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { + + PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( + "PreUpdatePassword", + "To configure PreUpdatePassword", + "https://example.com", + TestUtil.buildMockBasicAuthentication("admin", "admin"), + PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, + CERTIFICATE); + + doThrow(serverException).when(certificateManagementService).addCertificate(any(), any()); + try { + daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, actionModel, TENANT_ID); + Assert.fail("Successful addition of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(ActionMgtServerException.class, e.getClass()); + Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION.getMessage(), + e.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtServerException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } + + @Test(priority = 13, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testAddPreUpdatePasswordActionWithClientErrorFromCertificate() throws CertificateMgtException { + + PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( + "PreUpdatePassword", + "To configure PreUpdatePassword", + "https://example.com", + TestUtil.buildMockBasicAuthentication("admin", "admin"), + PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, + CERTIFICATE); + + doThrow(clientException).when(certificateManagementService).addCertificate(any(), any()); + try { + daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, actionModel, TENANT_ID); + Assert.fail("Successful addition of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(ActionMgtClientException.class, e.getClass()); + Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE.getMessage(), + e.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtClientException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java new file mode 100644 index 000000000000..296fcb9d0cb6 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.util; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; +import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction.PasswordFormat; +import org.wso2.carbon.identity.certificate.management.model.Certificate; + +import java.util.UUID; + +/** + * Utility class for Action Management Tests. + */ +public class TestUtil { + + public static final int TENANT_ID = 2; + public static final String TENANT_DOMAIN = "wso2.com"; + + public static final String PRE_ISSUE_ACCESS_TOKEN_TYPE = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(); + public static final String PRE_UPDATE_PASSWORD_TYPE = Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType(); + + public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); + public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); + public static final String CERTIFICATE_ID = String.valueOf(UUID.randomUUID()); + public static final String CERTIFICATE_NAME = "ACTIONS:" + PRE_UPDATE_PASSWORD_ACTION_ID; + public static final String CERTIFICATE = "sample-certificate"; + public static final String UPDATED_CERTIFICATE = "updated-sample-certificate"; + + public static Action buildMockAction(String name, + String description, + String uri, + Authentication authentication) { + + return new Action.ActionRequestBuilder() + .name(name) + .description(description) + .endpoint(buildMockEndpointConfig(uri, authentication)) + .build(); + } + + public static PreUpdatePasswordAction buildMockPreUpdatePasswordAction(String name, String description, String uri, + Authentication authentication, + PasswordFormat passwordSharingFormat, + String certificate) { + + return new PreUpdatePasswordAction.RequestBuilder() + .name(name) + .description(description) + .endpoint(buildMockEndpointConfig(uri, authentication)) + .passwordSharingFormat(passwordSharingFormat) + .certificate(new Certificate.Builder().certificateContent(certificate).build()) + .build(); + } + + public static Authentication buildMockBasicAuthentication(String username, String password) { + + return new Authentication.BasicAuthBuilder(username, password).build(); + } + + public static Authentication buildMockBearerAuthentication(String accessToken) { + + return new Authentication.BearerAuthBuilder(accessToken).build(); + } + + public static Authentication buildMockNoneAuthentication() { + + return new Authentication.NoneAuthBuilder().build(); + } + + private static EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { + + if (uri == null && authentication == null) { + return null; + } + + return new EndpointConfig.EndpointConfigBuilder() + .uri(uri) + .authentication(authentication) + .build(); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index 60acc4cb2749..64973df3183b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -22,6 +22,7 @@ + From 1f987bb9b27dc20f14ef0ddf390f7a6a7226f659 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Sun, 10 Nov 2024 20:33:38 +0530 Subject: [PATCH 04/34] lower coverage levels --- .../org.wso2.carbon.identity.action.management/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index f07510237b03..4f029dd8a1ba 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -183,14 +183,14 @@ - 0.78 + 0.76 COMPLEXITY COVEREDRATIO - 0.68 + 0.66 From 4dca5c14e75b80afacaf63808549a2d94b32135b Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 11 Nov 2024 02:08:49 +0530 Subject: [PATCH 05/34] Refactor unit tests --- .../pom.xml | 4 +- .../constant/ActionMgtConstants.java | 4 +- .../dao/impl/ActionManagementDAOImpl.java | 37 +++-- .../dao/impl/CacheBackedActionMgtDAO.java | 1 - .../action/management/model/Action.java | 34 +--- .../model/PreUpdatePasswordAction.java | 6 - .../ActionManagementServiceImplTest.java | 120 +++++--------- ...eUpdatePasswordActionServiceImplTest.java} | 153 ++++++++---------- .../action/management/util/TestUtil.java | 15 +- .../src/test/resources/testng.xml | 2 +- 10 files changed, 146 insertions(+), 230 deletions(-) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/{dao/PreUpdatePasswordActionManagementDAOImplTest.java => PreUpdatePasswordActionServiceImplTest.java} (87%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index 4f029dd8a1ba..deac82f059f1 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -183,14 +183,14 @@ - 0.76 + 0.77 COMPLEXITY COVEREDRATIO - 0.66 + 0.68 diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index e2fa57c31ec9..4df204ed55d5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -95,9 +95,9 @@ public enum ErrorMessages { "Error while persisting certificate in the system."), ERROR_WHILE_RETRIEVING_ACTION_CERTIFICATE("65016", "Error while retrieving action certificate.", "Error while retrieving certificate from the system."), - ERROR_WHILE_UPDATING_ACTION_CERTIFICATE("65016", "Error while updating action certificate.", + ERROR_WHILE_UPDATING_ACTION_CERTIFICATE("65017", "Error while updating action certificate.", "Error while updating certificate in the system."), - ERROR_WHILE_DELETING_ACTION_CERTIFICATE("65016", "Error while deleting action certificate.", + ERROR_WHILE_DELETING_ACTION_CERTIFICATE("65018", "Error while deleting action certificate.", "Error while deleting certificate from the system."); private final String code; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index b9b55f62ed07..84c28ec4d267 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -507,7 +507,7 @@ private void updateBasicInfo(String actionType, String actionId, Action updating } /** - * Resolves the endpoint properties for an action, supporting both addAction and updateAction scenarios. + * Resolves the endpoint properties for an action when action is updating. * This method ensures that authentication secrets are handled appropriately, and the URI is resolved * based on the provided or existing endpoint configurations. * When the updating action does not contain endpoint configuration, it uses the existing endpoint's properties. @@ -537,9 +537,8 @@ private Map resolveEndpointProperties(String actionId, Action up } /** - * Resolves the authentication properties for an endpoint, handling both addAction and updateAction scenarios. - * In addAction, the method generates new secrets based on the provided endpoint configuration. - * In updateAction, it deletes existing secrets and updates them with new properties as necessary. + * Resolves the authentication properties for an endpoint when action is updating. + * This deletes existing secrets and updates them with new properties as necessary. * When the updating endpoint does not contain authentication, it uses the existing endpoint's properties. * * @param actionId Action ID. @@ -557,8 +556,8 @@ private Map resolveEndpointAuthenticationProperties(String actio Authentication existingAuthentication = existingEndpoint.getAuthentication(); Map authentication = new HashMap<>(); - Authentication.Type resolvedAuthType = existingAuthentication.getType();; - List resolvedAuthProperties = existingAuthentication.getProperties();; + Authentication.Type resolvedAuthType = existingAuthentication.getType(); + List resolvedAuthProperties = existingAuthentication.getProperties(); if (updatingAuthentication != null) { // Delete existing secrets. @@ -605,10 +604,10 @@ private Map resolveActionTypeSpecificProperties(String actionTyp } // Handle certificate changes. - String certId = handleCertificateChanges(actionId, inputPreUpdatePasswordAction, + String certificateId = handleCertificateChanges(actionId, inputPreUpdatePasswordAction, existingPreUpdatePasswordAction, tenantId); - if (StringUtils.isNotEmpty(certId)) { - actionTypeSpecificProperties.put(CERTIFICATE_ID_PROPERTY, certId); + if (StringUtils.isNotEmpty(certificateId)) { + actionTypeSpecificProperties.put(CERTIFICATE_ID_PROPERTY, certificateId); } break; @@ -661,26 +660,26 @@ private String handleCertificateChanges(String actionId, PreUpdatePasswordAction PreUpdatePasswordAction existingAction, Integer tenantId) throws ActionMgtException { - String updatingCertificate = inputAction.getCertificate() != null ? + String inputCertificate = inputAction.getCertificate() != null ? inputAction.getCertificate().getCertificateContent() : null; - String updatingCertificateId = existingAction != null && existingAction.getCertificate() != null + String certificateId = existingAction != null && existingAction.getCertificate() != null ? existingAction.getCertificate().getId() : null; - if (updatingCertificate != null) { - if (updatingCertificateId == null) { + if (inputCertificate != null) { + if (StringUtils.isEmpty(certificateId)) { // Add the new certificate. - updatingCertificateId = addCertificate(actionId, updatingCertificate, tenantId); - } else if (updatingCertificate.isEmpty()) { + certificateId = addCertificate(actionId, inputCertificate, tenantId); + } else if (inputCertificate.isEmpty()) { // Delete the existing certificate. - deleteCertificate(updatingCertificateId, tenantId); - updatingCertificateId = null; + deleteCertificate(certificateId, tenantId); + certificateId = null; } else { // Update the existing certificate. - updateCertificate(updatingCertificateId, updatingCertificate, tenantId); + updateCertificate(certificateId, inputCertificate, tenantId); } } - return updatingCertificateId; + return certificateId; } /** diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java index bfb0f5f613d3..f3f2918d5b2c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java @@ -18,7 +18,6 @@ package org.wso2.carbon.identity.action.management.dao.impl; -//import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java index ff9783787a7c..dc1f3030bf47 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java @@ -115,7 +115,7 @@ public static ActionTypes[] filterByCategory(Category category) { */ public enum Category { PRE_POST, - IN_FLOW; + IN_FLOW } } @@ -124,27 +124,8 @@ public enum Category { */ public enum Status { - ACTIVE("ACTIVE"), - INACTIVE("INACTIVE"); - - private final String value; - - Status(String v) { - this.value = v; - } - - public String value() { - return value; - } - - public static Status fromValue(String value) { - for (Status b : Status.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } + ACTIVE, + INACTIVE } private String id; @@ -154,9 +135,6 @@ public static Status fromValue(String value) { private Status status; private EndpointConfig endpointConfig; - public Action() { - } - public Action(ActionResponseBuilder actionResponseBuilder) { this.id = actionResponseBuilder.id; @@ -216,9 +194,6 @@ public static class ActionResponseBuilder { private Status status; private EndpointConfig endpointConfig; - public ActionResponseBuilder() { - } - public ActionResponseBuilder id(String id) { this.id = id; @@ -270,9 +245,6 @@ public static class ActionRequestBuilder { private String description; private EndpointConfig endpointConfig; - public ActionRequestBuilder() { - } - public ActionRequestBuilder name(String name) { this.name = name; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java index 7bfbc43ea455..f1731179603b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java @@ -70,9 +70,6 @@ public static class ResponseBuilder extends ActionResponseBuilder { private PasswordFormat passwordSharingFormat; private Certificate certificate; - public ResponseBuilder() { - } - public ResponseBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat) { this.passwordSharingFormat = passwordSharingFormat; @@ -142,9 +139,6 @@ public static class RequestBuilder extends ActionRequestBuilder { private PasswordFormat passwordSharingFormat; private Certificate certificate; - public RequestBuilder() { - } - public RequestBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat) { this.passwordSharingFormat = passwordSharingFormat; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java index 6b0300fc7f41..3a8adda20c8e 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java @@ -18,23 +18,20 @@ package org.wso2.carbon.identity.action.management; -import org.mockito.MockedStatic; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; import org.wso2.carbon.identity.common.testng.WithRealmService; import org.wso2.carbon.identity.core.internal.IdentityCoreServiceDataHolder; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; @@ -46,6 +43,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_PATH; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; /** * This class is a test suite for the ActionManagementServiceImpl class. @@ -57,19 +56,15 @@ @WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) public class ActionManagementServiceImplTest { - private MockedStatic identityDatabaseUtil; + private ActionManagementService actionManagementService; + private Action action; - private String tenantDomain; - private ActionManagementService serviceImpl; private Map secretProperties; - private static final String ACCESS_TOKEN = "6e47f1f7-bd29-41e9-b5dc-e9dd70ac22b7"; - private static final String PRE_ISSUE_ACCESS_TOKEN = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getPathParam(); @BeforeClass public void setUpClass() { - serviceImpl = ActionManagementServiceImpl.getInstance(); - tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + actionManagementService = ActionManagementServiceImpl.getInstance(); } @BeforeMethod @@ -85,13 +80,12 @@ public void setUp() throws SecretManagementException { @Test(priority = 1) public void testAddAction() throws ActionMgtException, SecretManagementException { - Action creatingAction = buildMockAction( + Action creatingAction = TestUtil.buildMockAction( "PreIssueAccessToken", "To configure PreIssueAccessToken", "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, - tenantDomain); + TestUtil.buildMockBasicAuthentication("admin", "admin")); + action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); Assert.assertNotNull(action.getId()); Assert.assertEquals(creatingAction.getName(), action.getName()); Assert.assertEquals(creatingAction.getDescription(), action.getDescription()); @@ -117,24 +111,24 @@ public void testAddAction() throws ActionMgtException, SecretManagementException @Test(priority = 2, expectedExceptions = ActionMgtException.class, expectedExceptionsMessageRegExp = "Unable to create an Action.") public void testAddActionWithInvalidData() throws ActionMgtException { - Action creatingAction = buildMockAction( + Action creatingAction = TestUtil.buildMockAction( "PreIssueAccessToken_#1", "To configure PreIssueAccessToken", "https://example.com", - buildMockAPIKeyAuthentication("-test-header", "thisisapikey")); - Action action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, tenantDomain); + TestUtil.buildMockAPIKeyAuthentication("-test-header", "thisisapikey")); + Action action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); Assert.assertNull(action); } @Test(priority = 3, expectedExceptions = ActionMgtException.class, expectedExceptionsMessageRegExp = "Unable to create an Action.") public void testAddActionWithEmptyData() throws ActionMgtException { - Action creatingAction = buildMockAction( + Action creatingAction = TestUtil.buildMockAction( "", "To configure PreIssueAccessToken", "https://example.com", - buildMockBasicAuthentication(null, "admin")); - Action action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, tenantDomain); + TestUtil.buildMockBasicAuthentication(null, "admin")); + Action action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); Assert.assertNull(action); } @@ -142,19 +136,20 @@ public void testAddActionWithEmptyData() throws ActionMgtException { expectedExceptionsMessageRegExp = "Unable to create an Action.") public void testAddMaximumActionsPerType() throws ActionMgtException { - Action creatingAction = buildMockAction( + Action creatingAction = TestUtil.buildMockAction( "PreIssueAccessToken", "To configure PreIssueAccessToken", "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, - tenantDomain); + TestUtil.buildMockBasicAuthentication("admin", "admin")); + action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, + TENANT_DOMAIN); } @Test(priority = 5) public void testGetActionsByActionType() throws ActionMgtException, SecretManagementException { - List actions = serviceImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, tenantDomain); + List actions = actionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, + TENANT_DOMAIN); Assert.assertEquals(1, actions.size()); for (Action result: actions) { Assert.assertEquals(action.getId(), result.getId()); @@ -178,7 +173,8 @@ public void testGetActionsByActionType() throws ActionMgtException, SecretManage @Test(priority = 6) public void testGetActionByActionId() throws ActionMgtException, SecretManagementException { - Action result = serviceImpl.getActionByActionId(action.getType().getPathParam(), action.getId(), tenantDomain); + Action result = actionManagementService.getActionByActionId(action.getType().getPathParam(), action.getId(), + TENANT_DOMAIN); Assert.assertEquals(action.getId(), result.getId()); Assert.assertEquals(action.getName(), result.getName()); Assert.assertEquals(action.getDescription(), result.getDescription()); @@ -200,8 +196,8 @@ public void testGetActionByActionId() throws ActionMgtException, SecretManagemen public void testGetActionsByActionTypeFromCache() throws ActionMgtException, SecretManagementException { // Verify that the action is retrieved from the cache based on action type. - List actions = serviceImpl.getActionsByActionType( - PRE_ISSUE_ACCESS_TOKEN, tenantDomain); + List actions = actionManagementService.getActionsByActionType( + PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); Assert.assertEquals(1, actions.size()); Action result = actions.get(0); Assert.assertEquals(action.getId(), result.getId()); @@ -224,12 +220,13 @@ public void testGetActionsByActionTypeFromCache() throws ActionMgtException, Sec @Test(priority = 8) public void testUpdateAction() throws ActionMgtException, SecretManagementException { - Action updatingAction = buildMockAction( + Action updatingAction = TestUtil.buildMockAction( "Pre Issue Access Token", "To update configuration pre issue access token", "https://sample.com", - buildMockAPIKeyAuthentication("header", "value")); - Action result = serviceImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, tenantDomain); + TestUtil.buildMockAPIKeyAuthentication("header", "value")); + Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), + updatingAction, TENANT_DOMAIN); Assert.assertEquals(action.getId(), result.getId()); Assert.assertEquals(updatingAction.getName(), result.getName()); Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); @@ -253,23 +250,23 @@ public void testUpdateAction() throws ActionMgtException, SecretManagementExcept public void testDeactivateAction() throws ActionMgtException { Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Action deactivatedAction = serviceImpl.deactivateAction( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); + Action deactivatedAction = actionManagementService.deactivateAction( + PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), TENANT_DOMAIN); Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); } @Test(priority = 10) public void testActivateAction() throws ActionMgtException { - Action result = serviceImpl.activateAction( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); + Action result = actionManagementService.activateAction( + PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), TENANT_DOMAIN); Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); } @Test(priority = 11) public void testGetActionsCountPerType() throws ActionMgtException { - Map actionMap = serviceImpl.getActionsCountPerType(tenantDomain); + Map actionMap = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType())); Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PROFILE.getActionType())); Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_REGISTRATION.getActionType())); @@ -283,11 +280,11 @@ public void testGetActionsCountPerType() throws ActionMgtException { @Test(priority = 12) public void testDeleteAction() throws ActionMgtException { - serviceImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); - Assert.assertNull(serviceImpl.getActionByActionId(action.getType().getPathParam(), action.getId(), - tenantDomain)); - Map actions = serviceImpl.getActionsCountPerType(tenantDomain); - Assert.assertNull(actions.get(PRE_ISSUE_ACCESS_TOKEN)); + actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), TENANT_DOMAIN); + Assert.assertNull(actionManagementService.getActionByActionId(action.getType().getPathParam(), action.getId(), + TENANT_DOMAIN)); + Map actions = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); + Assert.assertNull(actions.get(PRE_ISSUE_ACCESS_TOKEN_PATH)); } private Map mapActionAuthPropertiesWithSecrets(Action action) throws SecretManagementException { @@ -297,43 +294,4 @@ private Map mapActionAuthPropertiesWithSecrets(Action action) th .stream() .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); } - - private Authentication buildMockBasicAuthentication(String username, String password) { - - return new Authentication.BasicAuthBuilder(username, password).build(); - } - - private Authentication buildMockBearerAuthentication(String accessToken) { - - return new Authentication.BearerAuthBuilder(accessToken).build(); - } - - private Authentication buildMockAPIKeyAuthentication(String header, String value) { - - return new Authentication.APIKeyAuthBuilder(header, value).build(); - } - - private EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { - - if (uri == null && authentication == null) { - return null; - } - - return new EndpointConfig.EndpointConfigBuilder() - .uri(uri) - .authentication(authentication) - .build(); - } - - private Action buildMockAction(String name, - String description, - String uri, - Authentication authentication) { - - return new Action.ActionRequestBuilder() - .name(name) - .description(description) - .endpoint(buildMockEndpointConfig(uri, authentication)) - .build(); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java similarity index 87% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java index 62fb1100565c..16400b29f3cc 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/PreUpdatePasswordActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java @@ -16,17 +16,14 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.dao; +package org.wso2.carbon.identity.action.management; import org.apache.commons.lang.StringUtils; import org.junit.Assert; -import org.mockito.MockedStatic; -import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; -import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; @@ -41,7 +38,8 @@ import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.common.testng.WithRealmService; +import org.wso2.carbon.identity.core.internal.IdentityCoreServiceDataHolder; import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; @@ -49,21 +47,18 @@ import java.util.List; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE; import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; -import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_PATH; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; -import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_ID; import static org.wso2.carbon.identity.action.management.util.TestUtil.UPDATED_CERTIFICATE; import static org.wso2.carbon.identity.certificate.management.constant.CertificateMgtErrors.ERROR_INVALID_CERTIFICATE_CONTENT; @@ -72,15 +67,15 @@ * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOImpl class * for PRE_UPDATE_PASSWORD action type. */ -@WithH2Database(files = {"dbscripts/h2.sql"}) @WithCarbonHome -public class PreUpdatePasswordActionManagementDAOImplTest { - - private ActionManagementDAOImpl daoImpl; - private MockedStatic identityTenantUtil; - private PreUpdatePasswordAction preUpdatePasswordAction; +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) +public class PreUpdatePasswordActionServiceImplTest { + private ActionManagementService actionManagementService; private CertificateManagementService certificateManagementService; + + private PreUpdatePasswordAction preUpdatePasswordAction; private Certificate certificate; private CertificateMgtServerException serverException; private CertificateMgtClientException clientException; @@ -88,18 +83,15 @@ public class PreUpdatePasswordActionManagementDAOImplTest { @BeforeClass public void setUpClass() { - daoImpl = new ActionManagementDAOImpl(); + actionManagementService = ActionManagementServiceImpl.getInstance(); } @BeforeMethod public void setUp() throws SecretManagementException { - identityTenantUtil = mockStatic(IdentityTenantUtil.class); SecretManagerImpl secretManager = mock(SecretManagerImpl.class); SecretType secretType = mock(SecretType.class); ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); - identityTenantUtil.when(()-> IdentityTenantUtil.getTenantId(anyString())).thenReturn(TENANT_ID); - identityTenantUtil.when(()-> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(TENANT_DOMAIN); when(secretType.getId()).thenReturn("secretId"); when(secretManager.getSecretType(any())).thenReturn(secretType); @@ -113,12 +105,6 @@ public void setUp() throws SecretManagementException { ERROR_INVALID_CERTIFICATE_CONTENT.getDescription(), ERROR_INVALID_CERTIFICATE_CONTENT.getCode()); } - @AfterMethod - public void tearDown() { - - identityTenantUtil.close(); - } - @Test(priority = 1) public void testAddPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { @@ -137,10 +123,10 @@ public void testAddPreUpdatePasswordAction() throws ActionMgtException, Certific doReturn(CERTIFICATE_ID).when(certificateManagementService).addCertificate(any(), any()); doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - preUpdatePasswordAction = (PreUpdatePasswordAction) daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, - PRE_UPDATE_PASSWORD_ACTION_ID, actionModel, TENANT_ID); + preUpdatePasswordAction = (PreUpdatePasswordAction) actionManagementService.addAction(PRE_UPDATE_PASSWORD_PATH, + actionModel, TENANT_DOMAIN); - Assert.assertEquals(PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction.getId()); + Assert.assertNotNull(preUpdatePasswordAction.getId()); Assert.assertEquals(actionModel.getName(), preUpdatePasswordAction.getName()); Assert.assertEquals(actionModel.getDescription(), preUpdatePasswordAction.getDescription()); Assert.assertEquals(PRE_UPDATE_PASSWORD_TYPE, preUpdatePasswordAction.getType().getActionType()); @@ -155,13 +141,12 @@ public void testAddPreUpdatePasswordAction() throws ActionMgtException, Certific } @Test(priority = 2, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testGetPreUpdatePasswordActionsByActionType() throws ActionMgtException, CertificateMgtException { + public void testGetPreUpdatePasswordActionByActionId() throws ActionMgtException, CertificateMgtException { doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - List preUpdatePasswordActionList = daoImpl.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); + PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) actionManagementService + .getActionByActionId(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), TENANT_DOMAIN); - Assert.assertEquals(1, preUpdatePasswordActionList.size()); - PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) preUpdatePasswordActionList.get(0); Assert.assertEquals(preUpdatePasswordAction.getId(), fetchedAction.getId()); Assert.assertEquals(preUpdatePasswordAction.getName(), fetchedAction.getName()); Assert.assertEquals(preUpdatePasswordAction.getDescription(), fetchedAction.getDescription()); @@ -176,16 +161,17 @@ public void testGetPreUpdatePasswordActionsByActionType() throws ActionMgtExcept Assert.assertEquals(preUpdatePasswordAction.getCertificate().getId(), fetchedAction.getCertificate().getId()); Assert.assertEquals( preUpdatePasswordAction.getCertificate().getName(), fetchedAction.getCertificate().getName()); - } @Test(priority = 3, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testGetPreUpdatePasswordActionByActionId() throws ActionMgtException, CertificateMgtException { + public void testGetPreUpdatePasswordActionsByActionType() throws ActionMgtException, CertificateMgtException { doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) - daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); + List preUpdatePasswordActionList = + actionManagementService.getActionsByActionType(PRE_UPDATE_PASSWORD_PATH, TENANT_DOMAIN); + Assert.assertEquals(1, preUpdatePasswordActionList.size()); + PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) preUpdatePasswordActionList.get(0); Assert.assertEquals(preUpdatePasswordAction.getId(), fetchedAction.getId()); Assert.assertEquals(preUpdatePasswordAction.getName(), fetchedAction.getName()); Assert.assertEquals(preUpdatePasswordAction.getDescription(), fetchedAction.getDescription()); @@ -200,29 +186,10 @@ public void testGetPreUpdatePasswordActionByActionId() throws ActionMgtException Assert.assertEquals(preUpdatePasswordAction.getCertificate().getId(), fetchedAction.getCertificate().getId()); Assert.assertEquals( preUpdatePasswordAction.getCertificate().getName(), fetchedAction.getCertificate().getName()); - } - - @Test(priority = 4, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testGetPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { - doThrow(serverException).when(certificateManagementService).getCertificate(anyString(), anyString()); - try { - daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); - Assert.fail("Successful retrieval of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(e.getClass(), ActionMgtServerException.class); - Assert.assertEquals(e.getMessage(), - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtServerException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } } - @Test(priority = 5, dependsOnMethods = "testAddPreUpdatePasswordAction") + @Test(priority = 4, dependsOnMethods = "testAddPreUpdatePasswordAction") public void testUpdatePreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( @@ -242,9 +209,8 @@ public void testUpdatePreUpdatePasswordAction() throws ActionMgtException, Certi doNothing().when(certificateManagementService).updateCertificateContent(anyString(), anyString(), anyString()); doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) daoImpl.updateAction( - PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, - preUpdatePasswordAction, TENANT_ID); + PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) actionManagementService.updateAction( + PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), updateActionModel, TENANT_DOMAIN); Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); Assert.assertEquals(updateActionModel.getName(), updatedAction.getName()); @@ -264,6 +230,27 @@ public void testUpdatePreUpdatePasswordAction() throws ActionMgtException, Certi preUpdatePasswordAction = updatedAction; } + @Test(priority = 5, dependsOnMethods = "testAddPreUpdatePasswordAction") + public void testGetPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { + + doThrow(serverException).when(certificateManagementService).getCertificate(anyString(), anyString()); + try { + actionManagementService.getActionByActionId(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), + TENANT_DOMAIN); + Assert.fail("Successful retrieval of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtServerException.class); + Assert.assertEquals(e.getMessage(), + ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof CertificateMgtServerException) { + return; + } + } + Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); + } + } + @Test(priority = 6, dependsOnMethods = "testAddPreUpdatePasswordAction") public void testUpdatePreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { @@ -275,10 +262,11 @@ public void testUpdatePreUpdatePasswordActionWithServerErrorFromCertificate() th PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, CERTIFICATE); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); doThrow(serverException).when(certificateManagementService).updateCertificateContent(any(), any(), any()); try { - daoImpl.updateAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, - preUpdatePasswordAction, TENANT_ID); + actionManagementService.updateAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), + updateActionModel, TENANT_DOMAIN); Assert.fail("Successful update of the action without an exception is considered as a failure"); } catch (ActionMgtException e) { Assert.assertEquals(ActionMgtServerException.class, e.getClass()); @@ -304,10 +292,11 @@ public void testUpdatePreUpdatePasswordActionWithClientErrorFromCertificate() th PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, CERTIFICATE); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); doThrow(clientException).when(certificateManagementService).updateCertificateContent(any(), any(), any()); try { - daoImpl.updateAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, - preUpdatePasswordAction, TENANT_ID); + actionManagementService.updateAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), + updateActionModel, TENANT_DOMAIN); Assert.fail("Successful update of the action without an exception is considered as a failure"); } catch (ActionMgtException e) { Assert.assertEquals(ActionMgtClientException.class, e.getClass()); @@ -328,10 +317,11 @@ public void testDeleteCertificateOfPreUpdatePasswordActionWithServerError() thro PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, null, null, null, StringUtils.EMPTY); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); doThrow(serverException).when(certificateManagementService).deleteCertificate(any(), any()); try { - daoImpl.updateAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, - preUpdatePasswordAction, TENANT_ID); + actionManagementService.updateAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), + updateActionModel, TENANT_DOMAIN); Assert.fail("Successful update of the action without an exception is considered as a failure"); } catch (ActionMgtException e) { Assert.assertEquals(ActionMgtServerException.class, e.getClass()); @@ -352,11 +342,11 @@ public void testDeleteCertificateOfPreUpdatePasswordAction() throws ActionMgtExc PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, null, null, null, StringUtils.EMPTY); + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); doNothing().when(certificateManagementService).deleteCertificate(anyString(), anyString()); - PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) daoImpl.updateAction( - PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, - preUpdatePasswordAction, TENANT_ID); + PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) actionManagementService.updateAction( + PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), updateActionModel, TENANT_DOMAIN); Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); Assert.assertEquals(preUpdatePasswordAction.getName(), updatedAction.getName()); @@ -373,7 +363,7 @@ public void testDeleteCertificateOfPreUpdatePasswordAction() throws ActionMgtExc preUpdatePasswordAction = updatedAction; } - @Test(priority = 10, dependsOnMethods = "testUpdatePreUpdatePasswordAction") + @Test(priority = 10, dependsOnMethods = "testDeleteCertificateOfPreUpdatePasswordAction") public void testAddCertificateOfPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, @@ -382,9 +372,8 @@ public void testAddCertificateOfPreUpdatePasswordAction() throws ActionMgtExcept doReturn(CERTIFICATE_ID).when(certificateManagementService).addCertificate(any(), anyString()); doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) daoImpl.updateAction( - PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, updateActionModel, - preUpdatePasswordAction, TENANT_ID); + PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) actionManagementService.updateAction( + PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), updateActionModel, TENANT_DOMAIN); Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); Assert.assertEquals(preUpdatePasswordAction.getName(), updatedAction.getName()); @@ -409,10 +398,11 @@ public void testAddCertificateOfPreUpdatePasswordAction() throws ActionMgtExcept @Test(priority = 8, dependsOnMethods = "testAddPreUpdatePasswordAction") public void testDeletePreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { + doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); doThrow(serverException).when(certificateManagementService).deleteCertificate(any(), any()); try { - daoImpl.deleteAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction, - TENANT_ID); + actionManagementService.deleteAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), + TENANT_DOMAIN); Assert.fail("Successful deletion of the action without an exception is considered as a failure"); } catch (ActionMgtException e) { Assert.assertEquals(ActionMgtServerException.class, e.getClass()); @@ -432,14 +422,13 @@ public void testDeletePreUpdatePasswordAction() throws ActionMgtException, Certi doNothing().when(certificateManagementService).deleteCertificate(anyString(), anyString()); - daoImpl.deleteAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction, - TENANT_ID); + actionManagementService.deleteAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), TENANT_DOMAIN); - Assert.assertNull(daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, - TENANT_ID)); + Assert.assertNull(actionManagementService.getActionByActionId(PRE_UPDATE_PASSWORD_PATH, + preUpdatePasswordAction.getId(), TENANT_DOMAIN)); } - @Test(priority = 12, dependsOnMethods = "testAddPreUpdatePasswordAction") + @Test(priority = 12) public void testAddPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( @@ -452,7 +441,7 @@ public void testAddPreUpdatePasswordActionWithServerErrorFromCertificate() throw doThrow(serverException).when(certificateManagementService).addCertificate(any(), any()); try { - daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, actionModel, TENANT_ID); + actionManagementService.addAction(PRE_UPDATE_PASSWORD_PATH, actionModel, TENANT_DOMAIN); Assert.fail("Successful addition of the action without an exception is considered as a failure"); } catch (ActionMgtException e) { Assert.assertEquals(ActionMgtServerException.class, e.getClass()); @@ -467,7 +456,7 @@ public void testAddPreUpdatePasswordActionWithServerErrorFromCertificate() throw } } - @Test(priority = 13, dependsOnMethods = "testAddPreUpdatePasswordAction") + @Test(priority = 13) public void testAddPreUpdatePasswordActionWithClientErrorFromCertificate() throws CertificateMgtException { PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( @@ -480,7 +469,7 @@ public void testAddPreUpdatePasswordActionWithClientErrorFromCertificate() throw doThrow(clientException).when(certificateManagementService).addCertificate(any(), any()); try { - daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, actionModel, TENANT_ID); + actionManagementService.addAction(PRE_UPDATE_PASSWORD_PATH, actionModel, TENANT_DOMAIN); Assert.fail("Successful addition of the action without an exception is considered as a failure"); } catch (ActionMgtException e) { Assert.assertEquals(ActionMgtClientException.class, e.getClass()); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index 296fcb9d0cb6..e1be2e3fd1cc 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -33,11 +33,14 @@ public class TestUtil { public static final int TENANT_ID = 2; - public static final String TENANT_DOMAIN = "wso2.com"; + public static final String TENANT_DOMAIN = "carbon.super"; public static final String PRE_ISSUE_ACCESS_TOKEN_TYPE = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(); public static final String PRE_UPDATE_PASSWORD_TYPE = Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType(); + public static final String PRE_ISSUE_ACCESS_TOKEN_PATH = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getPathParam(); + public static final String PRE_UPDATE_PASSWORD_PATH = Action.ActionTypes.PRE_UPDATE_PASSWORD.getPathParam(); + public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); public static final String CERTIFICATE_ID = String.valueOf(UUID.randomUUID()); @@ -45,10 +48,7 @@ public class TestUtil { public static final String CERTIFICATE = "sample-certificate"; public static final String UPDATED_CERTIFICATE = "updated-sample-certificate"; - public static Action buildMockAction(String name, - String description, - String uri, - Authentication authentication) { + public static Action buildMockAction(String name, String description, String uri, Authentication authentication) { return new Action.ActionRequestBuilder() .name(name) @@ -81,6 +81,11 @@ public static Authentication buildMockBearerAuthentication(String accessToken) { return new Authentication.BearerAuthBuilder(accessToken).build(); } + public static Authentication buildMockAPIKeyAuthentication(String header, String value) { + + return new Authentication.APIKeyAuthBuilder(header, value).build(); + } + public static Authentication buildMockNoneAuthentication() { return new Authentication.NoneAuthBuilder().build(); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index 64973df3183b..cb1fe221091d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -22,8 +22,8 @@ - + From 1296c3a8f8ca984e33604ab7bb91d80ca8a206e1 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 11 Nov 2024 02:19:17 +0530 Subject: [PATCH 06/34] Rename `IDN_ACTION_ENDPOINT` table name to `IDN_ACTION_PROPERTIES` --- .../management/constant/ActionMgtSQLConstants.java | 9 +++------ .../src/test/resources/dbscripts/h2.sql | 2 +- .../resources/dbscripts/db2.sql | 4 ++-- .../resources/dbscripts/h2.sql | 4 ++-- .../resources/dbscripts/mssql.sql | 6 +++--- .../resources/dbscripts/mysql-cluster.sql | 4 ++-- .../resources/dbscripts/mysql.sql | 4 ++-- .../resources/dbscripts/oracle.sql | 4 ++-- .../resources/dbscripts/oracle_rac.sql | 4 ++-- .../resources/dbscripts/postgresql.sql | 6 +++--- 10 files changed, 22 insertions(+), 25 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java index b41fb5282228..21a19098c941 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java @@ -55,18 +55,18 @@ public static class Query { public static final String ADD_ACTION_TO_ACTION_TYPE = "INSERT INTO IDN_ACTION (UUID, TYPE, NAME, " + "DESCRIPTION, STATUS, TENANT_ID) VALUES (:UUID;, :TYPE;, :NAME;, :DESCRIPTION;, :STATUS;, :TENANT_ID;)"; - public static final String ADD_ACTION_ENDPOINT_PROPERTIES = "INSERT INTO IDN_ACTION_ENDPOINT (ACTION_UUID, " + + public static final String ADD_ACTION_ENDPOINT_PROPERTIES = "INSERT INTO IDN_ACTION_PROPERTIES (ACTION_UUID, " + "PROPERTY_NAME, PROPERTY_VALUE, TENANT_ID) VALUES (:ACTION_UUID;, :PROPERTY_NAME;, :PROPERTY_VALUE;, " + ":TENANT_ID;)"; public static final String GET_ACTION_BASIC_INFO_BY_ID = "SELECT TYPE, NAME, DESCRIPTION, STATUS FROM " + "IDN_ACTION WHERE TYPE = :TYPE; AND UUID = :UUID; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTION_ENDPOINT_INFO_BY_ID = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM " + - "IDN_ACTION_ENDPOINT WHERE ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; + "IDN_ACTION_PROPERTIES WHERE ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE = "SELECT UUID, TYPE, NAME, DESCRIPTION," + " STATUS FROM IDN_ACTION WHERE TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String UPDATE_ACTION_BASIC_INFO = "UPDATE IDN_ACTION SET NAME = :NAME;, DESCRIPTION = " + ":DESCRIPTION; WHERE UUID = :UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; - public static final String DELETE_ACTION_ENDPOINT_PROPERTIES = "DELETE FROM IDN_ACTION_ENDPOINT WHERE " + + public static final String DELETE_ACTION_ENDPOINT_PROPERTIES = "DELETE FROM IDN_ACTION_PROPERTIES WHERE " + "ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String DELETE_ACTION = "DELETE FROM IDN_ACTION WHERE UUID = :UUID; AND TYPE = :TYPE;" + " AND TENANT_ID = :TENANT_ID;"; @@ -74,9 +74,6 @@ public static class Query { ":UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_COUNT_PER_ACTION_TYPE = "SELECT TYPE, COUNT(UUID) AS COUNT" + " FROM IDN_ACTION WHERE TENANT_ID = :TENANT_ID; GROUP BY TYPE"; - public static final String UPDATE_ACTION_ENDPOINT_PROPERTIES = "UPDATE IDN_ACTION_ENDPOINT SET " + - "PROPERTY_VALUE = :PROPERTY_VALUE; WHERE ACTION_UUID = :ACTION_UUID; AND " + - "TENANT_ID = :TENANT_ID; AND PROPERTY_NAME = :PROPERTY_NAME;"; private Query() { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql index 776921371a60..9bf8470be8e8 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql @@ -8,7 +8,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql index 99b5c560d56b..81f72be60ee2 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql @@ -2087,7 +2087,7 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ) / -CREATE TABLE IDN_ACTION_ENDPOINT ( +CREATE TABLE IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -2435,7 +2435,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); / -- XACML -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql index 78602660830e..9b84806ad5af 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql @@ -1366,7 +1366,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1609,7 +1609,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- XACML -- CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); CREATE INDEX IDX_POLICY_EDITOR_DATA_FK ON IDN_XACML_POLICY_EDITOR_DATA (POLICY_ID, VERSION, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql index 983b4213cf58..e6a4feda92ac 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql @@ -1514,8 +1514,8 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ); -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_ACTION_ENDPOINT]') AND TYPE in (N'U')) -CREATE TABLE IDN_ACTION_ENDPOINT ( +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_ACTION_PROPERTIES]') AND TYPE in (N'U')) +CREATE TABLE IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1770,7 +1770,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- XACML -- CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql index f79856f5220e..aa9ca6181f7e 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql @@ -1529,7 +1529,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) )ENGINE NDB; -CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1801,7 +1801,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- XACML -- CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql index 45642386c353..89319a62aa01 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql @@ -1397,7 +1397,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) )DEFAULT CHARACTER SET latin1 ENGINE INNODB; -CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1637,7 +1637,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- XACML -- CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql index 6ffa2eb13894..296fb4aa1874 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql @@ -2149,7 +2149,7 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ) / -CREATE TABLE IDN_ACTION_ENDPOINT ( +CREATE TABLE IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -2493,7 +2493,7 @@ CREATE INDEX IDX_CON_FILE_RES_ID ON IDN_CONFIG_FILE (RESOURCE_ID) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) / -- XACML -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql index 5bc4ad184d76..343ff0139294 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql @@ -2082,7 +2082,7 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ) / -CREATE TABLE IDN_ACTION_ENDPOINT ( +CREATE TABLE IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -2398,7 +2398,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) / -- XACML -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql index 3ac7225cb2d0..b7fed4a41894 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql @@ -1634,8 +1634,8 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -DROP TABLE IF EXISTS IDN_ACTION_ENDPOINT; -CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( +DROP TABLE IF EXISTS IDN_ACTION_PROPERTIES; +CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1898,7 +1898,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- XACML -- CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); From ab1bb18edaa9d42bbd276d0622da07b816378019 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 11 Nov 2024 02:39:18 +0530 Subject: [PATCH 07/34] Add jdbcTemplate.withTransaction for delete-secret and update-secret queries --- .../dao/impl/ActionManagementDAOImpl.java | 11 +++++--- .../mgt/core/dao/impl/SecretDAOImpl.java | 26 ++++++++++++------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 84c28ec4d267..34ded3675b1a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -560,11 +560,14 @@ private Map resolveEndpointAuthenticationProperties(String actio List resolvedAuthProperties = existingAuthentication.getProperties(); if (updatingAuthentication != null) { - // Delete existing secrets. - actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, actionId); - // Add new secrets. + if (resolvedAuthType != updatingAuthentication.getType()) { + // Delete existing secrets. + actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, actionId); + resolvedAuthType = updatingAuthentication.getType(); + } + + // Add new secrets or update existing secrets. resolvedAuthProperties = actionSecretProcessor.encryptAssociatedSecrets(updatingAuthentication, actionId); - resolvedAuthType = updatingAuthentication.getType(); } authentication.put(AUTHN_TYPE_PROPERTY, resolvedAuthType.getName()); diff --git a/components/secret-mgt/org.wso2.carbon.identity.secret.mgt.core/src/main/java/org/wso2/carbon/identity/secret/mgt/core/dao/impl/SecretDAOImpl.java b/components/secret-mgt/org.wso2.carbon.identity.secret.mgt.core/src/main/java/org/wso2/carbon/identity/secret/mgt/core/dao/impl/SecretDAOImpl.java index fe6adb91a790..f22352f0f108 100644 --- a/components/secret-mgt/org.wso2.carbon.identity.secret.mgt.core/src/main/java/org/wso2/carbon/identity/secret/mgt/core/dao/impl/SecretDAOImpl.java +++ b/components/secret-mgt/org.wso2.carbon.identity.secret.mgt.core/src/main/java/org/wso2/carbon/identity/secret/mgt/core/dao/impl/SecretDAOImpl.java @@ -212,12 +212,15 @@ public void deleteSecretByName(String name, String secretTypeId, int tenantId) t NamedJdbcTemplate jdbcTemplate = getNewTemplate(); try { - jdbcTemplate.executeUpdate(SQLConstants.DELETE_SECRET, preparedStatement -> { - preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_SECRET_NAME, name); - preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_TYPE, secretTypeId); - preparedStatement.setInt(DB_SCHEMA_COLUMN_NAME_TENANT_ID, tenantId); + jdbcTemplate.withTransaction(template -> { + template.executeUpdate(SQLConstants.DELETE_SECRET, preparedStatement -> { + preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_SECRET_NAME, name); + preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_TYPE, secretTypeId); + preparedStatement.setInt(DB_SCHEMA_COLUMN_NAME_TENANT_ID, tenantId); + }); + return null; }); - } catch (DataAccessException e) { + } catch (TransactionException e) { throw handleServerException(ERROR_CODE_DELETE_SECRET, e); } } @@ -282,14 +285,17 @@ public Secret updateSecretValue(Secret secret, String value) throws SecretManage Timestamp currentTime = new java.sql.Timestamp(new Date().getTime()); NamedJdbcTemplate jdbcTemplate = getNewTemplate(); try { - jdbcTemplate.executeUpdate(UPDATE_SECRET_VALUE, preparedStatement -> { - preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_ID, secret.getSecretId()); - preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_SECRET_VALUE, value); - preparedStatement.setTimeStamp(DB_SCHEMA_COLUMN_NAME_LAST_MODIFIED, currentTime, calendar); + jdbcTemplate.withTransaction(template -> { + template.executeUpdate(UPDATE_SECRET_VALUE, preparedStatement -> { + preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_ID, secret.getSecretId()); + preparedStatement.setString(DB_SCHEMA_COLUMN_NAME_SECRET_VALUE, value); + preparedStatement.setTimeStamp(DB_SCHEMA_COLUMN_NAME_LAST_MODIFIED, currentTime, calendar); + }); + return null; }); secret.setLastModified(currentTime.toInstant().toString()); secret.setSecretValue(value); - } catch (DataAccessException e) { + } catch (TransactionException e) { throw handleServerException(ERROR_CODE_UPDATE_SECRET, "value", e); } return secret; From f4b2f285153b9cecf16d2e9f4f7105c6f3d98936 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 11 Nov 2024 02:49:27 +0530 Subject: [PATCH 08/34] Fix sonarcloud suggestions --- .../ActionManagementServiceImplTest.java | 107 +++++++++--------- 1 file changed, 55 insertions(+), 52 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java index 3a8adda20c8e..a18308cd69ad 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java @@ -58,7 +58,7 @@ public class ActionManagementServiceImplTest { private ActionManagementService actionManagementService; - private Action action; + private Action preIssueAccessTokenAction; private Map secretProperties; @BeforeClass @@ -85,26 +85,28 @@ public void testAddAction() throws ActionMgtException, SecretManagementException "To configure PreIssueAccessToken", "https://example.com", TestUtil.buildMockBasicAuthentication("admin", "admin")); - action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); - Assert.assertNotNull(action.getId()); - Assert.assertEquals(creatingAction.getName(), action.getName()); - Assert.assertEquals(creatingAction.getDescription(), action.getDescription()); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); + preIssueAccessTokenAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, + TENANT_DOMAIN); + Assert.assertNotNull(preIssueAccessTokenAction.getId()); + Assert.assertEquals(creatingAction.getName(), preIssueAccessTokenAction.getName()); + Assert.assertEquals(creatingAction.getDescription(), preIssueAccessTokenAction.getDescription()); + Assert.assertEquals(Action.Status.ACTIVE, preIssueAccessTokenAction.getStatus()); Assert.assertEquals(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), - action.getType().getActionType()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), action.getEndpoint().getUri()); + preIssueAccessTokenAction.getType().getActionType()); + Assert.assertEquals(creatingAction.getEndpoint().getUri(), preIssueAccessTokenAction.getEndpoint().getUri()); Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - action.getEndpoint().getAuthentication().getType()); + preIssueAccessTokenAction.getEndpoint().getAuthentication().getType()); Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getProperties().size(), - action.getEndpoint().getAuthentication().getProperties().size()); + preIssueAccessTokenAction.getEndpoint().getAuthentication().getProperties().size()); Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getProperties().size(), - action.getEndpoint().getAuthentication().getPropertiesWithSecretReferences(action.getId()).size()); - secretProperties = mapActionAuthPropertiesWithSecrets(action); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), + preIssueAccessTokenAction.getEndpoint().getAuthentication().getPropertiesWithSecretReferences( + preIssueAccessTokenAction.getId()).size()); + secretProperties = mapActionAuthPropertiesWithSecrets(preIssueAccessTokenAction); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication() + .getProperty(Authentication.Property.USERNAME).getValue(), secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication() + .getProperty(Authentication.Property.PASSWORD).getValue(), secretProperties.get(Authentication.Property.PASSWORD.getName())); } @@ -141,7 +143,7 @@ public void testAddMaximumActionsPerType() throws ActionMgtException { "To configure PreIssueAccessToken", "https://example.com", TestUtil.buildMockBasicAuthentication("admin", "admin")); - action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, + preIssueAccessTokenAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); } @@ -152,13 +154,13 @@ public void testGetActionsByActionType() throws ActionMgtException, SecretManage TENANT_DOMAIN); Assert.assertEquals(1, actions.size()); for (Action result: actions) { - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType().getActionType(), result.getType().getActionType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); + Assert.assertEquals(preIssueAccessTokenAction.getName(), result.getName()); + Assert.assertEquals(preIssueAccessTokenAction.getDescription(), result.getDescription()); + Assert.assertEquals(preIssueAccessTokenAction.getType().getActionType(), result.getType().getActionType()); + Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); secretProperties = mapActionAuthPropertiesWithSecrets(result); Assert.assertEquals( @@ -173,15 +175,15 @@ public void testGetActionsByActionType() throws ActionMgtException, SecretManage @Test(priority = 6) public void testGetActionByActionId() throws ActionMgtException, SecretManagementException { - Action result = actionManagementService.getActionByActionId(action.getType().getPathParam(), action.getId(), - TENANT_DOMAIN); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Action result = actionManagementService.getActionByActionId(preIssueAccessTokenAction.getType().getPathParam(), + preIssueAccessTokenAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); + Assert.assertEquals(preIssueAccessTokenAction.getName(), result.getName()); + Assert.assertEquals(preIssueAccessTokenAction.getDescription(), result.getDescription()); + Assert.assertEquals(preIssueAccessTokenAction.getType(), result.getType()); + Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); secretProperties = mapActionAuthPropertiesWithSecrets(result); Assert.assertEquals( @@ -200,13 +202,13 @@ public void testGetActionsByActionTypeFromCache() throws ActionMgtException, Sec PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); Assert.assertEquals(1, actions.size()); Action result = actions.get(0); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); + Assert.assertEquals(preIssueAccessTokenAction.getName(), result.getName()); + Assert.assertEquals(preIssueAccessTokenAction.getDescription(), result.getDescription()); + Assert.assertEquals(preIssueAccessTokenAction.getType(), result.getType()); + Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getUri(), result.getEndpoint().getUri()); + Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication().getType(), result.getEndpoint().getAuthentication().getType()); secretProperties = mapActionAuthPropertiesWithSecrets(result); Assert.assertEquals( @@ -225,13 +227,13 @@ public void testUpdateAction() throws ActionMgtException, SecretManagementExcept "To update configuration pre issue access token", "https://sample.com", TestUtil.buildMockAPIKeyAuthentication("header", "value")); - Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), - updatingAction, TENANT_DOMAIN); - Assert.assertEquals(action.getId(), result.getId()); + Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + preIssueAccessTokenAction.getId(), updatingAction, TENANT_DOMAIN); + Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); Assert.assertEquals(updatingAction.getName(), result.getName()); Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); + Assert.assertEquals(preIssueAccessTokenAction.getType(), result.getType()); + Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); Assert.assertEquals( updatingAction.getEndpoint().getAuthentication().getType(), @@ -243,15 +245,15 @@ public void testUpdateAction() throws ActionMgtException, SecretManagementExcept Assert.assertEquals( result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), secretProperties.get(Authentication.Property.VALUE.getName())); - action = result; + preIssueAccessTokenAction = result; } @Test(priority = 9) public void testDeactivateAction() throws ActionMgtException { - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); + Assert.assertEquals(Action.Status.ACTIVE, preIssueAccessTokenAction.getStatus()); Action deactivatedAction = actionManagementService.deactivateAction( - PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), TENANT_DOMAIN); + PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), TENANT_DOMAIN); Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); } @@ -259,7 +261,7 @@ public void testDeactivateAction() throws ActionMgtException { public void testActivateAction() throws ActionMgtException { Action result = actionManagementService.activateAction( - PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), TENANT_DOMAIN); + PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), TENANT_DOMAIN); Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); } @@ -280,9 +282,10 @@ public void testGetActionsCountPerType() throws ActionMgtException { @Test(priority = 12) public void testDeleteAction() throws ActionMgtException { - actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, action.getId(), TENANT_DOMAIN); - Assert.assertNull(actionManagementService.getActionByActionId(action.getType().getPathParam(), action.getId(), - TENANT_DOMAIN)); + actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), + TENANT_DOMAIN); + Assert.assertNull(actionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, + preIssueAccessTokenAction.getId(), TENANT_DOMAIN)); Map actions = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); Assert.assertNull(actions.get(PRE_ISSUE_ACCESS_TOKEN_PATH)); } From 374b3416f6dd0ca0d28506fd3466a956d5b415a3 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 11 Nov 2024 02:56:49 +0530 Subject: [PATCH 09/34] Move errors defined to rest-api layer to service layer --- .../management/constant/ActionMgtConstants.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index 4df204ed55d5..118368b8cc58 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -57,6 +57,16 @@ public enum ErrorMessages { "%s is invalid."), ERROR_INVALID_ACTION_CERTIFICATE("60006", "Invalid request.", "Provided certificate is invalid."), + // Client errors thrown at REST API layer. + ERROR_INVALID_ACTION_ENDPOINT_AUTHENTICATION_PROPERTIES("60007", "Unable to perform the operation.", + "Required authentication properties are not provided or invalid."), + ERROR_INVALID_ACTION_ENDPOINT_AUTH_TYPE("60008", "Invalid Authentication Type for Action Endpoint.", + "Invalid authentication type used for path parameter."), + ERROR_EMPTY_ACTION_ENDPOINT_AUTHENTICATION_PROPERTIES("60009", "Unable to perform the operation.", + "Authentication property values cannot be empty."), + ERROR_NO_ACTION_FOUND_ON_GIVEN_ACTION_TYPE_AND_ID("60010", "Action is not found.", + "No action is found for given action id and action type"), + // Server errors. ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", "Error while persisting Action in the system."), @@ -98,7 +108,11 @@ public enum ErrorMessages { ERROR_WHILE_UPDATING_ACTION_CERTIFICATE("65017", "Error while updating action certificate.", "Error while updating certificate in the system."), ERROR_WHILE_DELETING_ACTION_CERTIFICATE("65018", "Error while deleting action certificate.", - "Error while deleting certificate from the system."); + "Error while deleting certificate from the system."), + + // Server errors thrown at REST API layer. + ERROR_NOT_IMPLEMENTED_ACTION_TYPE("650015", "Unable to perform the operation.", + "The requested action type is not currently supported by the server."); private final String code; private final String message; From fbb515ac2677d2505902b63151a8d2a328fec227 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 18 Nov 2024 17:07:33 +0530 Subject: [PATCH 10/34] Added updateEndpointAuthentication() public method to the service layer --- .../management/ActionManagementService.java | 14 +++++++++ .../ActionManagementServiceImpl.java | 29 ++++++++++++++++- .../ActionManagementServiceImplTest.java | 31 +++++++++++++++++++ .../action/management/util/TestUtil.java | 1 + 4 files changed, 74 insertions(+), 1 deletion(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java index fe3899c521a3..fe1851cb1b13 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java @@ -20,6 +20,7 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; import java.util.List; import java.util.Map; @@ -114,4 +115,17 @@ Action updateAction(String actionType, String actionId, Action action, String te * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. */ Action getActionByActionId(String actionType, String actionId, String tenantDomain) throws ActionMgtException; + + /** + * Update the authentication of the action endpoint. + * + * @param actionType Action Type. + * @param actionId Action ID. + * @param authentication Authentication Information to be updated. + * @param tenantDomain Tenant domain. + * @return Action response after update. + * @throws ActionMgtException If an error occurs while updating action endpoint authentication information. + */ + Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, + String tenantDomain) throws ActionMgtException; } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java index 632cfdd92ed9..5fc6258899f0 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java @@ -27,6 +27,7 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; import org.wso2.carbon.identity.action.management.util.ActionValidator; @@ -49,7 +50,6 @@ public class ActionManagementServiceImpl implements ActionManagementService { new CacheBackedActionMgtDAO(new ActionManagementDAOImpl()); private static final ActionValidator ACTION_VALIDATOR = new ActionValidator(); private static final ActionManagementAuditLogger auditLogger = new ActionManagementAuditLogger(); - private static final ActionSecretProcessor ACTION_SECRET_PROCESSOR = new ActionSecretProcessor(); private ActionManagementServiceImpl() { } @@ -236,6 +236,33 @@ public Action getActionByActionId(String actionType, String actionId, String ten IdentityTenantUtil.getTenantId(tenantDomain)); } + /** + * Update endpoint authentication of a given action. + * + * @param actionType Action type. + * @param actionId Action ID. + * @param authentication Authentication Information to be updated. + * @param tenantDomain Tenant domain. + * @return Updated action. + * @throws ActionMgtException if an error occurred while updating endpoint authentication information. + */ + @Override + public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, + String tenantDomain) throws ActionMgtException { + + String resolvedActionType = getActionTypeFromPath(actionType); + Action existingAction = checkIfActionExists(resolvedActionType, actionId, tenantDomain); + doEndpointAuthenticationValidation(authentication); + + Action updatingAction = new Action.ActionRequestBuilder() + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(authentication) + .build()) + .build(); + return CACHE_BACKED_DAO.updateAction(resolvedActionType, actionId, updatingAction, existingAction, + IdentityTenantUtil.getTenantId(tenantDomain)); + } + /** * Get Action Type from path. * diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java index a18308cd69ad..aab546f2b426 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java @@ -44,6 +44,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_PATH; +import static org.wso2.carbon.identity.action.management.util.TestUtil.SAMPLE_ACCESS_TOKEN; import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; /** @@ -280,6 +281,36 @@ public void testGetActionsCountPerType() throws ActionMgtException { } @Test(priority = 12) + public void testUpdateEndpointConfigWithSameAuthenticationType() throws ActionMgtException, + SecretManagementException { + + Authentication authentication = TestUtil.buildMockAPIKeyAuthentication("newheader", "newvalue"); + Action result = actionManagementService.updateActionEndpointAuthentication( + PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), authentication, TENANT_DOMAIN); + Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(authentication.getProperty(Authentication.Property.HEADER).getValue(), + result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); + secretProperties = mapActionAuthPropertiesWithSecrets(result); + Assert.assertEquals( + result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), + secretProperties.get(Authentication.Property.VALUE.getName())); + } + + @Test(priority = 13) + public void testUpdateEndpointConfigWithDifferentAuthenticationType() + throws ActionMgtException, SecretManagementException { + + Authentication authentication = TestUtil.buildMockBearerAuthentication(SAMPLE_ACCESS_TOKEN); + Action result = actionManagementService.updateActionEndpointAuthentication( + PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), authentication, TENANT_DOMAIN); + Assert.assertEquals(Authentication.Type.BEARER, result.getEndpoint().getAuthentication().getType()); + secretProperties = mapActionAuthPropertiesWithSecrets(result); + Assert.assertEquals( + result.getEndpoint().getAuthentication().getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + secretProperties.get(Authentication.Property.ACCESS_TOKEN.getName())); + } + + @Test(priority = 14) public void testDeleteAction() throws ActionMgtException { actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index e1be2e3fd1cc..aaa8a592ea48 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -43,6 +43,7 @@ public class TestUtil { public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); + public static final String SAMPLE_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; public static final String CERTIFICATE_ID = String.valueOf(UUID.randomUUID()); public static final String CERTIFICATE_NAME = "ACTIONS:" + PRE_UPDATE_PASSWORD_ACTION_ID; public static final String CERTIFICATE = "sample-certificate"; From fd27b27c873153deb3a4820aafc649f984968181 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Sat, 23 Nov 2024 02:27:21 +0530 Subject: [PATCH 11/34] Refactor action management with facade layer --- .../ActionExecutionServiceComponent.java | 2 +- ...ActionExecutionServiceComponentHolder.java | 2 +- .../impl/ActionExecutorServiceImplTest.java | 2 +- .../action/management/ActionBuilder.java | 68 ++ .../management/ActionPropertyResolver.java | 64 ++ .../constant/ActionMgtConstants.java | 105 -- .../constant/ActionMgtSQLConstants.java | 5 + .../constant/error/ErrorMessage.java | 87 ++ .../management/dao/ActionManagementDAO.java | 74 +- .../dao/impl/ActionManagementDAOFacade.java | 318 ++++++ .../dao/impl/ActionManagementDAOImpl.java | 941 ++++++------------ .../management/dao/model/ActionDTO.java | 238 +++++ .../exception/ActionMgtException.java | 5 +- .../exception/ActionMgtServerException.java | 4 +- ...a => ActionPropertyResolverException.java} | 14 +- .../factory/ActionBuilderFactory.java | 56 ++ .../ActionPropertyResolverFactory.java | 57 ++ .../internal/ActionMgtServiceComponent.java | 61 +- .../action/management/model/Action.java | 6 + .../management/model/Authentication.java | 2 +- .../ActionManagementService.java | 2 +- .../impl}/ActionManagementServiceImpl.java | 185 ++-- .../CacheBackedActionManagementService.java} | 98 +- .../management/util/ActionManagementUtil.java | 22 +- .../{ => util}/ActionSecretProcessor.java | 2 +- .../management/util/ActionValidator.java | 16 +- .../ActionManagementServiceImplTest.java | 2 + 27 files changed, 1508 insertions(+), 930 deletions(-) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/{ActionMgtRuntimeException.java => ActionPropertyResolverException.java} (64%) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{ => service}/ActionManagementService.java (98%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{ => service/impl}/ActionManagementServiceImpl.java (65%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{dao/impl/CacheBackedActionMgtDAO.java => service/impl/CacheBackedActionManagementService.java} (61%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{ => util}/ActionSecretProcessor.java (99%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java index 02e3efc2a81d..94c1e40a3719 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java @@ -34,7 +34,7 @@ import org.wso2.carbon.identity.action.execution.impl.ActionExecutionRequestBuilderFactory; import org.wso2.carbon.identity.action.execution.impl.ActionExecutionResponseProcessorFactory; import org.wso2.carbon.identity.action.execution.impl.ActionExecutorServiceImpl; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; /** * OSGI service component for the Action execution. diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java index 83be753ef413..8163a538354a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java @@ -18,7 +18,7 @@ package org.wso2.carbon.identity.action.execution.internal; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; /** * This class holds references for dependent services required for Action Execution Service to function. diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java index 5f1ece8a0c9e..4dc8a5033bca 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java @@ -60,7 +60,7 @@ import org.wso2.carbon.identity.action.execution.util.ActionExecutionDiagnosticLogger; import org.wso2.carbon.identity.action.execution.util.ActionExecutorConfig; import org.wso2.carbon.identity.action.execution.util.RequestFilter; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java new file mode 100644 index 000000000000..ddf09b32d971 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management; + +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.Action; + +/** + * This interface defines the Action Resolver. + * Action Resolver is the component that is responsible for the conversions between Action and ExtendedAction + * objects. + */ +public interface ActionBuilder { + + Action.ActionTypes getSupportedActionType(); + + /** + * Convert Action object into ActionDTO object. + * + * @param action Action object. + * @return ActionDTO object. + */ + default ActionDTO buildActionDTO(Action action) { + + return new ActionDTO.Builder() + .id(action.getId()) + .type(action.getType()) + .name(action.getName()) + .description(action.getDescription()) + .status(action.getStatus()) + .endpoint(action.getEndpoint()) + .properties(null) + .build(); + } + /** + * Convert ActionDTO object into Action object. + * + * @param actionDTO ActionDTO object. + * @return Action object. + */ + default Action buildAction(ActionDTO actionDTO) { + + return new Action.ActionResponseBuilder() + .id(actionDTO.getId()) + .type(actionDTO.getType()) + .name(actionDTO.getName()) + .description(actionDTO.getDescription()) + .status(actionDTO.getStatus()) + .endpoint(actionDTO.getEndpoint()) + .build(); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java new file mode 100644 index 000000000000..4f54a85892ee --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management; + +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; +import org.wso2.carbon.identity.action.management.model.Action; + +import java.util.Collections; +import java.util.Map; + +/** + * This interface defines the Action Property Resolver. + * Action Property Resolver is the component that is responsible for handling action type specific operations. + */ +public interface ActionPropertyResolver { + + Action.ActionTypes getSupportedActionType(); + + default Map addProperties(ActionDTO actionDTO, String tenantDomain) + throws ActionPropertyResolverException { + + return Collections.emptyMap(); + } + + default Map getProperties(ActionDTO actionDTO, String tenantDomain) + throws ActionPropertyResolverException { + + return null; + } + + default Map updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + String tenantDomain) throws ActionPropertyResolverException { + + return Collections.emptyMap(); + } + + default void deleteProperties(ActionDTO deletingActionDTO, String tenantDomain) + throws ActionPropertyResolverException { + } + + default void doPreAddActionPropertiesValidations(ActionDTO actionDTO) throws ActionMgtClientException { + } + + default void doPreUpdateActionPropertiesValidations(ActionDTO updatingActionDTO) throws ActionMgtClientException { + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index 118368b8cc58..2dc669ebfbdf 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -25,8 +25,6 @@ public class ActionMgtConstants { public static final String URI_PROPERTY = "uri"; public static final String AUTHN_TYPE_PROPERTY = "authnType"; - public static final String PASSWORD_SHARING_FORMAT_PROPERTY = "passwordSharingFormat"; - public static final String CERTIFICATE_ID_PROPERTY = "certificateId"; public static final String IDN_SECRET_TYPE_ACTION_SECRETS = "ACTION_API_ENDPOINT_AUTH_SECRETS"; public static final String ACTION_NAME_FIELD = "Action name"; @@ -37,107 +35,4 @@ public class ActionMgtConstants { public static final String ACCESS_TOKEN_FIELD = "Access token"; public static final String API_KEY_HEADER_FIELD = "API key header name"; public static final String API_KEY_VALUE_FIELD = "API key value"; - - /** - * Error messages. - */ - public enum ErrorMessages { - - // Client errors. - ERROR_INVALID_ACTION_TYPE("60001", "Invalid action type.", - "Invalid action type used for path parameter."), - ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED("60002", "Unable to create an Action.", - "Maximum number of actions per action type is reached."), - ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID("60003", - "Unable to perform the operation.", - "No Action is configured on the given Action Type and Id."), - ERROR_EMPTY_ACTION_REQUEST_FIELD("60004", "Invalid request.", - "%s is empty."), - ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", - "%s is invalid."), - ERROR_INVALID_ACTION_CERTIFICATE("60006", "Invalid request.", "Provided certificate is invalid."), - - // Client errors thrown at REST API layer. - ERROR_INVALID_ACTION_ENDPOINT_AUTHENTICATION_PROPERTIES("60007", "Unable to perform the operation.", - "Required authentication properties are not provided or invalid."), - ERROR_INVALID_ACTION_ENDPOINT_AUTH_TYPE("60008", "Invalid Authentication Type for Action Endpoint.", - "Invalid authentication type used for path parameter."), - ERROR_EMPTY_ACTION_ENDPOINT_AUTHENTICATION_PROPERTIES("60009", "Unable to perform the operation.", - "Authentication property values cannot be empty."), - ERROR_NO_ACTION_FOUND_ON_GIVEN_ACTION_TYPE_AND_ID("60010", "Action is not found.", - "No action is found for given action id and action type"), - - // Server errors. - ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", - "Error while persisting Action in the system."), - ERROR_WHILE_ADDING_ACTION_PROPERTIES("65002", "Error while adding Action properties", - "Error while persisting Action properties in the system."), - ERROR_WHILE_RETRIEVING_ACTION_PROPERTIES("65003", - "Error while retrieving Action properties", - "Error while retrieving Action properties from the system."), - ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE("65004", - "Error while retrieving Actions by Action Type", - "Error while retrieving Actions by Action Type from the system."), - ERROR_WHILE_UPDATING_ACTION_PROPERTIES("65005", - "Error while updating Action Endpoint properties", - "Error while updating Action Endpoint properties in the system."), - ERROR_WHILE_UPDATING_ACTION("65006", "Error while updating Action.", - "Error while updating Action in the system."), - ERROR_WHILE_DELETING_ACTION("65007", "Error while deleting Action.", - "Error while deleting Action from the system."), - ERROR_WHILE_UPDATING_ACTION_STATUS("65008", "Error while updating Action status.", - "Error while updating Action status in the system."), - ERROR_WHILE_RETRIEVING_ACTION_BY_ID("65009", "Error while retrieving Action by ID.", - "Error while retrieving Action from the system."), - ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE("65010", - "Error while retrieving count of Actions per Action Type.", - "Error while retrieving count of Actions per Action Type from the system."), - ERROR_WHILE_RETRIEVING_ACTION_BASIC_INFO("65011", "Error while retrieving Action basic info.", - "Error while retrieving Action basic info from the system."), - ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES("65012", - "Error while decrypting Action Endpoint Authentication properties", - "Error while decrypting Action Endpoint Authentication properties in the system."), - ERROR_WHILE_UPDATING_ACTION_BASIC_INFO("65013", "Error while updating basic Action information", - "Error while updating basic Action information in the system."), - ERROR_WHILE_BUILDING_ACTION_RESPONSE("65014", "Error while building Action response.", - "Error while building Action response object."), - ERROR_WHILE_ADDING_ACTION_CERTIFICATE("65015", "Error while adding action certificate.", - "Error while persisting certificate in the system."), - ERROR_WHILE_RETRIEVING_ACTION_CERTIFICATE("65016", "Error while retrieving action certificate.", - "Error while retrieving certificate from the system."), - ERROR_WHILE_UPDATING_ACTION_CERTIFICATE("65017", "Error while updating action certificate.", - "Error while updating certificate in the system."), - ERROR_WHILE_DELETING_ACTION_CERTIFICATE("65018", "Error while deleting action certificate.", - "Error while deleting certificate from the system."), - - // Server errors thrown at REST API layer. - ERROR_NOT_IMPLEMENTED_ACTION_TYPE("650015", "Unable to perform the operation.", - "The requested action type is not currently supported by the server."); - - private final String code; - private final String message; - private final String description; - - ErrorMessages(String code, String message, String description) { - - this.code = code; - this.message = message; - this.description = description; - } - - public String getCode() { - - return code; - } - - public String getMessage() { - - return message; - } - - public String getDescription() { - - return description; - } - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java index 21a19098c941..38f97e330a1a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java @@ -68,12 +68,17 @@ public static class Query { ":DESCRIPTION; WHERE UUID = :UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String DELETE_ACTION_ENDPOINT_PROPERTIES = "DELETE FROM IDN_ACTION_PROPERTIES WHERE " + "ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; + public static final String DELETE_ACTION_PROPERTY = "DELETE FROM IDN_ACTION_PROPERTIES WHERE " + + "PROPERTY_NAME = :PROPERTY_NAME; AND ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String DELETE_ACTION = "DELETE FROM IDN_ACTION WHERE UUID = :UUID; AND TYPE = :TYPE;" + " AND TENANT_ID = :TENANT_ID;"; public static final String CHANGE_ACTION_STATUS = "UPDATE IDN_ACTION SET STATUS = :STATUS; WHERE UUID = " + ":UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_COUNT_PER_ACTION_TYPE = "SELECT TYPE, COUNT(UUID) AS COUNT" + " FROM IDN_ACTION WHERE TENANT_ID = :TENANT_ID; GROUP BY TYPE"; + public static final String UPDATE_ACTION_PROPERTIES = "UPDATE IDN_ACTION_PROPERTIES SET " + + "PROPERTY_VALUE = :PROPERTY_VALUE; WHERE ACTION_UUID = :ACTION_UUID; AND " + + "TENANT_ID = :TENANT_ID; AND PROPERTY_NAME = :PROPERTY_NAME;"; private Query() { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java new file mode 100644 index 000000000000..11e370f1d8d7 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.constant.error; + +/** + * Error messages. + */ +public enum ErrorMessage { + + // Client errors. + ERROR_INVALID_ACTION_TYPE("60001", "Invalid action type.", + "Invalid action type used for path parameter."), + ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED("60002", "Unable to create an Action.", + "Maximum number of actions per action type is reached."), + ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID("60003", + "Unable to perform the operation.", + "No Action is configured on the given Action Type and Id."), + ERROR_EMPTY_ACTION_REQUEST_FIELD("60004", "Invalid request.", + "%s is empty."), + ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", + "%s is invalid."), + + // Server errors. + ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", + "Error while persisting Action in the system."), + ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE("65002", + "Error while retrieving Actions by Action Type", + "Error while retrieving Actions by Action Type from the system."), + ERROR_WHILE_RETRIEVING_ACTION_BY_ID("65003", "Error while retrieving Action by ID.", + "Error while retrieving Action from the system."), + ERROR_WHILE_UPDATING_ACTION("65004", "Error while updating Action.", + "Error while updating Action in the system."), + ERROR_WHILE_DELETING_ACTION("65005", "Error while deleting Action.", + "Error while deleting Action from the system."), + ERROR_WHILE_ACTIVATING_ACTION("65006", "Error while activating Action.", + "Error while updating Action status to ACTIVE."), + ERROR_WHILE_DEACTIVATING_ACTION("65007", "Error while deactivating Action.", + "Error while updating Action status to INACTIVE."), + ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE("65008", + "Error while retrieving count of Actions per Action Type.", + "Error while retrieving count of Actions per Action Type from the system."), + ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES("65009", + "Error while decrypting Action Endpoint Authentication properties", + "Error while decrypting Action Endpoint Authentication properties in the system."); + + private final String code; + private final String message; + private final String description; + + ErrorMessage(String code, String message, String description) { + + this.code = code; + this.message = message; + this.description = description; + } + + public String getCode() { + + return code; + } + + public String getMessage() { + + return message; + } + + public String getDescription() { + + return description; + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java index ecb131d1adf6..4680886cd859 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java @@ -18,28 +18,25 @@ package org.wso2.carbon.identity.action.management.dao; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.model.Action; import java.util.List; import java.util.Map; /** - * This interface performs CRUD operations for {@link Action}. + * This interface performs CRUD operations for {@link ActionDTO}. */ public interface ActionManagementDAO { /** - * Create a new {@link Action}. + * Create a new {@link ActionDTO}. * - * @param actionType Action Type. - * @param actionId Action Id. - * @param action Action creation model. - * @param tenantId Tenant Id. - * @return Created Action. + * @param actionDTO Action creation model. + * @param tenantId Tenant Id. * @throws ActionMgtException If an error occurs while adding the Action. */ - Action addAction(String actionType, String actionId, Action action, Integer tenantId) throws ActionMgtException; + void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException; /** * Retrieve the Actions configured for the given type. @@ -49,46 +46,51 @@ public interface ActionManagementDAO { * @return List of Action. * @throws ActionMgtException If an error occurs while retrieving the Actions of a given Action Type. */ - List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException; + List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException; /** - * Update {@link Action} by given Action type and Action ID. + * Get {@link ActionDTO} of a given Action Type and Action ID. * - * @param actionType Action Type. - * @param actionId Action ID. - * @param updatingAction Action update model. - * @param existingAction Existing Action. - * @param tenantId Tenant Id. - * @return Updated Action. + * @param actionId Action ID. + * @param tenantId Tenant Id. + * @return Action. + * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. + */ + ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException; + + /** + * Update {@link ActionDTO} by given Action type and Action ID. + * + * @param updatingActionDTO Action update model. + * @param existingActionDTO Existing Action. + * @param tenantId Tenant Id. * @throws ActionMgtException If an error occurs while updating the Action. */ - Action updateAction(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException; + void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException; /** - * Delete {@link Action} by given Action Type. + * Delete {@link ActionDTO} by given Action Type. * - * @param actionType Action Type. - * @param actionId Action Id. - * @param action Action to be deleted. - * @param tenantId Tenant Id. + * @param deletingActionDTO Action to be deleted. + * @param tenantId Tenant Id. * @throws ActionMgtException If an error occurs while deleting Action. */ - void deleteAction(String actionType, String actionId, Action action, Integer tenantId) throws ActionMgtException; + void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtException; /** - * Activate {@link Action} by given Action Type and Action ID. + * Activate {@link org.wso2.carbon.identity.action.management.model.Action} by given Action Type and Action ID. * - * @param actionType Action Type. - * @param actionId Action ID. + * @param actionType Action Type. + * @param actionId Action ID. * @param tenantId Tenant Id. * @return Activated Action. * @throws ActionMgtException If an error occurs while activating the Action. */ - Action activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; + ActionDTO activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; /** - * Deactivate {@link Action} by given Action Type and Action ID. + * Deactivate {@link org.wso2.carbon.identity.action.management.model.Action} by given Action Type and Action ID. * * @param actionType Action Type. * @param actionId Action ID. @@ -96,7 +98,7 @@ Action updateAction(String actionType, String actionId, Action updatingAction, A * @return Deactivated Action. * @throws ActionMgtException If an error occurs while deactivating the Action. */ - Action deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; + ActionDTO deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; /** * Get Actions count per Action Type. @@ -106,14 +108,4 @@ Action updateAction(String actionType, String actionId, Action updatingAction, A * @throws ActionMgtException If an error occurs while retrieving the Actions count. */ Map getActionsCountPerType(Integer tenantId) throws ActionMgtException; - - /** - * Get {@link Action} of a given Action Type and Action ID. - * - * @param actionId Action ID. - * @param tenantId Tenant Id. - * @return Action. - * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. - */ - Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException; } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java new file mode 100644 index 000000000000..520c52b04c4b --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -0,0 +1,318 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; +import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; +import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; +import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; +import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.AuthProperty; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; +import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Facade class for Action Management DAO. + * ActionManagementDAOFacade is responsible for handling external service integrations. + */ +public class ActionManagementDAOFacade implements ActionManagementDAO { + + private static final Log LOG = LogFactory.getLog(ActionManagementDAOFacade.class); + + private final ActionManagementDAO actionManagementDAO; + private final ActionSecretProcessor actionSecretProcessor; + + public ActionManagementDAOFacade(ActionManagementDAO actionManagementDAO) { + + this.actionManagementDAO = actionManagementDAO; + this.actionSecretProcessor = new ActionSecretProcessor(); + } + + @Override + public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + // Encrypt authentication secrets + encryptAuthenticationSecrets(actionDTO); + // Resolve action properties + addProperties(actionDTO, tenantId); + + actionManagementDAO.addAction(actionDTO, tenantId); + return null; + }); + } catch (TransactionException e) { + LOG.debug("Error while creating the Action of Action Type: " + actionDTO.getType().getDisplayName() + + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + + ". Rolling back created action information, authentication secrets and action properties."); + throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_ADDING_ACTION, e); + } + } + + @Override + public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { + + try { + List actionDTOS = actionManagementDAO.getActionsByActionType(actionType, tenantId); + getPropertiesOfActionDTOs(actionType, actionDTOS, tenantId); + + return actionDTOS; + } catch (ActionMgtException e) { + throw ActionManagementUtil.handleServerException( + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); + } + } + + @Override + public ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) + throws ActionMgtException { + + try { + ActionDTO actionDTO = actionManagementDAO.getActionByActionId(actionType, actionId, tenantId); + // Resolve action properties + getProperties(actionDTO, tenantId); + + return actionDTO; + } catch (ActionMgtException e) { + throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); + } + } + + @Override + public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + // Encrypt authentication secrets + updateAuthenticationSecrets(updatingActionDTO, existingActionDTO); + // Resolve action properties + updateProperties(updatingActionDTO, existingActionDTO, tenantId); + + actionManagementDAO.updateAction(updatingActionDTO, existingActionDTO, tenantId); + return null; + }); + } catch (TransactionException e) { + LOG.debug("Error while updating the Action of Action Type: " + + updatingActionDTO.getType().getDisplayName() + " and Action ID: " + updatingActionDTO.getId() + + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + + ". Rolling back updated action information"); + throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_UPDATING_ACTION, e); + } + } + + @Override + public void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + actionManagementDAO.deleteAction(deletingActionDTO, tenantId); + // Encrypt authentication secrets + deleteAuthenticationSecrets(deletingActionDTO); + // Resolve action properties + deleteProperties(deletingActionDTO, tenantId); + + return null; + }); + } catch (TransactionException e) { + LOG.debug("Error while deleting the Action of Action Type: " + + deletingActionDTO.getType().getDisplayName() + " and Action ID: " + deletingActionDTO.getId() + + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + + ". Rolling back deleted action information"); + throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_DELETING_ACTION, e); + } + } + + @Override + public ActionDTO activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + + try { + return actionManagementDAO.activateAction(actionType, actionId, tenantId); + } catch (ActionMgtException e) { + throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_ACTIVATING_ACTION, e); + } + } + + @Override + public ActionDTO deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + + try { + return actionManagementDAO.deactivateAction(actionType, actionId, tenantId); + } catch (ActionMgtException e) { + throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_DEACTIVATING_ACTION, e); + } + } + + @Override + public Map getActionsCountPerType(Integer tenantId) throws ActionMgtException { + + return actionManagementDAO.getActionsCountPerType(tenantId); + } + + private void encryptAuthenticationSecrets(ActionDTO actionDTO) throws ActionMgtException { + + try { + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets( + actionDTO.getEndpoint().getAuthentication(), actionDTO.getId()); + actionDTO.setAuthenticationProperties(encryptedProperties); + } catch (SecretManagementException e) { + throw new ActionMgtServerException("Error while encrypting Action Endpoint Authentication Secrets.", e); + } + } + + private void updateAuthenticationSecrets(ActionDTO updatingActionDTO, ActionDTO existingActionDTO) + throws ActionMgtException { + + if (updatingActionDTO.getEndpoint() == null || updatingActionDTO.getEndpoint().getAuthentication() == null) { + return; + } + + Authentication updatingAuthentication = updatingActionDTO.getEndpoint().getAuthentication(); + Authentication existingAuthentication = existingActionDTO.getEndpoint().getAuthentication(); + + try { + if (updatingAuthentication.getType() != existingAuthentication.getType()) { + actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, existingActionDTO.getId()); + } + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets( + updatingAuthentication, updatingActionDTO.getId()); + updatingActionDTO.setAuthenticationProperties(encryptedProperties); + } catch (SecretManagementException e) { + throw new ActionMgtServerException("Error while updating Action Endpoint Authentication Secrets.", e); + } + } + + private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws ActionMgtServerException { + + try { + actionSecretProcessor.deleteAssociatedSecrets(deletingActionDTO.getEndpoint().getAuthentication(), + deletingActionDTO.getId()); + } catch (SecretManagementException e) { + throw new ActionMgtServerException("Error while deleting Action Endpoint Authentication Secrets.", e); + } + } + + private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + Map properties = null; + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); + try { + if (actionPropertyResolver != null) { + properties = actionPropertyResolver.addProperties(actionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + if (properties != null) { + actionDTO.setProperties(properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + } + } catch (ActionPropertyResolverException e) { + throw new ActionMgtServerException("Failed to resolve Add Action properties for Action Type: " + + actionDTO.getType().getDisplayName(), e); + } + } + + private void getPropertiesOfActionDTOs(String actionType, List actionDTOS, Integer tenantId) + throws ActionMgtException { + + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver( + org.wso2.carbon.identity.action.management.model.Action.ActionTypes.valueOf(actionType)); + if (actionPropertyResolver == null) { + return; + } + + try { + for (ActionDTO actionDTO : actionDTOS) { + actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, + IdentityTenantUtil.getTenantDomain(tenantId))); + } + } catch (ActionPropertyResolverException e) { + throw new ActionMgtServerException("Error while resolving Properties of Actions of Action Type: " + + Action.ActionTypes.valueOf(actionType).getDisplayName(), e); + } + } + + private void getProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); + try { + if (actionPropertyResolver != null) { + actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, + IdentityTenantUtil.getTenantDomain(tenantId))); + } + } catch (ActionPropertyResolverException e) { + throw new ActionMgtServerException("Failed to fetch Action properties for Action Type: " + + actionDTO.getType().getDisplayName(), e); + } + } + + private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtServerException { + + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver(updatingActionDTO.getType()); + try { + if (actionPropertyResolver != null) { + Map properties = actionPropertyResolver.updateProperties(updatingActionDTO, + existingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + updatingActionDTO.setProperties(properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + } + } catch (ActionPropertyResolverException e) { + throw new ActionMgtServerException("Failed to resolve Update Action properties for Action Type: " + + updatingActionDTO.getType().getDisplayName(), e); + } + } + + private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtServerException { + + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver(deletingActionDTO.getType()); + try { + if (actionPropertyResolver != null) { + actionPropertyResolver.deleteProperties(deletingActionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + } catch (ActionPropertyResolverException e) { + throw new ActionMgtServerException("Failed to delete Action properties for Action Type: " + + deletingActionDTO.getType().getDisplayName(), e); + } + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 34ded3675b1a..db58bc07b0b5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -18,42 +18,34 @@ package org.wso2.carbon.identity.action.management.dao.impl; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; +import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; import org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException; import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; -import org.wso2.carbon.identity.action.management.ActionSecretProcessor; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.constant.ActionMgtSQLConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; -import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtRuntimeException; -import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; -import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtClientException; -import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtException; -import org.wso2.carbon.identity.certificate.management.model.Certificate; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.AUTHN_TYPE_PROPERTY; -import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.CERTIFICATE_ID_PROPERTY; -import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.PASSWORD_SHARING_FORMAT_PROPERTY; import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.URI_PROPERTY; /** @@ -61,162 +53,109 @@ */ public class ActionManagementDAOImpl implements ActionManagementDAO { - private static final Log LOG = LogFactory.getLog(ActionManagementDAOImpl.class); - private final ActionSecretProcessor actionSecretProcessor; - public ActionManagementDAOImpl() { + } - this.actionSecretProcessor = new ActionSecretProcessor(); + @Override + public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + // Add action basic information. + addBasicInfo(actionDTO, tenantId); + // Add action endpoint. + addEndpoint(actionDTO, tenantId); + // Add action properties. + addProperties(actionDTO, tenantId); } @Override - public Action addAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { + public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - template.executeInsert(ActionMgtSQLConstants.Query.ADD_ACTION_TO_ACTION_TYPE, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, action.getName()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, action.getDescription()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, - String.valueOf(Action.Status.ACTIVE)); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }, action, false); + List actionDTOS = new ArrayList<>(); + try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(false); + NamedPreparedStatement statement = new NamedPreparedStatement(dbConnection, + ActionMgtSQLConstants.Query.GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE)) { - // Add action properties. - addActionProperties(actionType, actionId, action, tenantId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - return null; - }); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + String actionId = rs.getString(ActionMgtSQLConstants.Column.ACTION_UUID); - return getActionByActionId(actionType, actionId, tenantId); - } catch (TransactionException e) { - if (e.getCause() instanceof ActionMgtClientException) { - throw (ActionMgtClientException) e.getCause(); - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while creating the Action of Action Type: %s in Tenant Domain: %s." + - " Rolling back created action information and deleting added secrets.", actionType, - IdentityTenantUtil.getTenantDomain(tenantId))); + ActionDTO.Builder actionBuilder = new ActionDTO.Builder() + .id(actionId) + .type(org.wso2.carbon.identity.action.management.model.Action.ActionTypes.valueOf( + rs.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) + .name(rs.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) + .description(rs.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) + .status(org.wso2.carbon.identity.action.management.model.Action.Status.valueOf( + rs.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))); + actionBuilder.setEndpointAndProperties(getActionPropertiesFromDB(actionId, tenantId)); + + actionDTOS.add(actionBuilder.build()); + } } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION, e); + + return actionDTOS; + } catch (SQLException e) { + throw new ActionMgtServerException("Error while retrieving Actions Basic information by Action Type.", e); } } @Override - public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { - - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - List actions = new ArrayList<>(); - try { - jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE, - (resultSet, rowNumber) -> { - String actionId = resultSet.getString(ActionMgtSQLConstants.Column.ACTION_UUID); - Action actionBasicInfo = new Action.ActionResponseBuilder() - .id(actionId) - .type(Action.ActionTypes - .valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) - .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) - .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) - .status(Action.Status.valueOf( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) - .build(); - - Map actionProperties = getActionPropertiesById(actionId, tenantId); - actions.add(buildActionResponse(actionType, actionBasicInfo, actionProperties, tenantId)); - return null; - }, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + public ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) + throws ActionMgtException { - return actions; - } catch (ActionMgtRuntimeException | DataAccessException e) { - /** - * Handling {@link ActionMgtRuntimeException}, which is intentionally thrown to represent underlying - * exceptions from the {@link #buildActionResponse(String, Action, Map, Integer)} method. - */ - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); + ActionDTO.Builder actionBuilder = getBasicInfo(actionType, actionId, tenantId); + if (actionBuilder == null) { + return null; } + actionBuilder.setEndpointAndProperties(getActionPropertiesFromDB(actionId, tenantId)); + + return actionBuilder.build(); } @Override - public Action updateAction(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { - - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - // Update Basic Info. - updateBasicInfo(actionType, actionId, updatingAction, existingAction, tenantId); - // Update Action Properties. - updateActionProperties(actionType, actionId, updatingAction, existingAction, tenantId); - - return null; - }); + public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException { - return getActionByActionId(actionType, actionId, tenantId); - } catch (TransactionException e) { - if (e.getCause() instanceof ActionMgtClientException) { - throw (ActionMgtClientException) e.getCause(); - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action of Action Type: %s and Action ID: %s in" + - " Tenant Domain: %s. Rolling back updated action information.", actionType, actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION, e); - } + // Update action basic information. + updateBasicInfo(updatingActionDTO, existingActionDTO, tenantId); + // Update Action Endpoint. + updateEndpoint(updatingActionDTO, existingActionDTO, tenantId); + // Update Action Properties. + updateProperties(updatingActionDTO, existingActionDTO, tenantId); } @Override - public void deleteAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { + public void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { jdbcTemplate.withTransaction(template -> { template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION, statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, deletingActionDTO.getId()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, + deletingActionDTO.getType().getActionType()); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); - // Delete action endpoint authentication related secrets. - actionSecretProcessor.deleteAssociatedSecrets(action.getEndpoint().getAuthentication(), actionId); - // Delete action type specific properties. - deleteActionTypeSpecificProperties(actionType, action, tenantId); return null; }); } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while deleting the Action of Action Type: %s and Action ID: %s in" + - " Tenant Domain: %s. Rolling back deleted action information.", actionType, actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_DELETING_ACTION, e); + throw new ActionMgtServerException("Error while deleting Action.", e); } } @Override - public Action activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public ActionDTO activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { return changeActionStatus(actionType, actionId, String.valueOf(Action.Status.ACTIVE), tenantId); - } @Override - public Action deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public ActionDTO deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { return changeActionStatus(actionType, actionId, String.valueOf(Action.Status.INACTIVE), tenantId); } @@ -236,622 +175,346 @@ public Map getActionsCountPerType(Integer tenantId) throws Acti return actionTypesCountMap; } catch (DataAccessException e) { throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); } } - @Override - public Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + private void addBasicInfo(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - Action action = getActionBasicInfoById(actionType, actionId, tenantId); - if (action != null) { - Map actionProperties = getActionPropertiesById(actionId, tenantId); - action = buildActionResponse(actionType, action, actionProperties, tenantId); - } - - return action; - } catch (ActionMgtException | ActionMgtRuntimeException | SQLException e) { - /** - * Handling {@link ActionMgtRuntimeException}, which is intentionally thrown to represent underlying - * exceptions from the {@link #buildActionResponse(String, Action, Map, Integer)} method. - */ - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); + jdbcTemplate.withTransaction(template -> { + template.executeInsert(ActionMgtSQLConstants.Query.ADD_ACTION_TO_ACTION_TYPE, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionDTO.getId()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, + actionDTO.getType().getActionType()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, actionDTO.getName()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, + actionDTO.getDescription()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, + String.valueOf( + org.wso2.carbon.identity.action.management.model.Action.Status.ACTIVE)); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }, actionDTO, false); + return null; + }); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while adding Action Basic information.", e); } } /** - * Add Action properties. + * Update the basic information of an {@link ActionDTO} by given Action ID. * - * @param actionType Type of the Action. - * @param actionId UUID of the created Action. - * @param action Properties of the Action. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while adding action properties to the database. + * @param updatingActionDTO Information to be updated. + * @param existingActionDTO Existing Action information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating the Action basic information. */ - private void addActionProperties(String actionType, String actionId, Action action, - Integer tenantId) throws ActionMgtException { + private void updateBasicInfo(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException { - try { - Map actionProperties = - resolveActionTypeSpecificProperties(actionType, actionId, action, null, tenantId); - - EndpointConfig endpoint = action.getEndpoint(); - // Encrypt the authentication secrets. - List authProperties = - actionSecretProcessor.encryptAssociatedSecrets(endpoint.getAuthentication(), actionId); - - actionProperties.put(URI_PROPERTY, endpoint.getUri()); - actionProperties.put(AUTHN_TYPE_PROPERTY, endpoint.getAuthentication().getType().name()); - authProperties.forEach(authProperty -> actionProperties.put(authProperty.getName(), - authProperty.getValue())); - - addActionPropertiesToDB(actionId, actionProperties, tenantId); - } catch (ActionMgtClientException e) { - throw e; - } catch (ActionMgtException | SecretManagementException | TransactionException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION_PROPERTIES, e); + if (updatingActionDTO.getName() == null && updatingActionDTO.getDescription() == null) { + return; } - } - - /** - * Add Action properties to the Database. - * - * @param actionId UUID of the created Action. - * @param actionProperties Properties of the Action. - * @param tenantId Tenant ID. - * @throws TransactionException If an error occurs while persisting action properties to the database. - */ - private void addActionPropertiesToDB(String actionId, Map actionProperties, Integer tenantId) - throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT_PROPERTIES, - statement -> { - for (Map.Entry property : actionProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, - property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, - property.getValue()); - statement.addBatch(); - } - }, null); - return null; - }); - } - - /** - * Update the properties of an {@link Action} by given Action ID. - * - * @param actionId Action ID. - * @param updatingAction Information to be updated. - * @param existingAction Existing Action information. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action properties. - */ - private void updateActionProperties(String actionType, String actionId, Action updatingAction, - Action existingAction, Integer tenantId) throws ActionMgtException { - try { - Map actionProperties = resolveEndpointProperties(actionId, updatingAction, existingAction); - actionProperties.putAll(resolveActionTypeSpecificProperties(actionType, actionId, updatingAction, - existingAction, tenantId)); - - updateActionPropertiesInDB(actionId, actionProperties, tenantId); - } catch (ActionMgtClientException e) { - throw e; - } catch (ActionMgtException | SecretManagementException | TransactionException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_PROPERTIES, e); + jdbcTemplate.executeUpdate(ActionMgtSQLConstants.Query.UPDATE_ACTION_BASIC_INFO, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, updatingActionDTO.getName() == null ? + existingActionDTO.getName() : updatingActionDTO.getName()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, + updatingActionDTO.getDescription() == null ? existingActionDTO.getDescription() + : updatingActionDTO.getDescription()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, updatingActionDTO.getId()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, + updatingActionDTO.getType().getActionType()); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }); + } catch (DataAccessException e) { + throw new ActionMgtServerException("Error while updating Action Basic information.", e); } } - /** - * Update the basic information of an {@link Action} by given Action ID. - * - * @param actionId UUID of the created Action. - * @param updatingProperties Action properties to be updated. - * @param tenantId Tenant ID. - * @throws TransactionException If an error occurs while updating the Action properties. - */ - private void updateActionPropertiesInDB(String actionId, Map updatingProperties, - Integer tenantId) throws TransactionException { - - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - jdbcTemplate.withTransaction(template -> { - template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTIES, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - - // Add updated action properties. - addActionPropertiesToDB(actionId, updatingProperties, tenantId); - return null; - }); - } - /** * Get Action Basic Info by Action ID. * - * @param actionId UUID of the created Action. - * @param tenantId Tenant ID. - * @return Action Basic Info. + * @param actionId UUID of the created Action. + * @param tenantId Tenant ID. + * @return Action Response Builder with action basic information. * @throws ActionMgtException If an error occurs while retrieving action basic info from the database. */ - private Action getActionBasicInfoById(String actionType, String actionId, Integer tenantId) + private ActionDTO.Builder getBasicInfo(String actionType, String actionId, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { return jdbcTemplate.fetchSingleRecord(ActionMgtSQLConstants.Query.GET_ACTION_BASIC_INFO_BY_ID, - (resultSet, rowNumber) -> new Action.ActionResponseBuilder() + (resultSet, rowNumber) -> new ActionDTO.Builder() .id(actionId) .type(Action.ActionTypes.valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) - .status(Action.Status.valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) - .build(), - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + .status(Action.Status.valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))), + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BASIC_INFO, e); + throw new ActionMgtServerException("Error while retrieving Action Basic information.", e); } } - /** - * Get Action properties by ID. - * - * @param actionId UUID of the created Action. - * @param tenantId Tenant ID. - * @return A map of action properties, including any additional data based on action type. - * @throws SQLException If an error occurs while retrieving action properties from the database. - */ - private Map getActionPropertiesById(String actionId, Integer tenantId) - throws SQLException { + private void addEndpoint(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - Map actionEndpointProperties = new HashMap<>(); + EndpointConfig endpoint = actionDTO.getEndpoint(); + Map endpointProperties = new HashMap<>(); try { - jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_ENDPOINT_INFO_BY_ID, - (resultSet, rowNumber) -> { - actionEndpointProperties.put( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME), - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE)); - return null; - }, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + endpointProperties.put(URI_PROPERTY, endpoint.getUri()); + endpointProperties.put(AUTHN_TYPE_PROPERTY, endpoint.getAuthentication().getType().name()); + endpoint.getAuthentication().getProperties().forEach( + authProperty -> endpointProperties.put(authProperty.getName(), authProperty.getValue())); - return actionEndpointProperties; - } catch (DataAccessException e) { - throw new SQLException(ActionMgtConstants.ErrorMessages - .ERROR_WHILE_RETRIEVING_ACTION_PROPERTIES.getMessage(), e); + addActionPropertiesToDB(actionDTO.getId(), endpointProperties, tenantId); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while adding Action Endpoint configurations.", e); } } - /** - * Update Action Status. - * - * @param actionType Action Type. - * @param actionId UUID of the Action. - * @param status Action status to be updated. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action status. - */ - private Action changeActionStatus(String actionType, String actionId, String status, Integer tenantId) - throws ActionMgtException { + private void updateEndpoint(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtServerException { + + EndpointConfig updatingEndpoint = updatingActionDTO.getEndpoint(); + if (updatingEndpoint == null) { + return; + } - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - jdbcTemplate.executeUpdate(ActionMgtSQLConstants.Query.CHANGE_ACTION_STATUS, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, status); - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + if (updatingEndpoint.getUri() != null) { + updateActionPropertiesInDB(updatingActionDTO.getId(), + Collections.singletonMap(URI_PROPERTY, updatingEndpoint.getUri()), tenantId); + } - return getActionBasicInfoById(actionType, actionId, tenantId); - } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_STATUS, e); + updateEndpointAuthentication(updatingActionDTO.getId(), updatingEndpoint.getAuthentication(), + existingActionDTO.getEndpoint().getAuthentication(), tenantId); + } catch (ActionMgtException | TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Endpoint.", e); } } - /** - * Update the basic information of an {@link Action} by given Action ID. - * - * @param actionType Action Type. - * @param actionId Action ID. - * @param updatingAction Information to be updated. - * @param existingAction Existing Action information. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action basic information. - */ - private void updateBasicInfo(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { + private void updateEndpointAuthentication(String actionId, Authentication updatingAuthentication, + Authentication existingAuthentication, Integer tenantId) + throws ActionMgtException { - if (updatingAction.getName() == null && updatingAction.getDescription() == null) { + if (updatingAuthentication == null) { return; } - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - jdbcTemplate.executeUpdate(ActionMgtSQLConstants.Query.UPDATE_ACTION_BASIC_INFO, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, - updatingAction.getName() == null ? existingAction.getName() : updatingAction.getName()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, - updatingAction.getDescription() == null ? existingAction.getDescription() - : updatingAction.getDescription()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_BASIC_INFO, e); + if (updatingAuthentication.getType() == existingAuthentication.getType()) { + updateAuthentication(actionId, updatingAuthentication, tenantId); + } else { + // Delete existing authentication configurations. + deleteAuthentication(actionId, existingAuthentication, tenantId); + // Add new authentication configurations. + addAuthentication(actionId, updatingAuthentication, tenantId); + } + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Endpoint Authentication.", e); } } - /** - * Resolves the endpoint properties for an action when action is updating. - * This method ensures that authentication secrets are handled appropriately, and the URI is resolved - * based on the provided or existing endpoint configurations. - * When the updating action does not contain endpoint configuration, it uses the existing endpoint's properties. - * - * @param actionId Action ID. - * @param updatingAction Action to update. - * @param existingAction Existing Action. - * @return A map containing the resolved endpoint properties to be stored. - * @throws SecretManagementException If an error occurs while updating the authentication secrets. - */ - private Map resolveEndpointProperties(String actionId, Action updatingAction, Action existingAction) - throws SecretManagementException { - - EndpointConfig updatingEndpoint = updatingAction.getEndpoint(); - EndpointConfig existingEndpoint = existingAction.getEndpoint(); - - Map resolvedEndpointProperties = - resolveEndpointAuthenticationProperties(actionId, updatingEndpoint, existingEndpoint); + private void addAuthentication(String actionId, Authentication updatingAuthentication, Integer tenantId) + throws TransactionException { - if (updatingEndpoint != null && updatingEndpoint.getUri() != null) { - resolvedEndpointProperties.put(URI_PROPERTY, updatingEndpoint.getUri()); - } else { - resolvedEndpointProperties.put(URI_PROPERTY, existingEndpoint.getUri()); - } + Map authenticationProperties = updatingAuthentication.getProperties().stream() + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + authenticationProperties.put(AUTHN_TYPE_PROPERTY, updatingAuthentication.getType().name()); - return resolvedEndpointProperties; + addActionPropertiesToDB(actionId, authenticationProperties, tenantId); } - /** - * Resolves the authentication properties for an endpoint when action is updating. - * This deletes existing secrets and updates them with new properties as necessary. - * When the updating endpoint does not contain authentication, it uses the existing endpoint's properties. - * - * @param actionId Action ID. - * @param updatingEndpoint Endpoint configurations to be updated. - * @param existingEndpoint Existing Endpoint configurations. - * @return A map containing the resolved endpoint authentication properties to be stored. - * @throws SecretManagementException If an error occurs while updating the authentication secrets. - */ - private Map resolveEndpointAuthenticationProperties(String actionId, - EndpointConfig updatingEndpoint, - EndpointConfig existingEndpoint) - throws SecretManagementException { - - Authentication updatingAuthentication = updatingEndpoint != null ? updatingEndpoint.getAuthentication() : null; - Authentication existingAuthentication = existingEndpoint.getAuthentication(); - - Map authentication = new HashMap<>(); - Authentication.Type resolvedAuthType = existingAuthentication.getType(); - List resolvedAuthProperties = existingAuthentication.getProperties(); - - if (updatingAuthentication != null) { - if (resolvedAuthType != updatingAuthentication.getType()) { - // Delete existing secrets. - actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, actionId); - resolvedAuthType = updatingAuthentication.getType(); - } - - // Add new secrets or update existing secrets. - resolvedAuthProperties = actionSecretProcessor.encryptAssociatedSecrets(updatingAuthentication, actionId); - } + private void deleteAuthentication(String actionId, Authentication existingAuthentication, Integer tenantId) + throws TransactionException { - authentication.put(AUTHN_TYPE_PROPERTY, resolvedAuthType.getName()); - resolvedAuthProperties.forEach(property -> authentication.put(property.getName(), property.getValue())); + List deletingProperties = existingAuthentication.getProperties().stream() + .map(AuthProperty::getName) + .collect(Collectors.toList()); + deletingProperties.add(AUTHN_TYPE_PROPERTY); - return authentication; + deleteActionPropertiesInDB(actionId, deletingProperties, tenantId); } - /** - * Resolve the action type specific properties for creating or updating an action. - * - * @param actionType Action Type. - * @param actionId Action ID. - * @param inputAction A map containing the properties for the new or updated action. - * @param existingAction A map containing the existing properties. - * @param tenantId Tenant ID. - * @return A map containing the resolved action type specific properties. - * @throws ActionMgtException If an error occurs while handling action type specific properties. - */ - private Map resolveActionTypeSpecificProperties(String actionType, String actionId, - Action inputAction, - Action existingAction, - Integer tenantId) throws ActionMgtException { - - Map actionTypeSpecificProperties = new HashMap<>(); - switch (Action.ActionTypes.valueOf(actionType)) { - case PRE_UPDATE_PASSWORD: - PreUpdatePasswordAction inputPreUpdatePasswordAction = (PreUpdatePasswordAction) inputAction; - PreUpdatePasswordAction existingPreUpdatePasswordAction = (PreUpdatePasswordAction) existingAction; - - if (inputPreUpdatePasswordAction.getPasswordSharingFormat() != null) { - actionTypeSpecificProperties.put(PASSWORD_SHARING_FORMAT_PROPERTY, - inputPreUpdatePasswordAction.getPasswordSharingFormat().name()); - } else { - actionTypeSpecificProperties.put(PASSWORD_SHARING_FORMAT_PROPERTY, - existingPreUpdatePasswordAction.getPasswordSharingFormat().name()); - } - - // Handle certificate changes. - String certificateId = handleCertificateChanges(actionId, inputPreUpdatePasswordAction, - existingPreUpdatePasswordAction, tenantId); - if (StringUtils.isNotEmpty(certificateId)) { - actionTypeSpecificProperties.put(CERTIFICATE_ID_PROPERTY, certificateId); - } - - break; - case PRE_ISSUE_ACCESS_TOKEN: - default: - break; - } + private void updateAuthentication(String actionId, Authentication updatingAuthentication, Integer tenantId) + throws TransactionException { - return actionTypeSpecificProperties; + Map nonSecretAuthenticationProperties = updatingAuthentication.getProperties().stream() + .filter(property -> !property.getIsConfidential()) + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + // Update non-secret endpoint properties. + updateActionPropertiesInDB(actionId, nonSecretAuthenticationProperties, tenantId); } - /** - * Deletes action type-specific properties associated with the provided action. - * - * @param actionType Type of the Action. - * @param action Action information. - * @param tenantId Tenant Id. - * @throws ActionMgtException If an error occurs while deleting action type specific properties. - */ - private void deleteActionTypeSpecificProperties(String actionType, Action action, Integer tenantId) - throws ActionMgtException { + private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { - switch (Action.ActionTypes.valueOf(actionType)) { - case PRE_UPDATE_PASSWORD: - Certificate certificate = ((PreUpdatePasswordAction) action).getCertificate(); - if (certificate != null) { - deleteCertificate(certificate.getId(), tenantId); - } - break; - case PRE_ISSUE_ACCESS_TOKEN: - default: - break; + Map actionProperties = actionDTO.getProperties().entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue())); + try { + addActionPropertiesToDB(actionDTO.getId(), actionProperties, tenantId); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while adding Action Properties.", e); } } - /** - * Updates the certificate associated with an action based on the provided updating properties. - * If a new certificate is provided, it persists the certificate and returns its ID. - * If the existing certificate is being removed (empty value), it deletes the certificate and returns null. - * If the existing certificate is being updated, it updates the certificate and returns its existing ID. - * - * @param actionId Action ID. - * @param inputAction A map containing the properties to update, including the certificate. - * @param existingAction A map containing the existing properties, including the current certificate ID. - * @param tenantId Tenant ID. - * @return The updated certificate ID, or null if the certificate was deleted. - * @throws ActionMgtException If an error occurs while updating the certificate. - */ - private String handleCertificateChanges(String actionId, PreUpdatePasswordAction inputAction, - PreUpdatePasswordAction existingAction, Integer tenantId) - throws ActionMgtException { + private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + Integer tenantId) throws ActionMgtException { - String inputCertificate = inputAction.getCertificate() != null ? - inputAction.getCertificate().getCertificateContent() : null; - String certificateId = existingAction != null && existingAction.getCertificate() != null - ? existingAction.getCertificate().getId() : null; - - if (inputCertificate != null) { - if (StringUtils.isEmpty(certificateId)) { - // Add the new certificate. - certificateId = addCertificate(actionId, inputCertificate, tenantId); - } else if (inputCertificate.isEmpty()) { - // Delete the existing certificate. - deleteCertificate(certificateId, tenantId); - certificateId = null; - } else { - // Update the existing certificate. - updateCertificate(certificateId, inputCertificate, tenantId); - } + Map updatingProperties = updatingActionDTO.getProperties().entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue())); + try { + // Delete existing properties. + deleteActionPropertiesInDB(updatingActionDTO.getId(), + new ArrayList<>(existingActionDTO.getProperties().keySet()), tenantId); + // Add updated properties. + addActionPropertiesToDB(updatingActionDTO.getId(), updatingProperties, tenantId); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Properties.", e); } - - return certificateId; } /** - * Add the certificate in the database. + * Add Action properties to the Database. * - * @param actionId UUID of the created Action. - * @param certificateContent Certificate to be added. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while adding the certificate. - * @returns Certificate ID. + * @param actionId UUID of the created Action. + * @param actionProperties Properties of the Action. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while persisting action properties to the database. */ - private String addCertificate(String actionId, String certificateContent, Integer tenantId) - throws ActionMgtException { - try { - Certificate certificate = new Certificate.Builder() - .name("ACTIONS:" + actionId) - .certificateContent(certificateContent) - .build(); - return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .addCertificate(certificate, IdentityTenantUtil.getTenantDomain(tenantId)); - } catch (CertificateMgtClientException e) { - throw ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE, e); - } catch (CertificateMgtException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION_CERTIFICATE, e); - } + private void addActionPropertiesToDB(String actionId, Map actionProperties, Integer tenantId) + throws TransactionException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + jdbcTemplate.withTransaction(template -> { + template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT_PROPERTIES, + statement -> { + for (Map.Entry property : actionProperties.entrySet()) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + property.getKey()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, + property.getValue()); + statement.addBatch(); + } + }, null); + return null; + }); } /** - * Get the certificate content by certificate ID. + * Get Action properties by ID. * - * @param certificateId Certificate ID. - * @param tenantId Tenant ID. - * @return Certificate information. - * @throws ActionMgtException If an error occurs while retrieving the certificate from the database. + * @param actionId UUID of the created Action. + * @param tenantId Tenant ID. + * @return A map of action properties, including any additional data based on action type. + * @throws ActionMgtException If an error occurs while retrieving action properties from the database. */ - private Certificate getCertificate(String certificateId, Integer tenantId) - throws ActionMgtException { + private Map getActionPropertiesFromDB(String actionId, Integer tenantId) throws ActionMgtException { + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + Map actionEndpointProperties = new HashMap<>(); try { - return ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .getCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); - } catch (CertificateMgtException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_CERTIFICATE, e); + jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_ENDPOINT_INFO_BY_ID, + (resultSet, rowNumber) -> { + actionEndpointProperties.put( + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME), + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE)); + return null; + }, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }); + + return actionEndpointProperties; + } catch (DataAccessException e) { + throw new ActionMgtServerException("Error while retrieving Action Properties.", e); } } /** - * Update the certificate by certificate ID. + * Update the given property of an {@link ActionDTO} by given Action ID. * - * @param certificateId Certificate ID. - * @param updatingCertificate Certificate to be updated. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the certificate in the database. + * @param actionId UUID of the created Action. + * @param updatingProperties Action properties to be updated. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while updating the Action properties. */ - private void updateCertificate(String certificateId, String updatingCertificate, Integer tenantId) - throws ActionMgtException { + private void updateActionPropertiesInDB(String actionId, Map updatingProperties, + Integer tenantId) throws TransactionException { - try { - ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .updateCertificateContent(certificateId, updatingCertificate, - IdentityTenantUtil.getTenantDomain(tenantId)); - } catch (CertificateMgtClientException e) { - throw ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE, e); - } catch (CertificateMgtException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_CERTIFICATE, e); - } + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + jdbcTemplate.withTransaction(template -> + template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_PROPERTIES, + statement -> { + for (Map.Entry property : updatingProperties.entrySet()) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, + property.getValue()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + property.getKey()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.addBatch(); + } + }, null)); } - /** - * Delete the certificate by certificate ID. - * - * @param certificateId Certificate ID. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while deleting the certificate in the database. - */ - private void deleteCertificate(String certificateId, Integer tenantId) throws ActionMgtException { + private void deleteActionPropertiesInDB(String actionId, List deletingProperties, Integer tenantId) + throws TransactionException { - try { - ActionMgtServiceComponentHolder.getInstance().getCertificateManagementService() - .deleteCertificate(certificateId, IdentityTenantUtil.getTenantDomain(tenantId)); - } catch (CertificateMgtException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_DELETING_ACTION_CERTIFICATE, e); - } + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + jdbcTemplate.withTransaction(template -> + template.executeBatchInsert(ActionMgtSQLConstants.Query.DELETE_ACTION_PROPERTY, + statement -> { + for (String property : deletingProperties) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + property); + statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.addBatch(); + } + }, null)); } /** - * Build the Action Response Object according to the actionType. + * Update Action Status. * - * @param actionType Action Type. - * @param action Action basic information. - * @param actionProperties Action Properties. - * @param tenantId Tenant Id. - * @return Action Response. - * @throws ActionMgtRuntimeException If an error occurs while retrieving the certificate. + * @param actionType Action Type. + * @param actionId UUID of the Action. + * @param status Action status to be updated. + * @param tenantId Tenant ID. + * @return Updated ActionDTO with basic information. + * @throws ActionMgtException If an error occurs while updating the Action status. */ - private Action buildActionResponse(String actionType, Action action, Map actionProperties, - Integer tenantId) { + private ActionDTO changeActionStatus(String actionType, String actionId, String status, Integer tenantId) + throws ActionMgtException { - Action.ActionResponseBuilder actionResponseBuilder; + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - switch (Action.ActionTypes.valueOf(actionType)) { - case PRE_UPDATE_PASSWORD: - Certificate certificate = actionProperties.get(CERTIFICATE_ID_PROPERTY) != null ? - getCertificate(actionProperties.get(CERTIFICATE_ID_PROPERTY), tenantId) : null; - - actionResponseBuilder = new PreUpdatePasswordAction.ResponseBuilder() - .certificate(certificate) - .passwordSharingFormat(PreUpdatePasswordAction.PasswordFormat.valueOf( - actionProperties.get(PASSWORD_SHARING_FORMAT_PROPERTY))); - break; - case PRE_ISSUE_ACCESS_TOKEN: - default: - actionResponseBuilder = new Action.ActionResponseBuilder(); - break; - } - - Authentication authentication = null; - Authentication.Type authnType = - Authentication.Type.valueOf(actionProperties.get(ActionMgtConstants.AUTHN_TYPE_PROPERTY)); - switch (authnType) { - case BASIC: - authentication = new Authentication.BasicAuthBuilder( - actionProperties.get(Authentication.Property.USERNAME.getName()), - actionProperties.get(Authentication.Property.PASSWORD.getName())).build(); - break; - case BEARER: - authentication = new Authentication.BearerAuthBuilder( - actionProperties.get(Authentication.Property.ACCESS_TOKEN.getName())).build(); - break; - case API_KEY: - authentication = new Authentication.APIKeyAuthBuilder( - actionProperties.get(Authentication.Property.HEADER.getName()), - actionProperties.get(Authentication.Property.VALUE.getName())).build(); - break; - case NONE: - authentication = new Authentication.NoneAuthBuilder().build(); - break; - default: - break; - } + jdbcTemplate.executeUpdate(ActionMgtSQLConstants.Query.CHANGE_ACTION_STATUS, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, status); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }); - EndpointConfig endpointConfig = new EndpointConfig.EndpointConfigBuilder() - .uri(actionProperties.get(ActionMgtConstants.URI_PROPERTY)) - .authentication(authentication) - .build(); - - return actionResponseBuilder - .id(action.getId()) - .type(Action.ActionTypes.valueOf(actionType)) - .name(action.getName()) - .description(action.getDescription()) - .status(action.getStatus()) - .endpoint(endpointConfig) - .build(); - } catch (ActionMgtException e) { - /** - * Throwing a runtime exception because {@link ActionMgtException} is not handled in - * {@link org.wso2.carbon.database.utils.jdbc.RowMapper} of {@link NamedJdbcTemplate#executeQuery(String, - * org.wso2.carbon.database.utils.jdbc.RowMapper,org.wso2.carbon.database.utils.jdbc.NamedQueryFilter)} - * in {@link #getActionsByActionType(String, Integer)} - */ - throw ActionManagementUtil.handleRuntimeException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_BUILDING_ACTION_RESPONSE.getMessage(), e); + return getBasicInfo(actionType, actionId, tenantId).build(); + } catch (DataAccessException e) { + throw new ActionMgtServerException("Error while updating Action Status to " + status, e); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java new file mode 100644 index 000000000000..5b2fd029c89b --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.dao.model; + +import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.AuthProperty; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Action Data Transfer Object. + */ +public class ActionDTO { + + private String id; + private Action.ActionTypes type; + private final String name; + private final String description; + private final Action.Status status; + private EndpointConfig endpoint; + private Map properties; + + public ActionDTO(Builder builder) { + + this.id = builder.id; + this.type = builder.type; + this.name = builder.name; + this.description = builder.description; + this.status = builder.status; + this.endpoint = builder.endpoint; + this.properties = builder.properties; + } + + public void setId(String id) { + + this.id = id; + } + + public String getId() { + + return id; + } + + public void setType(Action.ActionTypes type) { + + this.type = type; + } + + public Action.ActionTypes getType() { + + return type; + } + + public String getName() { + + return name; + } + + public String getDescription() { + + return description; + } + + public org.wso2.carbon.identity.action.management.model.Action.Status getStatus() { + + return status; + } + + public EndpointConfig getEndpoint() { + + return endpoint; + } + + public void setAuthenticationProperties(List authProperties) { + + if (this.endpoint != null && this.endpoint.getAuthentication() != null) { + Map propertyMap = authProperties.stream() + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + + this.endpoint = new EndpointConfig.EndpointConfigBuilder() + .uri(this.endpoint.getUri()) + .authentication(new Authentication.AuthenticationBuilder() + .type(this.endpoint.getAuthentication().getType()) + .properties(propertyMap) + .build()) + .build(); + } + } + + public void setProperties(Map properties) { + + this.properties = properties; + } + + public Map getProperties() { + + return properties; + } + + public Object getProperty(String propertyName) { + + if (properties == null) { + return null; + } + + return properties.get(propertyName); + } + + /** + * Builder for Extended Action. + */ + public static class Builder { + + private String id; + private Action.ActionTypes type; + private String name; + private String description; + private Action.Status status; + private EndpointConfig endpoint; + private Map properties; + + public Builder id(String id) { + + this.id = id; + return this; + } + + public Builder type(Action.ActionTypes type) { + + this.type = type; + return this; + } + + public Builder name(String name) { + + this.name = name; + return this; + } + + public Builder description(String description) { + + this.description = description; + return this; + } + + public Builder status(Action.Status status) { + + this.status = status; + return this; + } + + public Builder endpoint(EndpointConfig endpoint) { + + this.endpoint = endpoint; + return this; + } + + public void setEndpointAndProperties(Map properties) throws ActionMgtException { + + Authentication authentication; + Authentication.Type authnType = + Authentication.Type.valueOf(properties.remove(ActionMgtConstants.AUTHN_TYPE_PROPERTY)); + switch (authnType) { + case BASIC: + authentication = new Authentication.BasicAuthBuilder( + properties.remove(Authentication.Property.USERNAME.getName()), + properties.remove(Authentication.Property.PASSWORD.getName())).build(); + break; + case BEARER: + authentication = new Authentication.BearerAuthBuilder( + properties.remove(Authentication.Property.ACCESS_TOKEN.getName())).build(); + break; + case API_KEY: + authentication = new Authentication.APIKeyAuthBuilder( + properties.remove(Authentication.Property.HEADER.getName()), + properties.remove(Authentication.Property.VALUE.getName())).build(); + break; + case NONE: + authentication = new Authentication.NoneAuthBuilder().build(); + break; + default: + throw new ActionMgtServerException("Authentication type is not defined for the Action Endpoint."); + } + + this.endpoint = new EndpointConfig.EndpointConfigBuilder() + .uri(properties.remove(ActionMgtConstants.URI_PROPERTY)) + .authentication(authentication) + .build(); + // Add remaining properties as action properties. + this.properties = properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + public Builder properties(Map properties) { + + this.properties = properties; + return this; + } + + public Builder property(String propertyName, String propertyValue) { + + if (this.properties == null) { + this.properties = Collections.emptyMap(); + } + this.properties.put(propertyName, propertyValue); + return this; + } + + public ActionDTO build() { + + return new ActionDTO(this); + } + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java index 4b922602e35c..6d987f39d273 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java @@ -31,10 +31,9 @@ public ActionMgtException(String message) { super(message); } - public ActionMgtException(String message, String errorCode) { + public ActionMgtException(String message, Throwable cause) { - super(message); - this.errorCode = errorCode; + super(message, cause); } public ActionMgtException(String message, String errorCode, Throwable cause) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java index 3692b83eae40..a1b9a95309ca 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java @@ -23,9 +23,9 @@ */ public class ActionMgtServerException extends ActionMgtException { - public ActionMgtServerException(String message, String errorCode) { + public ActionMgtServerException(String message, Throwable cause) { - super(message, errorCode); + super(message, cause); } public ActionMgtServerException(String message, String description, String errorCode) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtRuntimeException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java similarity index 64% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtRuntimeException.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java index 778c8b90544e..f8801dcc5efb 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtRuntimeException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java @@ -19,12 +19,18 @@ package org.wso2.carbon.identity.action.management.exception; /** - * Runtime exception class for Action Management. + * Exception class for Action Resolver. + * This exception is thrown when there is an issue in performing action type specific operations. */ -public class ActionMgtRuntimeException extends RuntimeException { +public class ActionPropertyResolverException extends Exception { - public ActionMgtRuntimeException(String message, Throwable e) { + public ActionPropertyResolverException(String message) { - super(message, e); + super(message); + } + + public ActionPropertyResolverException(String message, Throwable cause) { + + super(message, cause); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java new file mode 100644 index 000000000000..278990f35a55 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.factory; + +import org.wso2.carbon.identity.action.management.ActionBuilder; +import org.wso2.carbon.identity.action.management.model.Action; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class defines the Action Object Builder Factory. + * Action Object Builder Factory is the component that is responsible for providing the {@link ActionBuilder} + * based on the action type. + */ +public class ActionBuilderFactory { + + private static final Map actionObjectBuilders = new HashMap<>(); + + public static ActionBuilder getActionBuilder(Action.ActionTypes actionType) { + + switch (actionType) { + case PRE_UPDATE_PASSWORD: + return actionObjectBuilders.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); + case PRE_ISSUE_ACCESS_TOKEN: + default: + return null; + } + } + + public static void registerActionBuilder(ActionBuilder actionBuilder) { + + actionObjectBuilders.put(actionBuilder.getSupportedActionType(), actionBuilder); + } + + public static void unregisterActionBuilder(ActionBuilder actionBuilder) { + + actionObjectBuilders.remove(actionBuilder.getSupportedActionType()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java new file mode 100644 index 000000000000..acd35e7c0914 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.factory; + +import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.model.Action; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class defines the Action Property Resolver Factory. + * Action Property Resolver Factory is the component that is responsible for providing the + * {@link ActionPropertyResolver} based on the action type. + */ +public class ActionPropertyResolverFactory { + + private static final Map actionPropertyResolvers = new HashMap<>(); + + public static ActionPropertyResolver getActionPropertyResolver(Action.ActionTypes actionType) { + + switch (actionType) { + case PRE_UPDATE_PASSWORD: + return actionPropertyResolvers.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); + case PRE_ISSUE_ACCESS_TOKEN: + return actionPropertyResolvers.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); + default: + return null; + } + } + + public static void registerActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + + actionPropertyResolvers.put(actionPropertyResolver.getSupportedActionType(), actionPropertyResolver); + } + + public static void unregisterActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + + actionPropertyResolvers.remove(actionPropertyResolver.getSupportedActionType()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index ff34ec5b3259..57b8b1417100 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -28,8 +28,12 @@ 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.action.management.ActionManagementService; -import org.wso2.carbon.identity.action.management.ActionManagementServiceImpl; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.ActionBuilder; +import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; +import org.wso2.carbon.identity.action.management.factory.ActionBuilderFactory; +import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -50,7 +54,8 @@ protected void activate(ComponentContext context) { try { BundleContext bundleCtx = context.getBundleContext(); - bundleCtx.registerService(ActionManagementService.class, ActionManagementServiceImpl.getInstance(), null); + bundleCtx.registerService(ActionManagementService.class, CacheBackedActionManagementService.getInstance(), + null); LOG.debug("Action management bundle is activated"); } catch (Throwable e) { LOG.error("Error while initializing Action management component.", e); @@ -69,6 +74,56 @@ protected void deactivate(ComponentContext context) { } } + @Reference( + name = "action.builder", + service = ActionBuilder.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetActionBuilder" + ) + protected void setActionBuilder(ActionBuilder actionBuilder) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Registering ActionBuilder: " + actionBuilder.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + ActionBuilderFactory.registerActionBuilder(actionBuilder); + } + + protected void unsetActionBuilder(ActionBuilder actionBuilder) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Unregistering ActionBuilder: " + actionBuilder.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + ActionBuilderFactory.unregisterActionBuilder(actionBuilder); + } + + @Reference( + name = "action.property.resolver", + service = ActionPropertyResolver.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetActionPropertyResolver" + ) + protected void setActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Registering ActionPropertyResolver: " + actionPropertyResolver.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + ActionPropertyResolverFactory.registerActionPropertyResolver(actionPropertyResolver); + } + + protected void unsetActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Unregistering ActionPropertyResolver: " + actionPropertyResolver.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + ActionPropertyResolverFactory.unregisterActionPropertyResolver(actionPropertyResolver); + } + @Reference( name = "org.wso2.carbon.identity.secret.mgt.core.SecretManager", service = SecretManager.class, diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java index dc1f3030bf47..9cc7dfe40052 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java @@ -19,6 +19,7 @@ package org.wso2.carbon.identity.action.management.model; import java.util.Arrays; +import java.util.Map; /** * Action. @@ -182,6 +183,11 @@ public EndpointConfig getEndpoint() { return endpointConfig; } + public Map getProperties() { + + return null; + } + /** * ActionResponseBuilder. */ diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java index 5608107befc7..1a8dfd99ffdb 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java @@ -20,7 +20,7 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.action.management.ActionSecretProcessor; +import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionManagementService.java similarity index 98% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionManagementService.java index fe1851cb1b13..62b121127510 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionManagementService.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java similarity index 65% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index 5fc6258899f0..3977ed844551 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -16,18 +16,25 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.ActionBuilder; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; -import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; -import org.wso2.carbon.identity.action.management.dao.impl.CacheBackedActionMgtDAO; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; +import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.factory.ActionBuilderFactory; +import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; import org.wso2.carbon.identity.action.management.util.ActionValidator; @@ -38,6 +45,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; /** * Action management service. @@ -45,18 +53,14 @@ public class ActionManagementServiceImpl implements ActionManagementService { private static final Log LOG = LogFactory.getLog(ActionManagementServiceImpl.class); - private static final ActionManagementService INSTANCE = new ActionManagementServiceImpl(); - private static final CacheBackedActionMgtDAO CACHE_BACKED_DAO = - new CacheBackedActionMgtDAO(new ActionManagementDAOImpl()); private static final ActionValidator ACTION_VALIDATOR = new ActionValidator(); private static final ActionManagementAuditLogger auditLogger = new ActionManagementAuditLogger(); - private ActionManagementServiceImpl() { - } + private final ActionManagementDAOFacade daoFacade; - public static ActionManagementService getInstance() { + public ActionManagementServiceImpl(ActionManagementDAO actionManagementDAO) { - return INSTANCE; + this.daoFacade = new ActionManagementDAOFacade(actionManagementDAO); } /** @@ -77,11 +81,14 @@ public Action addAction(String actionType, Action action, String tenantDomain) t String resolvedActionType = getActionTypeFromPath(actionType); // Check whether the maximum allowed actions per type is reached. validateMaxActionsPerType(resolvedActionType, tenantDomain); - doPreAddActionValidations(action); String generatedActionId = UUID.randomUUID().toString(); - Action createdAction = CACHE_BACKED_DAO.addAction(resolvedActionType, generatedActionId, action, - IdentityTenantUtil.getTenantId(tenantDomain)); + ActionDTO resolvedActionDTO = buildActionDTO(actionType, generatedActionId, action); + doPreAddActionValidations(actionType, resolvedActionDTO); + + daoFacade.addAction(resolvedActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + Action createdAction = getActionByActionId(actionType, generatedActionId, tenantDomain); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ADD, createdAction); + return createdAction; } @@ -99,8 +106,12 @@ public List getActionsByActionType(String actionType, String tenantDomai if (LOG.isDebugEnabled()) { LOG.debug(String.format("Retrieving Actions for Action Type: %s.", actionType)); } - return CACHE_BACKED_DAO.getActionsByActionType(getActionTypeFromPath(actionType), + List actionDTOS = daoFacade.getActionsByActionType(getActionTypeFromPath(actionType), IdentityTenantUtil.getTenantId(tenantDomain)); + + return actionDTOS.stream() + .map(actionDTO -> buildAction(actionType, actionDTO)) + .collect(Collectors.toList()); } /** @@ -124,12 +135,13 @@ public Action updateAction(String actionType, String actionId, Action action, St LOG.debug(String.format("Updating Action for Action Type: %s and Action ID: %s.", actionType, actionId)); } String resolvedActionType = getActionTypeFromPath(actionType); - Action existingAction = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - doPreUpdateActionValidations(action); - Action updatedAction = CACHE_BACKED_DAO.updateAction(resolvedActionType, actionId, action, existingAction, - IdentityTenantUtil.getTenantId(tenantDomain)); + ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); + ActionDTO updatingActionDTO = buildActionDTO(actionType, actionId, action); + doPreUpdateActionValidations(actionType, updatingActionDTO); + + daoFacade.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, action); - return updatedAction; + return getActionByActionId(actionType, actionId, tenantDomain); } /** @@ -147,9 +159,8 @@ public void deleteAction(String actionType, String actionId, String tenantDomain LOG.debug(String.format("Deleting Action for Action Type: %s and Action ID: %s", actionType, actionId)); } String resolvedActionType = getActionTypeFromPath(actionType); - Action action = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - CACHE_BACKED_DAO.deleteAction(resolvedActionType, actionId, action, - IdentityTenantUtil.getTenantId(tenantDomain)); + ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); + daoFacade.deleteAction(existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DELETE, actionType, actionId); } @@ -160,7 +171,7 @@ public void deleteAction(String actionType, String actionId, String tenantDomain * @param actionId Action ID. * @param tenantDomain Tenant domain. * @return Activated action. - * @throws ActionMgtException if an error occurred while activating the action. + * @throws ActionMgtException If an error occurred while activating the action. */ @Override public Action activateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { @@ -170,10 +181,10 @@ public Action activateAction(String actionType, String actionId, String tenantDo } String resolvedActionType = getActionTypeFromPath(actionType); checkIfActionExists(resolvedActionType, actionId, tenantDomain); - Action activatedAction = CACHE_BACKED_DAO.activateAction(resolvedActionType, actionId, + ActionDTO activatedActionDTO = daoFacade.activateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ACTIVATE, actionType, actionId); - return activatedAction; + return buildAction(actionType, activatedActionDTO); } /** @@ -183,7 +194,7 @@ public Action activateAction(String actionType, String actionId, String tenantDo * @param actionId Action ID. * @param tenantDomain Tenant domain. * @return deactivated action. - * @throws ActionMgtException if an error occurred while deactivating the action. + * @throws ActionMgtException If an error occurred while deactivating the action. */ @Override public Action deactivateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { @@ -194,10 +205,10 @@ public Action deactivateAction(String actionType, String actionId, String tenant } String resolvedActionType = getActionTypeFromPath(actionType); checkIfActionExists(resolvedActionType, actionId, tenantDomain); - Action deactivatedAction = CACHE_BACKED_DAO.deactivateAction(resolvedActionType, actionId, + ActionDTO deactivatedActionDTO = daoFacade.deactivateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DEACTIVATE, actionType, actionId); - return deactivatedAction; + return buildAction(actionType, deactivatedActionDTO); } /** @@ -213,7 +224,7 @@ public Map getActionsCountPerType(String tenantDomain) throws A if (LOG.isDebugEnabled()) { LOG.debug("Retrieving Actions count per Type."); } - return CACHE_BACKED_DAO.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); + return daoFacade.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); } /** @@ -232,8 +243,10 @@ public Action getActionByActionId(String actionType, String actionId, String ten if (LOG.isDebugEnabled()) { LOG.debug(String.format("Retrieving Action of Action ID: %s", actionId)); } - return CACHE_BACKED_DAO.getActionByActionId(getActionTypeFromPath(actionType), actionId, + ActionDTO actionDTO = daoFacade.getActionByActionId(getActionTypeFromPath(actionType), actionId, IdentityTenantUtil.getTenantId(tenantDomain)); + + return buildAction(actionType, actionDTO); } /** @@ -250,17 +263,13 @@ public Action getActionByActionId(String actionType, String actionId, String ten public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, String tenantDomain) throws ActionMgtException { - String resolvedActionType = getActionTypeFromPath(actionType); - Action existingAction = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - doEndpointAuthenticationValidation(authentication); - Action updatingAction = new Action.ActionRequestBuilder() .endpoint(new EndpointConfig.EndpointConfigBuilder() .authentication(authentication) .build()) .build(); - return CACHE_BACKED_DAO.updateAction(resolvedActionType, actionId, updatingAction, existingAction, - IdentityTenantUtil.getTenantId(tenantDomain)); + + return updateAction(actionType, actionId, updatingAction, tenantDomain); } /** @@ -276,8 +285,7 @@ private String getActionTypeFromPath(String actionType) throws ActionMgtClientEx .filter(type -> type.getPathParam().equals(actionType)) .map(Action.ActionTypes::getActionType) .findFirst() - .orElseThrow(() -> ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_TYPE)); + .orElseThrow(() -> ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_TYPE)); } /** @@ -293,7 +301,7 @@ private void validateMaxActionsPerType(String actionType, String tenantDomain) t if (actionsCountPerType.containsKey(actionType) && actionsCountPerType.get(actionType) >= IdentityUtil.getMaximumActionsPerActionType()) { throw ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED); + ErrorMessage.ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED); } } @@ -303,33 +311,42 @@ private void validateMaxActionsPerType(String actionType, String tenantDomain) t * @param actionType Action Type. * @param actionId Action ID. * @param tenantDomain Tenant Domain. + * @return ActionDTO if the action exists. * @throws ActionMgtException If the action does not exist. */ - private Action checkIfActionExists(String actionType, String actionId, String tenantDomain) + private ActionDTO checkIfActionExists(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - Action action = CACHE_BACKED_DAO.getActionByActionId(actionType, actionId, + ActionDTO actionDTO = daoFacade.getActionByActionId(actionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); - if (action == null || !actionType.equals(action.getType().name())) { + if (actionDTO == null || !actionType.equals(actionDTO.getType().name())) { throw ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID); + ErrorMessage.ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID); } - return action; + + return actionDTO; } /** * Perform pre validations on action model when creating an action. * - * @param action Action create model. + * @param actionType Action type. + * @param actionDTO Action create model. * @throws ActionMgtClientException if action model is invalid. */ - private void doPreAddActionValidations(Action action) throws ActionMgtClientException { - - ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ACTION_NAME_FIELD, action.getName()); - ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ENDPOINT_URI_FIELD, action.getEndpoint().getUri()); - ACTION_VALIDATOR.validateActionName(action.getName()); - ACTION_VALIDATOR.validateEndpointUri(action.getEndpoint().getUri()); - doEndpointAuthenticationValidation(action.getEndpoint().getAuthentication()); + private void doPreAddActionValidations(String actionType, ActionDTO actionDTO) throws ActionMgtClientException { + + ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ACTION_NAME_FIELD, actionDTO.getName()); + ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ENDPOINT_URI_FIELD, actionDTO.getEndpoint().getUri()); + ACTION_VALIDATOR.validateActionName(actionDTO.getName()); + ACTION_VALIDATOR.validateEndpointUri(actionDTO.getEndpoint().getUri()); + doEndpointAuthenticationValidation(actionDTO.getEndpoint().getAuthentication()); + + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); + if (actionPropertyResolver != null) { + actionPropertyResolver.doPreAddActionPropertiesValidations(actionDTO); + } } /** @@ -337,19 +354,26 @@ private void doPreAddActionValidations(Action action) throws ActionMgtClientExce * This is specifically used during HTTP PATCH operation and * only validate non-null and non-empty fields. * - * @param action Action update model. + * @param actionType Action type. + * @param actionDTO Action update model. * @throws ActionMgtClientException if action model is invalid. */ - private void doPreUpdateActionValidations(Action action) throws ActionMgtClientException { + private void doPreUpdateActionValidations(String actionType, ActionDTO actionDTO) throws ActionMgtClientException { - if (action.getName() != null) { - ACTION_VALIDATOR.validateActionName(action.getName()); + if (actionDTO.getName() != null) { + ACTION_VALIDATOR.validateActionName(actionDTO.getName()); } - if (action.getEndpoint() != null && action.getEndpoint().getUri() != null) { - ACTION_VALIDATOR.validateEndpointUri(action.getEndpoint().getUri()); + if (actionDTO.getEndpoint() != null && actionDTO.getEndpoint().getUri() != null) { + ACTION_VALIDATOR.validateEndpointUri(actionDTO.getEndpoint().getUri()); } - if (action.getEndpoint() != null && action.getEndpoint().getAuthentication() != null) { - doEndpointAuthenticationValidation(action.getEndpoint().getAuthentication()); + if (actionDTO.getEndpoint() != null && actionDTO.getEndpoint().getAuthentication() != null) { + doEndpointAuthenticationValidation(actionDTO.getEndpoint().getAuthentication()); + } + + ActionPropertyResolver actionPropertyResolver = + ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); + if (actionPropertyResolver != null) { + actionPropertyResolver.doPreUpdateActionPropertiesValidations(actionDTO); } } @@ -384,4 +408,45 @@ private void doEndpointAuthenticationValidation(Authentication authentication) t break; } } + + private ActionDTO buildActionDTO(String actionType, String actionId, Action action) { + + ActionBuilder actionBuilder = + ActionBuilderFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); + if (actionBuilder != null) { + ActionDTO actionDTO = actionBuilder.buildActionDTO(action); + actionDTO.setId(actionId); + actionDTO.setType(Action.ActionTypes.valueOf(actionType)); + + return actionDTO; + } + + return new ActionDTO.Builder() + .id(action.getId() != null ? action.getId() : actionId) + .type(action.getType() != null ? action.getType() : Action.ActionTypes.valueOf(actionType)) + .name(action.getName()) + .description(action.getDescription()) + .status(action.getStatus()) + .endpoint(action.getEndpoint()) + .properties(null) + .build(); + } + + private Action buildAction(String actionType, ActionDTO actionDTO) { + + ActionBuilder actionBuilder = + ActionBuilderFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); + if (actionBuilder != null) { + return actionBuilder.buildAction(actionDTO); + } + + return new Action.ActionResponseBuilder() + .id(actionDTO.getId()) + .type(actionDTO.getType()) + .name(actionDTO.getName()) + .description(actionDTO.getDescription()) + .status(actionDTO.getStatus()) + .endpoint(actionDTO.getEndpoint()) + .build(); + } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java similarity index 61% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java index f3f2918d5b2c..c52b22aecb0b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.dao.impl; +package org.wso2.carbon.identity.action.management.service.impl; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; @@ -24,41 +24,48 @@ import org.wso2.carbon.identity.action.management.cache.ActionCacheByType; import org.wso2.carbon.identity.action.management.cache.ActionCacheEntry; import org.wso2.carbon.identity.action.management.cache.ActionTypeCacheKey; -import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import java.util.List; import java.util.Map; /** - * This class implements the {@link ActionManagementDAO} interface. + * CacheBackedActionManagementService act as the caching layer for the Action Management Service. */ -public class CacheBackedActionMgtDAO implements ActionManagementDAO { +public class CacheBackedActionManagementService implements ActionManagementService { - private static final Log LOG = LogFactory.getLog(CacheBackedActionMgtDAO.class); + private static final CacheBackedActionManagementService INSTANCE = new CacheBackedActionManagementService(); + private static final Log LOG = LogFactory.getLog(CacheBackedActionManagementService.class); + private static final ActionManagementServiceImpl ACTION_MGT_SERVICE = + new ActionManagementServiceImpl(new ActionManagementDAOImpl()); private final ActionCacheByType actionCacheByType; - private final ActionManagementDAO actionManagementDAO; - public CacheBackedActionMgtDAO(ActionManagementDAO actionManagementDAO) { + private CacheBackedActionManagementService() { - this.actionManagementDAO = actionManagementDAO; actionCacheByType = ActionCacheByType.getInstance(); } + public static CacheBackedActionManagementService getInstance() { + + return INSTANCE; + } + @Override - public Action addAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { + public Action addAction(String actionType, Action action, String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.addAction(actionType, actionId, action, tenantId); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return ACTION_MGT_SERVICE.addAction(actionType, action, tenantDomain); } @Override - public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { + public List getActionsByActionType(String actionType, String tenantDomain) throws ActionMgtException { ActionTypeCacheKey cacheKey = new ActionTypeCacheKey(actionType); - ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantId); + ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantDomain); if (entry != null) { if (LOG.isDebugEnabled()) { @@ -66,72 +73,72 @@ public List getActionsByActionType(String actionType, Integer tenantId) } return entry.getActions(); } - if (LOG.isDebugEnabled()) { LOG.debug("Cache entry not found for Action Type " + actionType + ". Fetching entry from DB."); } - List actions = actionManagementDAO.getActionsByActionType(actionType, tenantId); + List actions = ACTION_MGT_SERVICE.getActionsByActionType(actionType, tenantDomain); if (actions != null && !actions.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Entry fetched from DB for Action Type " + actionType + ". Updating cache."); } - actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actions), tenantId); + actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actions), tenantDomain); } else { if (LOG.isDebugEnabled()) { LOG.debug("Entry for Action Type " + actionType + " not found in cache or DB."); } } + return actions; } @Override - public Action updateAction(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { + public Action updateAction(String actionType, String actionId, Action action, String tenantDomain) + throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.updateAction(actionType, actionId, updatingAction, existingAction, tenantId); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return ACTION_MGT_SERVICE.updateAction(actionType, actionId, action, tenantDomain); } @Override - public void deleteAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { + public void deleteAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - actionManagementDAO.deleteAction(actionType, actionId, action, tenantId); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + ACTION_MGT_SERVICE.deleteAction(actionType, actionId, tenantDomain); } @Override - public Action activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public Action activateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.activateAction(actionType, actionId, tenantId); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return ACTION_MGT_SERVICE.activateAction(actionType, actionId, tenantDomain); } @Override - public Action deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public Action deactivateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.deactivateAction(actionType, actionId, tenantId); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return ACTION_MGT_SERVICE.deactivateAction(actionType, actionId, tenantDomain); } @Override - public Map getActionsCountPerType(Integer tenantId) throws ActionMgtException { + public Map getActionsCountPerType(String tenantDomain) throws ActionMgtException { - return actionManagementDAO.getActionsCountPerType(tenantId); + return ACTION_MGT_SERVICE.getActionsCountPerType(tenantDomain); } @Override - public Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public Action getActionByActionId(String actionType, String actionId, String tenantDomain) + throws ActionMgtException { ActionTypeCacheKey cacheKey = new ActionTypeCacheKey(actionType); - ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantId); + ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantDomain); /* If the entry for the given action type is not null, get the action list from cache and iterate to get the action by matching action id. */ if (entry != null) { - for (Action action: entry.getActions()) { + for (Action action : entry.getActions()) { if (StringUtils.equals(action.getId(), actionId)) { LOG.debug("Action is found from the cache with action Id " + actionId); return action; @@ -143,9 +150,9 @@ public Action getActionByActionId(String actionType, String actionId, Integer te LOG.debug("Action is not found from the cache with action Id " + actionId + ". Fetching entry from DB."); } - Action action = actionManagementDAO.getActionByActionId(actionType, actionId, tenantId); + Action action = ACTION_MGT_SERVICE.getActionByActionId(actionType, actionId, tenantDomain); if (action != null) { - updateCache(action, entry, cacheKey, tenantId); + updateCache(action, entry, cacheKey, tenantDomain); } else { if (LOG.isDebugEnabled()) { LOG.debug("Action with action Id " + actionId + " is not found in cache or DB."); @@ -155,7 +162,16 @@ public Action getActionByActionId(String actionType, String actionId, Integer te return action; } - private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheKey cacheKey, int tenantId) { + @Override + public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, + String tenantDomain) throws ActionMgtException { + + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return ACTION_MGT_SERVICE.updateActionEndpointAuthentication(actionType, actionId, authentication, + tenantDomain); + } + + private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheKey cacheKey, String tenantDomain) { if (LOG.isDebugEnabled()) { LOG.debug("Entry fetched from DB for Action Id " + action.getId() + ". Updating cache."); @@ -165,8 +181,8 @@ private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheK if (entry != null) { List actionsFromCache = entry.getActions(); actionsFromCache.add(action); - actionCacheByType.clearCacheEntry(cacheKey, tenantId); - actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actionsFromCache), tenantId); + actionCacheByType.clearCacheEntry(cacheKey, tenantDomain); + actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actionsFromCache), tenantDomain); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java index 8a14d98fb402..1acfaddfab8e 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java @@ -19,9 +19,8 @@ package org.wso2.carbon.identity.action.management.util; import org.apache.commons.lang.ArrayUtils; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtRuntimeException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; /** @@ -36,8 +35,7 @@ public class ActionManagementUtil { * @param data Data. * @return ActionMgtClientException. */ - public static ActionMgtClientException handleClientException( - ActionMgtConstants.ErrorMessages error, String... data) { + public static ActionMgtClientException handleClientException(ErrorMessage error, String... data) { String description = error.getDescription(); if (ArrayUtils.isNotEmpty(data)) { @@ -54,7 +52,7 @@ public static ActionMgtClientException handleClientException( * @param e Throwable. * @return ActionMgtClientException. */ - public static ActionMgtClientException handleClientException(ActionMgtConstants.ErrorMessages error, Throwable e) { + public static ActionMgtClientException handleClientException(ErrorMessage error, Throwable e) { return new ActionMgtClientException(error.getMessage(), error.getDescription(), error.getCode(), e); } @@ -67,8 +65,7 @@ public static ActionMgtClientException handleClientException(ActionMgtConstants. * @param data Data. * @return ActionMgtServerException. */ - public static ActionMgtServerException handleServerException( - ActionMgtConstants.ErrorMessages error, Throwable e, String... data) { + public static ActionMgtServerException handleServerException(ErrorMessage error, Throwable e, String... data) { String description = error.getDescription(); if (ArrayUtils.isNotEmpty(data)) { @@ -77,15 +74,4 @@ public static ActionMgtServerException handleServerException( return new ActionMgtServerException(error.getMessage(), description, error.getCode(), e); } - - /** - * Handle Action Management runtime exceptions. - * - * @param e Throwable. - * @return ActionMgtRuntimeException. - */ - public static ActionMgtRuntimeException handleRuntimeException(String errorMessage, Throwable e) { - - return new ActionMgtRuntimeException(errorMessage, e); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionSecretProcessor.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java similarity index 99% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionSecretProcessor.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java index 6bbb598350f7..ca0b44d26b4d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionSecretProcessor.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.util; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.AuthProperty; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java index 9de2ed68c026..672f49cb1be5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java @@ -20,6 +20,7 @@ import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import java.util.regex.Pattern; @@ -48,8 +49,7 @@ public class ActionValidator { public void validateForBlank(String fieldName, String fieldValue) throws ActionMgtClientException { if (StringUtils.isBlank(fieldValue)) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_EMPTY_ACTION_REQUEST_FIELD, fieldName); + throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_EMPTY_ACTION_REQUEST_FIELD, fieldName); } } @@ -63,8 +63,8 @@ public void validateActionName(String name) throws ActionMgtClientException { boolean isValidName = actionNameRegexPattern.matcher(name).matches(); if (!isValidName) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ACTION_NAME_FIELD); + throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, + ActionMgtConstants.ACTION_NAME_FIELD); } } @@ -78,8 +78,8 @@ public void validateEndpointUri(String uri) throws ActionMgtClientException { boolean isValidUri = endpointUriRegexPattern.matcher(uri).matches(); if (!isValidUri) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ENDPOINT_URI_FIELD); + throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, + ActionMgtConstants.ENDPOINT_URI_FIELD); } } @@ -93,8 +93,8 @@ public void validateHeader(String header) throws ActionMgtClientException { boolean isValidHeader = headerRegexPattern.matcher(header).matches(); if (!isValidHeader) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.API_KEY_HEADER_FIELD); + throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, + ActionMgtConstants.API_KEY_HEADER_FIELD); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java index aab546f2b426..01dfc0155c43 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java @@ -27,6 +27,8 @@ import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.impl.ActionManagementServiceImpl; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; From 42b86e0bdd299dc8e9f1dee8cd4a0f543d48513f Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 25 Nov 2024 12:02:00 +0530 Subject: [PATCH 12/34] Refactor ActionManagementDAOImpl test --- .../dao/impl/ActionManagementDAOImpl.java | 14 +- .../management/dao/model/ActionDTO.java | 3 +- .../management/model/Authentication.java | 3 +- .../dao/ActionManagementDAOImplTest.java | 659 +++++++++++------- .../util/ActionManagementAuditLoggerTest.java | 2 +- .../action/management/util/TestUtil.java | 34 + 6 files changed, 473 insertions(+), 242 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index db58bc07b0b5..016612cf11cb 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -360,7 +360,12 @@ private void updateAuthentication(String actionId, Authentication updatingAuthen private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { - Map actionProperties = actionDTO.getProperties().entrySet().stream() + Map propertiesMap = actionDTO.getProperties(); + if (propertiesMap == null) { + return; + } + + Map actionProperties = propertiesMap.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue())); try { addActionPropertiesToDB(actionDTO.getId(), actionProperties, tenantId); @@ -372,7 +377,12 @@ private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionM private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) throws ActionMgtException { - Map updatingProperties = updatingActionDTO.getProperties().entrySet().stream() + Map propertiesMap = updatingActionDTO.getProperties(); + if (propertiesMap == null) { + return; + } + + Map updatingProperties = propertiesMap.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue())); try { // Delete existing properties. diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java index 5b2fd029c89b..619d23962aeb 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java @@ -27,6 +27,7 @@ import org.wso2.carbon.identity.action.management.model.EndpointConfig; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -224,7 +225,7 @@ public Builder properties(Map properties) { public Builder property(String propertyName, String propertyValue) { if (this.properties == null) { - this.properties = Collections.emptyMap(); + this.properties = new HashMap<>(); } this.properties.put(propertyName, propertyValue); return this; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java index 1a8dfd99ffdb..1b30bf18cee5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java @@ -20,6 +20,7 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; @@ -143,7 +144,7 @@ public List getPropertiesWithDecryptedValues(String actionId) thro secretProcessor.decryptAssociatedSecrets(properties, type.getName(), actionId); } catch (SecretManagementException e) { throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES, e); + ErrorMessage.ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES, e); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index 1aedcae591b9..6e933139ed0a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -18,34 +18,30 @@ package org.wso2.carbon.identity.action.management.dao; -import org.junit.Assert; import org.mockito.MockedStatic; +import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; -import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; import java.util.List; import java.util.Map; import java.util.UUID; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_TYPE; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; @@ -62,7 +58,7 @@ public class ActionManagementDAOImplTest { private ActionManagementDAOImpl daoImpl; private MockedStatic identityTenantUtil; - private Action createdAction; + private ActionDTO createdActionDTO; @BeforeClass public void setUpClass() { @@ -74,12 +70,7 @@ public void setUpClass() { public void setUp() throws SecretManagementException { identityTenantUtil = mockStatic(IdentityTenantUtil.class); - SecretManagerImpl secretManager = mock(SecretManagerImpl.class); - SecretType secretType = mock(SecretType.class); - ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); identityTenantUtil.when(()-> IdentityTenantUtil.getTenantId(anyString())).thenReturn(TENANT_ID); - when(secretType.getId()).thenReturn("secretId"); - when(secretManager.getSecretType(any())).thenReturn(secretType); } @AfterMethod @@ -91,291 +82,485 @@ public void tearDown() { @Test(priority = 1) public void testAddAction() throws ActionMgtException { - Action creatingAction = TestUtil.buildMockAction( - "PreIssueAccessToken", - "To configure PreIssueAccessToken", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin")); - - createdAction = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, creatingAction, + ActionDTO creatingActionDTO = new ActionDTO.Builder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME) + .description(TestUtil.TEST_ACTION_DESCRIPTION) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TestUtil.TEST_USERNAME_SECRET_REFERENCE, + TestUtil.TEST_PASSWORD_SECRET_REFERENCE)) + .build()) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2) + .build(); + + try { + daoImpl.addAction(creatingActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + createdActionDTO = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_ID); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, createdAction.getId()); - Assert.assertEquals(creatingAction.getName(), createdAction.getName()); - Assert.assertEquals(creatingAction.getDescription(), createdAction.getDescription()); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, createdAction.getStatus()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), createdAction.getEndpoint().getUri()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - createdAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); + Assert.assertEquals(createdActionDTO.getType(), creatingActionDTO.getType()); + Assert.assertEquals(createdActionDTO.getName(), creatingActionDTO.getName()); + Assert.assertEquals(createdActionDTO.getDescription(), creatingActionDTO.getDescription()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(createdActionDTO.getEndpoint().getUri(), creatingActionDTO.getEndpoint().getUri()); + + Authentication createdAuthentication = createdActionDTO.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + creatingActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.TEST_USERNAME_SECRET_REFERENCE); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.TEST_PASSWORD_SECRET_REFERENCE); + + Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); } @Test(priority = 2, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Error while adding Action.") + expectedExceptionsMessageRegExp = "Error while adding Action Basic information.") public void testAddActionWithoutName() throws ActionMgtException { - Action action = TestUtil.buildMockAction( - null, - "To configure PreIssueAccessToken", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin")); - - daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, String.valueOf(UUID.randomUUID()), action, TENANT_ID); + ActionDTO creatingActionDTO = new ActionDTO.Builder() + .id(String.valueOf(UUID.randomUUID())) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(null) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TestUtil.TEST_USERNAME_SECRET_REFERENCE, + TestUtil.TEST_PASSWORD_SECRET_REFERENCE)) + .build()) + .build(); + + daoImpl.addAction(creatingActionDTO, TENANT_ID); } - @Test(priority = 3, dependsOnMethods = "testAddAction") + @Test(priority = 3) public void testGetActionsByActionType() throws ActionMgtException { - List actionList = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_TYPE, TENANT_ID); - Assert.assertEquals(1, actionList.size()); - Action result = actionList.get(0); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(createdAction.getName(), result.getName()); - Assert.assertEquals(createdAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); + List actionDTOList = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_TYPE, TENANT_ID); + Assert.assertEquals(actionDTOList.size(), 1); + ActionDTO result = actionDTOList.get(0); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + Assert.assertEquals(result.getEndpoint().getAuthentication().getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + + Authentication createdAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.TEST_USERNAME_SECRET_REFERENCE); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.TEST_PASSWORD_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); } @Test(priority = 4) - public void testGetActionByActionId() throws ActionMgtException { - - Action result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(createdAction.getName(), result.getName()); - Assert.assertEquals(createdAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - } - - @Test(priority = 5) public void testDeleteAction() throws ActionMgtException { - daoImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, createdAction, TENANT_ID); + daoImpl.deleteAction(createdActionDTO, TENANT_ID); Assert.assertNull(daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_ID)); } - @Test(priority = 6) + @Test(priority = 5) public void testAddActionWithoutDescription() throws ActionMgtException { - String id = String.valueOf(UUID.randomUUID()); - Action creatingAction = TestUtil.buildMockAction( - "PreIssueAccessToken", - null, - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin")); - createdAction = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, id, creatingAction, TENANT_ID); - Assert.assertEquals(id, createdAction.getId()); - Assert.assertEquals(creatingAction.getName(), createdAction.getName()); - Assert.assertNull(null, createdAction.getDescription()); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, createdAction.getStatus()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), createdAction.getEndpoint().getUri()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - createdAction.getEndpoint().getAuthentication().getType()); + ActionDTO creatingActionDTO = new ActionDTO.Builder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TestUtil.TEST_USERNAME_SECRET_REFERENCE, + TestUtil.TEST_PASSWORD_SECRET_REFERENCE)) + .build()) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2) + .build(); + try { + daoImpl.addAction(creatingActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + createdActionDTO = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID); + Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); + Assert.assertEquals(createdActionDTO.getType(), creatingActionDTO.getType()); + Assert.assertEquals(createdActionDTO.getName(), creatingActionDTO.getName()); + Assert.assertNull(createdActionDTO.getDescription()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(createdActionDTO.getEndpoint().getUri(), creatingActionDTO.getEndpoint().getUri()); + + Authentication createdAuthentication = createdActionDTO.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + creatingActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.TEST_USERNAME_SECRET_REFERENCE); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.TEST_PASSWORD_SECRET_REFERENCE); + + Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); } @Test(priority = 7, dependsOnMethods = "testAddActionWithoutDescription") - public void testUpdateAction() throws ActionMgtException { - - Action updatingAction = TestUtil.buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - "https://sample.com", - TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType() - ); - createdAction = result; + public void testUpdateCompleteAction() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME_UPDATED) + .description(TestUtil.TEST_ACTION_DESCRIPTION_UPDATED) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI_UPDATED) + .authentication(TestUtil.buildMockBearerAuthentication( + TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE)) + .build()) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1_UPDATED) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2_UPDATED) + .build(); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 8) - public void testUpdateActionWithoutNameAndDescription() throws ActionMgtException { - - // TODO: 'Name' is a required attribute. Thus, DAO layer should throw an exception if name is null. - // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = TestUtil.buildMockAction( - null, - null, - "https://sample.com", - TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(createdAction.getName(), result.getName()); - Assert.assertEquals(createdAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); + public void testUpdateActionBasicInfo() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME) + .description(TestUtil.TEST_ACTION_DESCRIPTION) + .build(); + + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 9) - public void testUpdateActionWithNameAndDescription() throws ActionMgtException { - - // TODO: 'Uri','AuthenticationType','AuthProperties' are required attributes. Thus, DAO layer should throw an - // exception if those attributes are null. This should be fixed in DAO layer and test case needs to be updated - // accordingly. - Action updatingAction = TestUtil.buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - null, - null); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); + public void testUpdateActionEndpoint() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockAPIKeyAuthentication(TestUtil.TEST_API_KEY_HEADER, + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE)) + .build()) + .build(); + + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.HEADER).getValue(), + TestUtil.TEST_API_KEY_HEADER); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.VALUE).getValue(), + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 10) - public void testUpdateActionWithoutEndpointUri() throws ActionMgtException { - - // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if Uri is null. - // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = TestUtil.buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - null, - TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); + public void testUpdateActionEndpointUri() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI_UPDATED) + .build()) + .build(); + + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.HEADER).getValue(), + TestUtil.TEST_API_KEY_HEADER); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.VALUE).getValue(), + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 11) - public void testUpdateActionWithAuthType() throws ActionMgtException { - - Action updatingAction = TestUtil.buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - "https://sample.com", - TestUtil.buildMockBearerAuthentication("57c7df90-cacc-4f56-9b0a-f14bfbff3076")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(createdAction.getName(), result.getName()); - Assert.assertEquals(createdAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - createdAction = result; + public void testUpdateActionEndpointAuthenticationWithSameAuthType() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(TestUtil.buildMockAPIKeyAuthentication(TestUtil.TEST_API_KEY_HEADER_UPDATED, + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE)) + .build()) + .build(); + + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.HEADER).getValue(), + TestUtil.TEST_API_KEY_HEADER_UPDATED); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.VALUE).getValue(), + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 12) - public void testUpdateActionWithUri() throws ActionMgtException { - - // TODO: 'Name','AuthenticationType' and 'AuthProperties' are required attributes. Thus, DAO layer should throw - // an exception if those attributes are null. This should be fixed in DAO layer and test case needs to be - // updated accordingly. - Action updatingAction = TestUtil.buildMockAction( - null, - null, - "https://sample.com", - null); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(createdAction.getName(), result.getName()); - Assert.assertEquals(createdAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(createdAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - createdAction = result; + public void testUpdateActionEndpointAuthenticationWithDifferentAuthType() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(new Authentication.NoneAuthBuilder().build()) + .build()) + .build(); + + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 13) - public void testUpdateActionWithAuthTypeWithoutUri() throws ActionMgtException { - - // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if uri is null. - // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = TestUtil.buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - null, - TestUtil.buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), updatingAction, - createdAction, TENANT_ID); - Assert.assertEquals(createdAction.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(createdAction.getType(), result.getType()); - Assert.assertEquals(createdAction.getStatus(), result.getStatus()); - Assert.assertEquals(createdAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); + public void testUpdateActionProperties() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2) + .build(); + + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } + @Test(priority = 14) public void testDeactivateAction() throws ActionMgtException { - Assert.assertEquals(Action.Status.ACTIVE, createdAction.getStatus()); - Action deactivatedAction = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), + Assert.assertEquals(Action.Status.ACTIVE, createdActionDTO.getStatus()); + ActionDTO deactivatedActionDTO = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdActionDTO.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); + Assert.assertEquals(Action.Status.INACTIVE, deactivatedActionDTO.getStatus()); } @Test(priority = 15) public void testActivateAction() throws ActionMgtException { - Action result = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdAction.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); + ActionDTO activatedActionDTO = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(Action.Status.ACTIVE, activatedActionDTO.getStatus()); } @Test(priority = 16) public void testGetActionsCountPerType() throws ActionMgtException { - PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( - "PreUpdatePassword", - "To configure PreUpdatePassword", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin"), - PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, - null); - - Action preUpdatePasswordAction = daoImpl.addAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, - actionModel, TENANT_ID); - + ActionDTO creatingPreUpdatePasswordActionDTO = new ActionDTO.Builder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TestUtil.TEST_ACTION_NAME) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(new Authentication.NoneAuthBuilder().build()) + .build()) + .build(); + + daoImpl.addAction(creatingPreUpdatePasswordActionDTO, TENANT_ID); + ActionDTO createdPreUpdatePasswordActionDTO = daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, + PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); + Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); Assert.assertTrue(actionMap.containsKey(PRE_ISSUE_ACCESS_TOKEN_TYPE)); Assert.assertEquals(1, actionMap.get(PRE_ISSUE_ACCESS_TOKEN_TYPE).intValue()); Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); Assert.assertEquals(1, actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue()); - - daoImpl.deleteAction(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, preUpdatePasswordAction, - TENANT_ID); - daoImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, createdAction, TENANT_ID); + + daoImpl.deleteAction(createdPreUpdatePasswordActionDTO, TENANT_ID); + daoImpl.deleteAction(createdActionDTO, TENANT_ID); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java index 6e151f750959..a5b1d64cb194 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java @@ -232,7 +232,7 @@ private void assertActionData(AuditLog.AuditLogBuilder auditLogBuilder) Assert.assertEquals(extractMapByField("ActionName", auditLogBuilder), "Test Action"); Assert.assertEquals(extractMapByField("ActionType", auditLogBuilder), Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType()); - Assert.assertEquals(extractMapByField("ActionStatus", auditLogBuilder), Action.Status.ACTIVE.value()); + Assert.assertEquals(extractMapByField("ActionStatus", auditLogBuilder), Action.Status.ACTIVE.name()); Assert.assertEquals(extractMapByField("ActionDescription", auditLogBuilder), "This is a test action."); Assert.assertEquals(extractEndpointMapByField("AuthenticationScheme", auditLogBuilder), diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index aaa8a592ea48..b1f3ee82a9d3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -18,6 +18,7 @@ package org.wso2.carbon.identity.action.management.util; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; @@ -25,6 +26,7 @@ import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction.PasswordFormat; import org.wso2.carbon.identity.certificate.management.model.Certificate; +import java.util.Map; import java.util.UUID; /** @@ -43,6 +45,32 @@ public class TestUtil { public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); + + public static final String TEST_ACTION_NAME = "PreIssueAccessToken"; + public static final String TEST_ACTION_DESCRIPTION = "To configure PreIssueAccessToken"; + public static final String TEST_ACTION_URI = "https://example.com"; + public static final String TEST_USERNAME_SECRET_REFERENCE = buildSecretName(Authentication.Type.BASIC.getName(), + Authentication.Property.USERNAME.getName()); + public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(Authentication.Type.BASIC.getName(), + Authentication.Property.PASSWORD.getName()); + public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = + buildSecretName(Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName()); + public static final String TEST_API_KEY_HEADER = "sampleHeader"; + public static final String TEST_API_KEY_HEADER_UPDATED = "UpdatedSampleHeader"; + public static final String TEST_API_KEY_VALUE_SECRET_REFERENCE = + buildSecretName(Authentication.Type.API_KEY.getName(), Authentication.Property.VALUE.getName()); + public static final String TEST_ACTION_PROPERTY_NAME_1 = "samplePropertyName"; + public static final String TEST_ACTION_PROPERTY_VALUE_1 = "samplePropertyValue"; + public static final String TEST_ACTION_PROPERTY_NAME_2 = "samplePropertyName2"; + public static final String TEST_ACTION_PROPERTY_VALUE_2 = "samplePropertyValue2"; + + public static final String TEST_ACTION_NAME_UPDATED = "Updated PreIssueAccessToken"; + public static final String TEST_ACTION_DESCRIPTION_UPDATED = "To configure updated PreIssueAccessToken"; + public static final String TEST_ACTION_URI_UPDATED = "https://sample.com"; + public static final String TEST_ACTION_PROPERTY_VALUE_1_UPDATED = "UpdatedSamplePropertyValue"; + public static final String TEST_ACTION_PROPERTY_VALUE_2_UPDATED = "UpdatedSamplePropertyValue2"; + + public static final String SAMPLE_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; public static final String CERTIFICATE_ID = String.valueOf(UUID.randomUUID()); public static final String CERTIFICATE_NAME = "ACTIONS:" + PRE_UPDATE_PASSWORD_ACTION_ID; @@ -58,6 +86,12 @@ public static Action buildMockAction(String name, String description, String uri .build(); } + private static String buildSecretName(String authType, String authPropertyName) { + + String testSecretTypeId = "fcaf81a9-0d58-4cf4-98c8-fde2f3ba8df2"; + return testSecretTypeId + ":" + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID + ":" + authType + ":" + authPropertyName; + } + public static PreUpdatePasswordAction buildMockPreUpdatePasswordAction(String name, String description, String uri, Authentication authentication, PasswordFormat passwordSharingFormat, From 19deaefb870e6bbd2082fc11bcc8bad0ce951595 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 26 Nov 2024 06:20:55 +0530 Subject: [PATCH 13/34] Added ActionManagementDAOFacadeTest --- .../dao/impl/ActionManagementDAOFacade.java | 93 ++--- .../management/dao/model/ActionDTO.java | 2 +- .../dao/ActionManagementDAOFacadeTest.java | 352 ++++++++++++++++++ .../dao/ActionManagementDAOImplTest.java | 27 +- .../action/management/util/TestUtil.java | 43 ++- 5 files changed, 420 insertions(+), 97 deletions(-) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index 520c52b04c4b..fe6a354e0411 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -30,7 +30,6 @@ import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; -import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; @@ -90,7 +89,7 @@ public List getActionsByActionType(String actionType, Integer tenantI getPropertiesOfActionDTOs(actionType, actionDTOS, tenantId); return actionDTOS; - } catch (ActionMgtException e) { + } catch (ActionMgtException | ActionPropertyResolverException e) { throw ActionManagementUtil.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); } @@ -102,11 +101,13 @@ public ActionDTO getActionByActionId(String actionType, String actionId, Integer try { ActionDTO actionDTO = actionManagementDAO.getActionByActionId(actionType, actionId, tenantId); - // Resolve action properties - getProperties(actionDTO, tenantId); + if (actionDTO != null) { + // Resolve action properties + getProperties(actionDTO, tenantId); + } return actionDTO; - } catch (ActionMgtException e) { + } catch (ActionMgtException | ActionPropertyResolverException e) { throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); } } @@ -227,28 +228,24 @@ private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws Act } } - private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { Map properties = null; ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); - try { - if (actionPropertyResolver != null) { - properties = actionPropertyResolver.addProperties(actionDTO, - IdentityTenantUtil.getTenantDomain(tenantId)); - } - if (properties != null) { - actionDTO.setProperties(properties.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); - } - } catch (ActionPropertyResolverException e) { - throw new ActionMgtServerException("Failed to resolve Add Action properties for Action Type: " - + actionDTO.getType().getDisplayName(), e); + + if (actionPropertyResolver != null) { + properties = actionPropertyResolver.addProperties(actionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + if (properties != null) { + actionDTO.setProperties(properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } } private void getPropertiesOfActionDTOs(String actionType, List actionDTOS, Integer tenantId) - throws ActionMgtException { + throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver( @@ -257,62 +254,46 @@ private void getPropertiesOfActionDTOs(String actionType, List action return; } - try { - for (ActionDTO actionDTO : actionDTOS) { - actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - } catch (ActionPropertyResolverException e) { - throw new ActionMgtServerException("Error while resolving Properties of Actions of Action Type: " - + Action.ActionTypes.valueOf(actionType).getDisplayName(), e); + for (ActionDTO actionDTO : actionDTOS) { + actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, + IdentityTenantUtil.getTenantDomain(tenantId))); } } - private void getProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + private void getProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); - try { - if (actionPropertyResolver != null) { - actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - } catch (ActionPropertyResolverException e) { - throw new ActionMgtServerException("Failed to fetch Action properties for Action Type: " - + actionDTO.getType().getDisplayName(), e); + + if (actionPropertyResolver != null) { + actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, + IdentityTenantUtil.getTenantDomain(tenantId))); } } private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) - throws ActionMgtServerException { + throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(updatingActionDTO.getType()); - try { - if (actionPropertyResolver != null) { - Map properties = actionPropertyResolver.updateProperties(updatingActionDTO, - existingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); - updatingActionDTO.setProperties(properties.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); - } - } catch (ActionPropertyResolverException e) { - throw new ActionMgtServerException("Failed to resolve Update Action properties for Action Type: " - + updatingActionDTO.getType().getDisplayName(), e); + + if (actionPropertyResolver != null) { + Map properties = actionPropertyResolver.updateProperties(updatingActionDTO, + existingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + updatingActionDTO.setProperties(properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } } - private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtServerException { + private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) + throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(deletingActionDTO.getType()); - try { - if (actionPropertyResolver != null) { - actionPropertyResolver.deleteProperties(deletingActionDTO, - IdentityTenantUtil.getTenantDomain(tenantId)); - } - } catch (ActionPropertyResolverException e) { - throw new ActionMgtServerException("Failed to delete Action properties for Action Type: " - + deletingActionDTO.getType().getDisplayName(), e); + + if (actionPropertyResolver != null) { + actionPropertyResolver.deleteProperties(deletingActionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java index 619d23962aeb..f0b4c4ff47c2 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java @@ -222,7 +222,7 @@ public Builder properties(Map properties) { return this; } - public Builder property(String propertyName, String propertyValue) { + public Builder property(String propertyName, Object propertyValue) { if (this.properties == null) { this.properties = new HashMap<>(); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java new file mode 100644 index 000000000000..e1308109a5cc --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.dao; + +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; +import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.util.TestUtil; +import org.wso2.carbon.identity.certificate.management.model.Certificate; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; +import org.wso2.carbon.identity.common.testng.WithH2Database; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; + +/** + * This class is a test suite for the ActionManagementDAOFacade class. + * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOFacade class which is + * responsible for handling external services. + */ +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithCarbonHome +public class ActionManagementDAOFacadeTest { + + @Mock + private ActionPropertyResolver actionPropertyResolver; + private MockedStatic actionPropertyResolverFactory; + private MockedStatic identityTenantUtil; + + private ActionManagementDAOFacade daoFacade; + private ActionDTO createdActionDTO; + + @BeforeClass + public void setUpClass() { + + daoFacade = new ActionManagementDAOFacade(new ActionManagementDAOImpl()); + } + + @BeforeMethod + public void setUp() throws SecretManagementException { + + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + when(secretType.getId()).thenReturn(TestUtil.TEST_SECRET_TYPE_ID); + when(secretManager.getSecretType(any())).thenReturn(secretType); + + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + identityTenantUtil.when(()-> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(TENANT_DOMAIN); + + MockitoAnnotations.openMocks(this); + actionPropertyResolverFactory = mockStatic(ActionPropertyResolverFactory.class); + } + + @AfterMethod + public void tearDown() { + + identityTenantUtil.close(); + actionPropertyResolverFactory.close(); + } + + @Test(priority = 1) + public void testAddAction() throws ActionMgtException, ActionPropertyResolverException { + + ActionDTO creatingActionDTO = new ActionDTO.Builder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)) + .build()) + .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE) + .property(CERTIFICATE_PROPERTY_NAME, + new Certificate.Builder().certificateContent(TEST_CERTIFICATE).build()) + .build(); + + actionPropertyResolverFactory.when( + () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionPropertyResolver); + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); + properties.put(CERTIFICATE_PROPERTY_NAME, TestUtil.CERTIFICATE_ID); + when(actionPropertyResolver.addProperties(any(), any())).thenReturn(properties); + + try { + daoFacade.addAction(creatingActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + + Map retrievedProperties = new HashMap<>(); + retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); + retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE).build()); + when(actionPropertyResolver.getProperties(any(), any())).thenReturn(retrievedProperties); + + createdActionDTO = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, + TENANT_ID); + Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); + Assert.assertEquals(createdActionDTO.getType(), creatingActionDTO.getType()); + Assert.assertEquals(createdActionDTO.getName(), creatingActionDTO.getName()); + Assert.assertEquals(createdActionDTO.getDescription(), creatingActionDTO.getDescription()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(createdActionDTO.getEndpoint().getUri(), creatingActionDTO.getEndpoint().getUri()); + + Authentication createdAuthentication = createdActionDTO.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + creatingActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC.getName(), + Authentication.Property.USERNAME.getName())); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC.getName(), + Authentication.Property.PASSWORD.getName())); + + Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); + Assert.assertEquals(createdActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), + creatingActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertEquals(((Certificate) createdActionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)) + .getCertificateContent(), TEST_CERTIFICATE); + } + + @Test(priority = 2) + public void testGetActionsByType() throws ActionMgtException, ActionPropertyResolverException { + + actionPropertyResolverFactory.when( + () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionPropertyResolver); + Map retrievedProperties = new HashMap<>(); + retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); + retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE).build()); + when(actionPropertyResolver.getProperties(any(), any())).thenReturn(retrievedProperties); + + List actionDTOs = daoFacade.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); + ActionDTO result = actionDTOs.get(0); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + createdActionDTO.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME) + .getValue()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + createdActionDTO.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD) + .getValue()); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); + Assert.assertEquals(result.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), + createdActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertEquals(((Certificate) result.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent(), + ((Certificate) createdActionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent()); + } + + @Test(priority = 3, dependsOnMethods = "testAddAction") + public void testUpdateCompleteAction() throws ActionMgtException, ActionPropertyResolverException { + + ActionDTO updatingAction = new ActionDTO.Builder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TEST_ACTION_NAME_UPDATED) + .description(TEST_ACTION_DESCRIPTION_UPDATED) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI_UPDATED) + .authentication(TestUtil.buildMockBearerAuthentication( + TEST_ACCESS_TOKEN_SECRET_REFERENCE)) + .build()) + .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED) + .property(CERTIFICATE_PROPERTY_NAME, + new Certificate.Builder().certificateContent(TEST_CERTIFICATE_UPDATED).build()) + .build(); + + actionPropertyResolverFactory.when( + () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionPropertyResolver); + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED); + properties.put(CERTIFICATE_PROPERTY_NAME, CERTIFICATE_ID); + when(actionPropertyResolver.updateProperties(any(), any(), anyString())).thenReturn(properties); + + try { + daoFacade.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + + Map retrievedProperties = new HashMap<>(); + retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED); + retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE_UPDATED).build()); + when(actionPropertyResolver.getProperties(any(), any())).thenReturn(retrievedProperties); + + ActionDTO result = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BEARER.getName(), + Authentication.Property.ACCESS_TOKEN.getName())); + + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); + + Assert.assertTrue(updatingAction.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertTrue(updatingAction.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); + Assert.assertEquals(result.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), + updatingAction.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertEquals(((Certificate) result.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent(), + TEST_CERTIFICATE_UPDATED); + createdActionDTO = result; + } + + @Test(priority = 4) + public void testDeactivateAction() throws ActionMgtException { + + Assert.assertEquals(Action.Status.ACTIVE, createdActionDTO.getStatus()); + ActionDTO deactivatedActionDTO = daoFacade.deactivateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(Action.Status.INACTIVE, deactivatedActionDTO.getStatus()); + } + + @Test(priority = 5) + public void testActivateAction() throws ActionMgtException { + + ActionDTO activatedActionDTO = daoFacade.activateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(Action.Status.ACTIVE, activatedActionDTO.getStatus()); + } + + @Test(priority = 6) + public void testGetActionsCountPerType() throws ActionMgtException { + + Map actionMap = daoFacade.getActionsCountPerType(TENANT_ID); + Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); + Assert.assertEquals(1, actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue()); + } + + @Test(priority = 7) + public void testDeleteAction() throws ActionMgtException, ActionPropertyResolverException { + + actionPropertyResolverFactory.when( + () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionPropertyResolver); + doNothing().when(actionPropertyResolver).deleteProperties(any(), anyString()); + + try { + daoFacade.deleteAction(createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertNull(daoFacade.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID)); + Assert.assertEquals(daoFacade.getActionsCountPerType(TENANT_ID), Collections.emptyMap()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index 6e933139ed0a..ca76a131054b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -18,11 +18,8 @@ package org.wso2.carbon.identity.action.management.dao; -import org.mockito.MockedStatic; import org.testng.Assert; -import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; @@ -33,15 +30,11 @@ import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import java.util.List; import java.util.Map; import java.util.UUID; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mockStatic; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_TYPE; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; @@ -57,7 +50,6 @@ public class ActionManagementDAOImplTest { private ActionManagementDAOImpl daoImpl; - private MockedStatic identityTenantUtil; private ActionDTO createdActionDTO; @BeforeClass @@ -66,19 +58,6 @@ public void setUpClass() { daoImpl = new ActionManagementDAOImpl(); } - @BeforeMethod - public void setUp() throws SecretManagementException { - - identityTenantUtil = mockStatic(IdentityTenantUtil.class); - identityTenantUtil.when(()-> IdentityTenantUtil.getTenantId(anyString())).thenReturn(TENANT_ID); - } - - @AfterMethod - public void tearDown() { - - identityTenantUtil.close(); - } - @Test(priority = 1) public void testAddAction() throws ActionMgtException { @@ -180,7 +159,11 @@ public void testGetActionsByActionType() throws ActionMgtException { @Test(priority = 4) public void testDeleteAction() throws ActionMgtException { - daoImpl.deleteAction(createdActionDTO, TENANT_ID); + try { + daoImpl.deleteAction(createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } Assert.assertNull(daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_ID)); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index b1f3ee82a9d3..cb230b72f8eb 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -18,7 +18,6 @@ package org.wso2.carbon.identity.action.management.util; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; @@ -26,7 +25,6 @@ import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction.PasswordFormat; import org.wso2.carbon.identity.certificate.management.model.Certificate; -import java.util.Map; import java.util.UUID; /** @@ -46,26 +44,36 @@ public class TestUtil { public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); - public static final String TEST_ACTION_NAME = "PreIssueAccessToken"; - public static final String TEST_ACTION_DESCRIPTION = "To configure PreIssueAccessToken"; + public static final String TEST_SECRET_TYPE_ID = "fcaf81a9-0d58-4cf4-98c8-fde2f3ba8df2"; + + public static final String TEST_ACTION_NAME = "Test Action Name"; + public static final String TEST_ACTION_DESCRIPTION = "Test Action description"; public static final String TEST_ACTION_URI = "https://example.com"; - public static final String TEST_USERNAME_SECRET_REFERENCE = buildSecretName(Authentication.Type.BASIC.getName(), - Authentication.Property.USERNAME.getName()); - public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(Authentication.Type.BASIC.getName(), - Authentication.Property.PASSWORD.getName()); - public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = - buildSecretName(Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName()); + public static final String TEST_USERNAME = "sampleUsername"; + public static final String TEST_USERNAME_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BASIC.getName(), Authentication.Property.USERNAME.getName()); + public static final String TEST_PASSWORD = "samplePassword"; + public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BASIC.getName(), Authentication.Property.PASSWORD.getName()); + public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName()); public static final String TEST_API_KEY_HEADER = "sampleHeader"; public static final String TEST_API_KEY_HEADER_UPDATED = "UpdatedSampleHeader"; - public static final String TEST_API_KEY_VALUE_SECRET_REFERENCE = - buildSecretName(Authentication.Type.API_KEY.getName(), Authentication.Property.VALUE.getName()); + public static final String TEST_API_KEY_VALUE_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.API_KEY.getName(), Authentication.Property.VALUE.getName()); public static final String TEST_ACTION_PROPERTY_NAME_1 = "samplePropertyName"; public static final String TEST_ACTION_PROPERTY_VALUE_1 = "samplePropertyValue"; public static final String TEST_ACTION_PROPERTY_NAME_2 = "samplePropertyName2"; public static final String TEST_ACTION_PROPERTY_VALUE_2 = "samplePropertyValue2"; - - public static final String TEST_ACTION_NAME_UPDATED = "Updated PreIssueAccessToken"; - public static final String TEST_ACTION_DESCRIPTION_UPDATED = "To configure updated PreIssueAccessToken"; + public static final String PASSWORD_SHARING_TYPE_PROPERTY_NAME = "passwordSharingType"; + public static final String TEST_PASSWORD_SHARING_TYPE = "PLAIN_TEXT"; + public static final String TEST_PASSWORD_SHARING_TYPE_UPDATED = "SHA256_HASHED"; + public static final String CERTIFICATE_PROPERTY_NAME = "certificate"; + public static final String TEST_CERTIFICATE = "sampleCertificate"; + public static final String TEST_CERTIFICATE_UPDATED = "UpdatedSampleCertificate"; + + public static final String TEST_ACTION_NAME_UPDATED = "Updated Test Action Name"; + public static final String TEST_ACTION_DESCRIPTION_UPDATED = "Updated Test Action description"; public static final String TEST_ACTION_URI_UPDATED = "https://sample.com"; public static final String TEST_ACTION_PROPERTY_VALUE_1_UPDATED = "UpdatedSamplePropertyValue"; public static final String TEST_ACTION_PROPERTY_VALUE_2_UPDATED = "UpdatedSamplePropertyValue2"; @@ -86,10 +94,9 @@ public static Action buildMockAction(String name, String description, String uri .build(); } - private static String buildSecretName(String authType, String authPropertyName) { + public static String buildSecretName(String actionId, String authType, String authPropertyName) { - String testSecretTypeId = "fcaf81a9-0d58-4cf4-98c8-fde2f3ba8df2"; - return testSecretTypeId + ":" + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID + ":" + authType + ":" + authPropertyName; + return TEST_SECRET_TYPE_ID + ":" + actionId + ":" + authType + ":" + authPropertyName; } public static PreUpdatePasswordAction buildMockPreUpdatePasswordAction(String name, String description, String uri, From 73129ff409dc220674594045370c909805220d13 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 26 Nov 2024 06:33:43 +0530 Subject: [PATCH 14/34] Rename ActionBuilder to ActionConverter --- ...ctionBuilder.java => ActionConverter.java} | 7 ++- ...ctory.java => ActionConverterFactory.java} | 22 ++++----- .../internal/ActionMgtServiceComponent.java | 45 ++++++------------- .../ActionMgtServiceComponentHolder.java | 20 --------- 4 files changed, 27 insertions(+), 67 deletions(-) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{ActionBuilder.java => ActionConverter.java} (89%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/{ActionBuilderFactory.java => ActionConverterFactory.java} (55%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionConverter.java similarity index 89% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionConverter.java index ddf09b32d971..7083993cd839 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionBuilder.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionConverter.java @@ -22,11 +22,11 @@ import org.wso2.carbon.identity.action.management.model.Action; /** - * This interface defines the Action Resolver. - * Action Resolver is the component that is responsible for the conversions between Action and ExtendedAction + * This interface defines the Action ActionConverter. + * Action ActionConverter is the component that is responsible for the conversions between Action and ExtendedAction * objects. */ -public interface ActionBuilder { +public interface ActionConverter { Action.ActionTypes getSupportedActionType(); @@ -45,7 +45,6 @@ default ActionDTO buildActionDTO(Action action) { .description(action.getDescription()) .status(action.getStatus()) .endpoint(action.getEndpoint()) - .properties(null) .build(); } /** diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java similarity index 55% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java index 278990f35a55..d1c85d359d66 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionBuilderFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java @@ -18,39 +18,39 @@ package org.wso2.carbon.identity.action.management.factory; -import org.wso2.carbon.identity.action.management.ActionBuilder; +import org.wso2.carbon.identity.action.management.ActionConverter; import org.wso2.carbon.identity.action.management.model.Action; import java.util.HashMap; import java.util.Map; /** - * This class defines the Action Object Builder Factory. - * Action Object Builder Factory is the component that is responsible for providing the {@link ActionBuilder} + * This class defines the Action Converter Factory. + * Action Converter Factory is the component that is responsible for providing the {@link ActionConverter} * based on the action type. */ -public class ActionBuilderFactory { +public class ActionConverterFactory { - private static final Map actionObjectBuilders = new HashMap<>(); + private static final Map actionConverters = new HashMap<>(); - public static ActionBuilder getActionBuilder(Action.ActionTypes actionType) { + public static ActionConverter getActionBuilder(Action.ActionTypes actionType) { switch (actionType) { case PRE_UPDATE_PASSWORD: - return actionObjectBuilders.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); + return actionConverters.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); case PRE_ISSUE_ACCESS_TOKEN: default: return null; } } - public static void registerActionBuilder(ActionBuilder actionBuilder) { + public static void registerActionConverter(ActionConverter actionConverter) { - actionObjectBuilders.put(actionBuilder.getSupportedActionType(), actionBuilder); + actionConverters.put(actionConverter.getSupportedActionType(), actionConverter); } - public static void unregisterActionBuilder(ActionBuilder actionBuilder) { + public static void unregisterActionConverter(ActionConverter actionConverter) { - actionObjectBuilders.remove(actionBuilder.getSupportedActionType()); + actionConverters.remove(actionConverter.getSupportedActionType()); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index 57b8b1417100..b22a6baf193a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -28,12 +28,12 @@ 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.action.management.service.ActionManagementService; -import org.wso2.carbon.identity.action.management.ActionBuilder; +import org.wso2.carbon.identity.action.management.ActionConverter; import org.wso2.carbon.identity.action.management.ActionPropertyResolver; -import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; -import org.wso2.carbon.identity.action.management.factory.ActionBuilderFactory; +import org.wso2.carbon.identity.action.management.factory.ActionConverterFactory; import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -75,28 +75,28 @@ protected void deactivate(ComponentContext context) { } @Reference( - name = "action.builder", - service = ActionBuilder.class, + name = "action.converter", + service = ActionConverter.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, - unbind = "unsetActionBuilder" + unbind = "unsetActionConverter" ) - protected void setActionBuilder(ActionBuilder actionBuilder) { + protected void setActionConverter(ActionConverter actionConverter) { if (LOG.isDebugEnabled()) { - LOG.debug("Registering ActionBuilder: " + actionBuilder.getClass().getName() + + LOG.debug("Registering ActionConverter: " + actionConverter.getClass().getName() + " in the ActionMgtServiceComponent."); } - ActionBuilderFactory.registerActionBuilder(actionBuilder); + ActionConverterFactory.registerActionConverter(actionConverter); } - protected void unsetActionBuilder(ActionBuilder actionBuilder) { + protected void unsetActionConverter(ActionConverter actionConverter) { if (LOG.isDebugEnabled()) { - LOG.debug("Unregistering ActionBuilder: " + actionBuilder.getClass().getName() + + LOG.debug("Unregistering ActionConverter: " + actionConverter.getClass().getName() + " in the ActionMgtServiceComponent."); } - ActionBuilderFactory.unregisterActionBuilder(actionBuilder); + ActionConverterFactory.unregisterActionConverter(actionConverter); } @Reference( @@ -161,23 +161,4 @@ private void unsetSecretResolveManager(SecretResolveManager secretResolveManager ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(null); LOG.debug("SecretResolveManager unset in ActionMgtServiceComponentHolder bundle."); } - - @Reference( - name = "org.wso2.carbon.identity.certificate.management.service.CertificateManagementService", - service = CertificateManagementService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetCertificateManagementService" - ) - private void setCertificateManagementService(CertificateManagementService certificateManagementService) { - - ActionMgtServiceComponentHolder.getInstance().setCertificateManagementService(certificateManagementService); - LOG.debug("CertificateManagementService set in ActionMgtServiceComponentHolder bundle."); - } - - private void unsetCertificateManagementService(CertificateManagementService certificateManagementService) { - - ActionMgtServiceComponentHolder.getInstance().setCertificateManagementService(null); - LOG.debug("CertificateManagementService unset in ActionMgtServiceComponentHolder bundle."); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java index d921157e0af1..81e889869454 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java @@ -86,24 +86,4 @@ public void setSecretResolveManager(SecretResolveManager secretResolveManager) { this.secretResolveManager = secretResolveManager; } - - /** - * Get the CertificateManagementService. - * - * @return CertificateManagementService instance. - */ - public CertificateManagementService getCertificateManagementService() { - - return certificateMgtService; - } - - /** - * Set the CertificateManagementService. - * - * @param certificateMgtService CertificateManagementService instance. - */ - public void setCertificateManagementService(CertificateManagementService certificateMgtService) { - - this.certificateMgtService = certificateMgtService; - } } From 0d427a3bf05a8d3938c8825a90154c0146295a6a Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 26 Nov 2024 06:46:54 +0530 Subject: [PATCH 15/34] Modify ActionManagementServiceImplTest --- .../impl/ActionManagementServiceImpl.java | 86 ++++++++++--------- .../ActionManagementServiceImplTest.java | 6 +- 2 files changed, 49 insertions(+), 43 deletions(-) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/{ => service}/ActionManagementServiceImplTest.java (98%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index 3977ed844551..d6013731d2eb 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -20,8 +20,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.action.management.ActionConverter; import org.wso2.carbon.identity.action.management.ActionPropertyResolver; -import org.wso2.carbon.identity.action.management.ActionBuilder; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; @@ -29,7 +29,7 @@ import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.factory.ActionBuilderFactory; +import org.wso2.carbon.identity.action.management.factory.ActionConverterFactory; import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; @@ -82,8 +82,8 @@ public Action addAction(String actionType, Action action, String tenantDomain) t // Check whether the maximum allowed actions per type is reached. validateMaxActionsPerType(resolvedActionType, tenantDomain); String generatedActionId = UUID.randomUUID().toString(); - ActionDTO resolvedActionDTO = buildActionDTO(actionType, generatedActionId, action); - doPreAddActionValidations(actionType, resolvedActionDTO); + ActionDTO resolvedActionDTO = buildActionDTO(resolvedActionType, generatedActionId, action); + doPreAddActionValidations(resolvedActionType, resolvedActionDTO); daoFacade.addAction(resolvedActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); Action createdAction = getActionByActionId(actionType, generatedActionId, tenantDomain); @@ -106,14 +106,38 @@ public List getActionsByActionType(String actionType, String tenantDomai if (LOG.isDebugEnabled()) { LOG.debug(String.format("Retrieving Actions for Action Type: %s.", actionType)); } - List actionDTOS = daoFacade.getActionsByActionType(getActionTypeFromPath(actionType), + String resolvedActionType = getActionTypeFromPath(actionType); + List actionDTOS = daoFacade.getActionsByActionType(resolvedActionType, IdentityTenantUtil.getTenantId(tenantDomain)); return actionDTOS.stream() - .map(actionDTO -> buildAction(actionType, actionDTO)) + .map(actionDTO -> buildAction(resolvedActionType, actionDTO)) .collect(Collectors.toList()); } + /** + * Retrieve an action by action ID. + * + * @param actionType Action type. + * @param actionId Action ID. + * @param tenantDomain Tenant domain. + * @return Action object. + * @throws ActionMgtException if an error occurred while retrieving the action. + */ + @Override + public Action getActionByActionId(String actionType, String actionId, String tenantDomain) + throws ActionMgtException { + + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Retrieving Action of Action ID: %s", actionId)); + } + String resolvedActionType = getActionTypeFromPath(actionType); + ActionDTO actionDTO = daoFacade.getActionByActionId(resolvedActionType, actionId, + IdentityTenantUtil.getTenantId(tenantDomain)); + + return buildAction(resolvedActionType, actionDTO); + } + /** * Update an action of specified type in the given tenant. * This method performs an HTTP PATCH operation. @@ -136,8 +160,8 @@ public Action updateAction(String actionType, String actionId, Action action, St } String resolvedActionType = getActionTypeFromPath(actionType); ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - ActionDTO updatingActionDTO = buildActionDTO(actionType, actionId, action); - doPreUpdateActionValidations(actionType, updatingActionDTO); + ActionDTO updatingActionDTO = buildActionDTO(resolvedActionType, actionId, action); + doPreUpdateActionValidations(resolvedActionType, updatingActionDTO); daoFacade.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, action); @@ -184,7 +208,7 @@ public Action activateAction(String actionType, String actionId, String tenantDo ActionDTO activatedActionDTO = daoFacade.activateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ACTIVATE, actionType, actionId); - return buildAction(actionType, activatedActionDTO); + return buildAction(resolvedActionType, activatedActionDTO); } /** @@ -208,7 +232,7 @@ public Action deactivateAction(String actionType, String actionId, String tenant ActionDTO deactivatedActionDTO = daoFacade.deactivateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DEACTIVATE, actionType, actionId); - return buildAction(actionType, deactivatedActionDTO); + return buildAction(resolvedActionType, deactivatedActionDTO); } /** @@ -227,28 +251,6 @@ public Map getActionsCountPerType(String tenantDomain) throws A return daoFacade.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); } - /** - * Retrieve an action by action ID. - * - * @param actionType Action type. - * @param actionId Action ID. - * @param tenantDomain Tenant domain. - * @return Action object. - * @throws ActionMgtException if an error occurred while retrieving the action. - */ - @Override - public Action getActionByActionId(String actionType, String actionId, String tenantDomain) - throws ActionMgtException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving Action of Action ID: %s", actionId)); - } - ActionDTO actionDTO = daoFacade.getActionByActionId(getActionTypeFromPath(actionType), actionId, - IdentityTenantUtil.getTenantId(tenantDomain)); - - return buildAction(actionType, actionDTO); - } - /** * Update endpoint authentication of a given action. * @@ -411,10 +413,10 @@ private void doEndpointAuthenticationValidation(Authentication authentication) t private ActionDTO buildActionDTO(String actionType, String actionId, Action action) { - ActionBuilder actionBuilder = - ActionBuilderFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); - if (actionBuilder != null) { - ActionDTO actionDTO = actionBuilder.buildActionDTO(action); + ActionConverter actionConverter = + ActionConverterFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); + if (actionConverter != null) { + ActionDTO actionDTO = actionConverter.buildActionDTO(action); actionDTO.setId(actionId); actionDTO.setType(Action.ActionTypes.valueOf(actionType)); @@ -434,10 +436,14 @@ private ActionDTO buildActionDTO(String actionType, String actionId, Action acti private Action buildAction(String actionType, ActionDTO actionDTO) { - ActionBuilder actionBuilder = - ActionBuilderFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); - if (actionBuilder != null) { - return actionBuilder.buildAction(actionDTO); + if (actionDTO == null) { + return null; + } + + ActionConverter actionConverter = + ActionConverterFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); + if (actionConverter != null) { + return actionConverter.buildAction(actionDTO); } return new Action.ActionResponseBuilder() diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java similarity index 98% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java index 01dfc0155c43..562eb041a6bc 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java @@ -16,18 +16,18 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.action.management.service.impl.ActionManagementServiceImpl; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; @@ -67,7 +67,7 @@ public class ActionManagementServiceImplTest { @BeforeClass public void setUpClass() { - actionManagementService = ActionManagementServiceImpl.getInstance(); + actionManagementService = new ActionManagementServiceImpl(new ActionManagementDAOImpl()); } @BeforeMethod From 4986fd40383761049af82f4a1a8943e1445f6ba7 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:17:44 +0530 Subject: [PATCH 16/34] Add CachedBackedActionManagementServiceTest --- .../pom.xml | 2 +- .../management/dao/model/ActionDTO.java | 1 - .../factory/ActionConverterFactory.java | 2 +- .../internal/ActionMgtServiceComponent.java | 1 - .../management/model/Authentication.java | 3 +- .../impl/ActionManagementServiceImpl.java | 4 +- .../CacheBackedActionManagementService.java | 81 +-- ...reUpdatePasswordActionServiceImplTest.java | 486 ------------------ .../dao/ActionManagementDAOFacadeTest.java | 16 +- .../factory/ActionConverterFactoryTest.java | 69 +++ .../ActionPropertyResolverFactoryTest.java | 69 +++ .../ActionManagementServiceImplTest.java | 63 ++- ...acheBackedActionManagementServiceTest.java | 310 +++++++++++ .../action/management/util/TestUtil.java | 48 +- .../src/test/resources/testng.xml | 12 +- 15 files changed, 563 insertions(+), 604 deletions(-) delete mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index ed76d3e757a9..94b11a4fb9a3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -190,7 +190,7 @@ COVEREDRATIO - 0.68 + 0.60 diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java index f0b4c4ff47c2..2179a9aacb1d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java @@ -26,7 +26,6 @@ import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java index d1c85d359d66..d8517a2c9010 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java @@ -33,7 +33,7 @@ public class ActionConverterFactory { private static final Map actionConverters = new HashMap<>(); - public static ActionConverter getActionBuilder(Action.ActionTypes actionType) { + public static ActionConverter getActionConverter(Action.ActionTypes actionType) { switch (actionType) { case PRE_UPDATE_PASSWORD: diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index b22a6baf193a..6aeb12247242 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -34,7 +34,6 @@ import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; -import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java index 1b30bf18cee5..a987e450cd7e 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java @@ -21,10 +21,9 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; -import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import java.util.ArrayList; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index d6013731d2eb..d3f058523e11 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -414,7 +414,7 @@ private void doEndpointAuthenticationValidation(Authentication authentication) t private ActionDTO buildActionDTO(String actionType, String actionId, Action action) { ActionConverter actionConverter = - ActionConverterFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); + ActionConverterFactory.getActionConverter(Action.ActionTypes.valueOf(actionType)); if (actionConverter != null) { ActionDTO actionDTO = actionConverter.buildActionDTO(action); actionDTO.setId(actionId); @@ -441,7 +441,7 @@ private Action buildAction(String actionType, ActionDTO actionDTO) { } ActionConverter actionConverter = - ActionConverterFactory.getActionBuilder(Action.ActionTypes.valueOf(actionType)); + ActionConverterFactory.getActionConverter(Action.ActionTypes.valueOf(actionType)); if (actionConverter != null) { return actionConverter.buildAction(actionDTO); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java index c52b22aecb0b..e37b36ae33a5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java @@ -57,8 +57,9 @@ public static CacheBackedActionManagementService getInstance() { @Override public Action addAction(String actionType, Action action, String tenantDomain) throws ActionMgtException { + Action createdAction = ACTION_MGT_SERVICE.addAction(actionType, action, tenantDomain); actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); - return ACTION_MGT_SERVICE.addAction(actionType, action, tenantDomain); + return createdAction; } @Override @@ -93,41 +94,6 @@ public List getActionsByActionType(String actionType, String tenantDomai return actions; } - @Override - public Action updateAction(String actionType, String actionId, Action action, String tenantDomain) - throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); - return ACTION_MGT_SERVICE.updateAction(actionType, actionId, action, tenantDomain); - } - - @Override - public void deleteAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); - ACTION_MGT_SERVICE.deleteAction(actionType, actionId, tenantDomain); - } - - @Override - public Action activateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); - return ACTION_MGT_SERVICE.activateAction(actionType, actionId, tenantDomain); - } - - @Override - public Action deactivateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); - return ACTION_MGT_SERVICE.deactivateAction(actionType, actionId, tenantDomain); - } - - @Override - public Map getActionsCountPerType(String tenantDomain) throws ActionMgtException { - - return ACTION_MGT_SERVICE.getActionsCountPerType(tenantDomain); - } - @Override public Action getActionByActionId(String actionType, String actionId, String tenantDomain) throws ActionMgtException { @@ -162,13 +128,52 @@ public Action getActionByActionId(String actionType, String actionId, String ten return action; } + @Override + public Action updateAction(String actionType, String actionId, Action action, String tenantDomain) + throws ActionMgtException { + + Action updatedAction = ACTION_MGT_SERVICE.updateAction(actionType, actionId, action, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return updatedAction; + } + + @Override + public void deleteAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { + + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + ACTION_MGT_SERVICE.deleteAction(actionType, actionId, tenantDomain); + } + + @Override + public Action activateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { + + Action activatedAction = ACTION_MGT_SERVICE.activateAction(actionType, actionId, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return activatedAction; + } + + @Override + public Action deactivateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { + + Action deactivatedAction = ACTION_MGT_SERVICE.deactivateAction(actionType, actionId, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return deactivatedAction; + } + + @Override + public Map getActionsCountPerType(String tenantDomain) throws ActionMgtException { + + return ACTION_MGT_SERVICE.getActionsCountPerType(tenantDomain); + } + @Override public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, String tenantDomain) throws ActionMgtException { + Action updatedAction = ACTION_MGT_SERVICE.updateActionEndpointAuthentication(actionType, actionId, + authentication, tenantDomain); actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); - return ACTION_MGT_SERVICE.updateActionEndpointAuthentication(actionType, actionId, authentication, - tenantDomain); + return updatedAction; } private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheKey cacheKey, String tenantDomain) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java deleted file mode 100644 index 16400b29f3cc..000000000000 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/PreUpdatePasswordActionServiceImplTest.java +++ /dev/null @@ -1,486 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.action.management; - -import org.apache.commons.lang.StringUtils; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; -import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; -import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; -import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; -import org.wso2.carbon.identity.action.management.util.TestUtil; -import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtClientException; -import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtException; -import org.wso2.carbon.identity.certificate.management.exception.CertificateMgtServerException; -import org.wso2.carbon.identity.certificate.management.model.Certificate; -import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.core.internal.IdentityCoreServiceDataHolder; -import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; -import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; -import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; - -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE; -import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; -import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; -import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_PATH; -import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; -import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; -import static org.wso2.carbon.identity.action.management.util.TestUtil.UPDATED_CERTIFICATE; -import static org.wso2.carbon.identity.certificate.management.constant.CertificateMgtErrors.ERROR_INVALID_CERTIFICATE_CONTENT; - -/** - * This class is a test suite for the ActionManagementDAOImpl class. - * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOImpl class - * for PRE_UPDATE_PASSWORD action type. - */ -@WithCarbonHome -@WithH2Database(files = {"dbscripts/h2.sql"}) -@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) -public class PreUpdatePasswordActionServiceImplTest { - - private ActionManagementService actionManagementService; - private CertificateManagementService certificateManagementService; - - private PreUpdatePasswordAction preUpdatePasswordAction; - private Certificate certificate; - private CertificateMgtServerException serverException; - private CertificateMgtClientException clientException; - - @BeforeClass - public void setUpClass() { - - actionManagementService = ActionManagementServiceImpl.getInstance(); - } - - @BeforeMethod - public void setUp() throws SecretManagementException { - - SecretManagerImpl secretManager = mock(SecretManagerImpl.class); - SecretType secretType = mock(SecretType.class); - ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); - when(secretType.getId()).thenReturn("secretId"); - when(secretManager.getSecretType(any())).thenReturn(secretType); - - certificateManagementService = mock(CertificateManagementService.class); - ActionMgtServiceComponentHolder.getInstance() - .setCertificateManagementService(certificateManagementService); - - serverException = new CertificateMgtServerException("server_error_message", "server_error_description", "65030", - new Throwable()); - clientException = new CertificateMgtClientException(ERROR_INVALID_CERTIFICATE_CONTENT.getMessage(), - ERROR_INVALID_CERTIFICATE_CONTENT.getDescription(), ERROR_INVALID_CERTIFICATE_CONTENT.getCode()); - } - - @Test(priority = 1) - public void testAddPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { - - PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( - "PreUpdatePassword", - "To configure PreUpdatePassword", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin"), - PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, - CERTIFICATE); - certificate = new Certificate.Builder() - .id(String.valueOf(CERTIFICATE_ID)) - .name(CERTIFICATE_NAME) - .certificateContent(CERTIFICATE) - .build(); - - doReturn(CERTIFICATE_ID).when(certificateManagementService).addCertificate(any(), any()); - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - preUpdatePasswordAction = (PreUpdatePasswordAction) actionManagementService.addAction(PRE_UPDATE_PASSWORD_PATH, - actionModel, TENANT_DOMAIN); - - Assert.assertNotNull(preUpdatePasswordAction.getId()); - Assert.assertEquals(actionModel.getName(), preUpdatePasswordAction.getName()); - Assert.assertEquals(actionModel.getDescription(), preUpdatePasswordAction.getDescription()); - Assert.assertEquals(PRE_UPDATE_PASSWORD_TYPE, preUpdatePasswordAction.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, preUpdatePasswordAction.getStatus()); - Assert.assertEquals(actionModel.getEndpoint().getUri(), preUpdatePasswordAction.getEndpoint().getUri()); - Assert.assertEquals(actionModel.getEndpoint().getAuthentication().getType(), - preUpdatePasswordAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(actionModel.getPasswordSharingFormat(), preUpdatePasswordAction.getPasswordSharingFormat()); - Assert.assertNotNull(preUpdatePasswordAction.getCertificate()); - Assert.assertEquals(CERTIFICATE_ID, preUpdatePasswordAction.getCertificate().getId()); - Assert.assertEquals(CERTIFICATE_NAME, preUpdatePasswordAction.getCertificate().getName()); - } - - @Test(priority = 2, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testGetPreUpdatePasswordActionByActionId() throws ActionMgtException, CertificateMgtException { - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) actionManagementService - .getActionByActionId(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), TENANT_DOMAIN); - - Assert.assertEquals(preUpdatePasswordAction.getId(), fetchedAction.getId()); - Assert.assertEquals(preUpdatePasswordAction.getName(), fetchedAction.getName()); - Assert.assertEquals(preUpdatePasswordAction.getDescription(), fetchedAction.getDescription()); - Assert.assertEquals(preUpdatePasswordAction.getType(), fetchedAction.getType()); - Assert.assertEquals(preUpdatePasswordAction.getStatus(), fetchedAction.getStatus()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), fetchedAction.getEndpoint().getUri()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), - fetchedAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals( - preUpdatePasswordAction.getPasswordSharingFormat(), fetchedAction.getPasswordSharingFormat()); - Assert.assertNotNull(fetchedAction.getCertificate()); - Assert.assertEquals(preUpdatePasswordAction.getCertificate().getId(), fetchedAction.getCertificate().getId()); - Assert.assertEquals( - preUpdatePasswordAction.getCertificate().getName(), fetchedAction.getCertificate().getName()); - } - - @Test(priority = 3, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testGetPreUpdatePasswordActionsByActionType() throws ActionMgtException, CertificateMgtException { - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - List preUpdatePasswordActionList = - actionManagementService.getActionsByActionType(PRE_UPDATE_PASSWORD_PATH, TENANT_DOMAIN); - - Assert.assertEquals(1, preUpdatePasswordActionList.size()); - PreUpdatePasswordAction fetchedAction = (PreUpdatePasswordAction) preUpdatePasswordActionList.get(0); - Assert.assertEquals(preUpdatePasswordAction.getId(), fetchedAction.getId()); - Assert.assertEquals(preUpdatePasswordAction.getName(), fetchedAction.getName()); - Assert.assertEquals(preUpdatePasswordAction.getDescription(), fetchedAction.getDescription()); - Assert.assertEquals(preUpdatePasswordAction.getType(), fetchedAction.getType()); - Assert.assertEquals(preUpdatePasswordAction.getStatus(), fetchedAction.getStatus()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), fetchedAction.getEndpoint().getUri()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), - fetchedAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals( - preUpdatePasswordAction.getPasswordSharingFormat(), fetchedAction.getPasswordSharingFormat()); - Assert.assertNotNull(fetchedAction.getCertificate()); - Assert.assertEquals(preUpdatePasswordAction.getCertificate().getId(), fetchedAction.getCertificate().getId()); - Assert.assertEquals( - preUpdatePasswordAction.getCertificate().getName(), fetchedAction.getCertificate().getName()); - - } - - @Test(priority = 4, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testUpdatePreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { - - PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( - "Updated PreUpdatePassword Action", - "To configure PreUpdatePassword of wso2.com organization", - "https://my-extension.com/pre-update-password", - TestUtil.buildMockNoneAuthentication(), - PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, - UPDATED_CERTIFICATE); - - certificate = new Certificate.Builder() - .id(String.valueOf(CERTIFICATE_ID)) - .name(CERTIFICATE_NAME) - .certificateContent(UPDATED_CERTIFICATE) - .build(); - - doNothing().when(certificateManagementService).updateCertificateContent(anyString(), anyString(), anyString()); - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - - PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) actionManagementService.updateAction( - PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), updateActionModel, TENANT_DOMAIN); - - Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); - Assert.assertEquals(updateActionModel.getName(), updatedAction.getName()); - Assert.assertEquals(updateActionModel.getDescription(), updatedAction.getDescription()); - Assert.assertEquals(preUpdatePasswordAction.getType(), updatedAction.getType()); - Assert.assertEquals(preUpdatePasswordAction.getStatus(), updatedAction.getStatus()); - Assert.assertEquals(updateActionModel.getEndpoint().getUri(), updatedAction.getEndpoint().getUri()); - Assert.assertEquals(updateActionModel.getEndpoint().getAuthentication().getType(), - updatedAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(updateActionModel.getPasswordSharingFormat(), updatedAction.getPasswordSharingFormat()); - Assert.assertNotNull(updatedAction.getCertificate()); - Assert.assertEquals(certificate.getId(), updatedAction.getCertificate().getId()); - Assert.assertEquals(certificate.getName(), updatedAction.getCertificate().getName()); - Assert.assertEquals(certificate.getCertificateContent(), - updatedAction.getCertificate().getCertificateContent()); - - preUpdatePasswordAction = updatedAction; - } - - @Test(priority = 5, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testGetPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { - - doThrow(serverException).when(certificateManagementService).getCertificate(anyString(), anyString()); - try { - actionManagementService.getActionByActionId(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), - TENANT_DOMAIN); - Assert.fail("Successful retrieval of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(e.getClass(), ActionMgtServerException.class); - Assert.assertEquals(e.getMessage(), - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtServerException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } - } - - @Test(priority = 6, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testUpdatePreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { - - PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( - "Updated PreUpdatePassword Action", - "To configure PreUpdatePassword of wso2.com organization", - "https://my-extension.com/pre-update-password", - TestUtil.buildMockNoneAuthentication(), - PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, - CERTIFICATE); - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - doThrow(serverException).when(certificateManagementService).updateCertificateContent(any(), any(), any()); - try { - actionManagementService.updateAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), - updateActionModel, TENANT_DOMAIN); - Assert.fail("Successful update of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(ActionMgtServerException.class, e.getClass()); - Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION.getMessage(), - e.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtServerException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } - } - - @Test(priority = 7, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testUpdatePreUpdatePasswordActionWithClientErrorFromCertificate() throws CertificateMgtException { - - PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction( - "Updated PreUpdatePassword Action", - "To configure PreUpdatePassword of wso2.com organization", - "https://my-extension.com/pre-update-password", - TestUtil.buildMockNoneAuthentication(), - PreUpdatePasswordAction.PasswordFormat.SHA256_HASHED, - CERTIFICATE); - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - doThrow(clientException).when(certificateManagementService).updateCertificateContent(any(), any(), any()); - try { - actionManagementService.updateAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), - updateActionModel, TENANT_DOMAIN); - Assert.fail("Successful update of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(ActionMgtClientException.class, e.getClass()); - Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE.getMessage(), - e.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtClientException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtClientException was not found in the exception chain"); - } - } - - @Test(priority = 8, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testDeleteCertificateOfPreUpdatePasswordActionWithServerError() throws CertificateMgtException { - - PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, - null, null, null, StringUtils.EMPTY); - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - doThrow(serverException).when(certificateManagementService).deleteCertificate(any(), any()); - try { - actionManagementService.updateAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), - updateActionModel, TENANT_DOMAIN); - Assert.fail("Successful update of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(ActionMgtServerException.class, e.getClass()); - Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION.getMessage(), - e.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtServerException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } - } - - @Test(priority = 9, dependsOnMethods = "testUpdatePreUpdatePasswordAction") - public void testDeleteCertificateOfPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { - - PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, - null, null, null, StringUtils.EMPTY); - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - doNothing().when(certificateManagementService).deleteCertificate(anyString(), anyString()); - - PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) actionManagementService.updateAction( - PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), updateActionModel, TENANT_DOMAIN); - - Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); - Assert.assertEquals(preUpdatePasswordAction.getName(), updatedAction.getName()); - Assert.assertEquals(preUpdatePasswordAction.getDescription(), updatedAction.getDescription()); - Assert.assertEquals(preUpdatePasswordAction.getType(), updatedAction.getType()); - Assert.assertEquals(preUpdatePasswordAction.getStatus(), updatedAction.getStatus()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), updatedAction.getEndpoint().getUri()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), - updatedAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(preUpdatePasswordAction.getPasswordSharingFormat(), - updatedAction.getPasswordSharingFormat()); - Assert.assertNull(updatedAction.getCertificate()); - - preUpdatePasswordAction = updatedAction; - } - - @Test(priority = 10, dependsOnMethods = "testDeleteCertificateOfPreUpdatePasswordAction") - public void testAddCertificateOfPreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { - - PreUpdatePasswordAction updateActionModel = TestUtil.buildMockPreUpdatePasswordAction(null, null, - null, null, null, CERTIFICATE); - - doReturn(CERTIFICATE_ID).when(certificateManagementService).addCertificate(any(), anyString()); - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - - PreUpdatePasswordAction updatedAction = (PreUpdatePasswordAction) actionManagementService.updateAction( - PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), updateActionModel, TENANT_DOMAIN); - - Assert.assertEquals(preUpdatePasswordAction.getId(), updatedAction.getId()); - Assert.assertEquals(preUpdatePasswordAction.getName(), updatedAction.getName()); - Assert.assertEquals(preUpdatePasswordAction.getDescription(), updatedAction.getDescription()); - Assert.assertEquals(preUpdatePasswordAction.getType(), updatedAction.getType()); - Assert.assertEquals(preUpdatePasswordAction.getStatus(), updatedAction.getStatus()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getUri(), updatedAction.getEndpoint().getUri()); - Assert.assertEquals(preUpdatePasswordAction.getEndpoint().getAuthentication().getType(), - updatedAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(preUpdatePasswordAction.getPasswordSharingFormat(), - updatedAction.getPasswordSharingFormat()); - - Assert.assertNotNull(updatedAction.getCertificate()); - Assert.assertEquals(certificate.getId(), updatedAction.getCertificate().getId()); - Assert.assertEquals(certificate.getName(), updatedAction.getCertificate().getName()); - Assert.assertEquals(certificate.getCertificateContent(), - updatedAction.getCertificate().getCertificateContent()); - - preUpdatePasswordAction = updatedAction; - } - - @Test(priority = 8, dependsOnMethods = "testAddPreUpdatePasswordAction") - public void testDeletePreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { - - doReturn(certificate).when(certificateManagementService).getCertificate(anyString(), anyString()); - doThrow(serverException).when(certificateManagementService).deleteCertificate(any(), any()); - try { - actionManagementService.deleteAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), - TENANT_DOMAIN); - Assert.fail("Successful deletion of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(ActionMgtServerException.class, e.getClass()); - Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_DELETING_ACTION.getMessage(), - e.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtServerException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } - } - - @Test(priority = 11) - public void testDeletePreUpdatePasswordAction() throws ActionMgtException, CertificateMgtException { - - doNothing().when(certificateManagementService).deleteCertificate(anyString(), anyString()); - - actionManagementService.deleteAction(PRE_UPDATE_PASSWORD_PATH, preUpdatePasswordAction.getId(), TENANT_DOMAIN); - - Assert.assertNull(actionManagementService.getActionByActionId(PRE_UPDATE_PASSWORD_PATH, - preUpdatePasswordAction.getId(), TENANT_DOMAIN)); - } - - @Test(priority = 12) - public void testAddPreUpdatePasswordActionWithServerErrorFromCertificate() throws CertificateMgtException { - - PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( - "PreUpdatePassword", - "To configure PreUpdatePassword", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin"), - PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, - CERTIFICATE); - - doThrow(serverException).when(certificateManagementService).addCertificate(any(), any()); - try { - actionManagementService.addAction(PRE_UPDATE_PASSWORD_PATH, actionModel, TENANT_DOMAIN); - Assert.fail("Successful addition of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(ActionMgtServerException.class, e.getClass()); - Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION.getMessage(), - e.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtServerException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } - } - - @Test(priority = 13) - public void testAddPreUpdatePasswordActionWithClientErrorFromCertificate() throws CertificateMgtException { - - PreUpdatePasswordAction actionModel = TestUtil.buildMockPreUpdatePasswordAction( - "PreUpdatePassword", - "To configure PreUpdatePassword", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin"), - PreUpdatePasswordAction.PasswordFormat.PLAIN_TEXT, - CERTIFICATE); - - doThrow(clientException).when(certificateManagementService).addCertificate(any(), any()); - try { - actionManagementService.addAction(PRE_UPDATE_PASSWORD_PATH, actionModel, TENANT_DOMAIN); - Assert.fail("Successful addition of the action without an exception is considered as a failure"); - } catch (ActionMgtException e) { - Assert.assertEquals(ActionMgtClientException.class, e.getClass()); - Assert.assertEquals(ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_CERTIFICATE.getMessage(), - e.getMessage()); - for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof CertificateMgtClientException) { - return; - } - } - Assert.fail("Expected cause of type CertificateMgtServerException was not found in the exception chain"); - } - } -} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index e1308109a5cc..1e457eb10f48 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -46,6 +46,11 @@ import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -53,12 +58,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; @@ -69,7 +68,7 @@ import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_ID; -import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION_UPDATED; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; @@ -250,8 +249,7 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty .description(TEST_ACTION_DESCRIPTION_UPDATED) .endpoint(new EndpointConfig.EndpointConfigBuilder() .uri(TEST_ACTION_URI_UPDATED) - .authentication(TestUtil.buildMockBearerAuthentication( - TEST_ACCESS_TOKEN_SECRET_REFERENCE)) + .authentication(TestUtil.buildMockBearerAuthentication(TEST_ACCESS_TOKEN)) .build()) .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED) .property(CERTIFICATE_PROPERTY_NAME, diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java new file mode 100644 index 000000000000..49487b032778 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.factory; + +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.ActionConverter; +import org.wso2.carbon.identity.action.management.model.Action; + +import static org.mockito.Mockito.doReturn; + +/** + * Action Converter Factory Test. + */ +public class ActionConverterFactoryTest { + + private final Action.ActionTypes actionType = Action.ActionTypes.PRE_UPDATE_PASSWORD; + @Mock + private ActionConverter mockActionConverter; + + @BeforeMethod + public void setUp() { + + MockitoAnnotations.openMocks(this); + doReturn(actionType).when(mockActionConverter).getSupportedActionType(); + } + + @Test + public void testRegisterActionConverter() { + + ActionConverterFactory.registerActionConverter(mockActionConverter); + ActionConverter registeredResult = ActionConverterFactory.getActionConverter(actionType); + Assert.assertEquals(registeredResult, mockActionConverter); + } + + @Test(dependsOnMethods = {"testRegisterActionConverter"}) + public void testUnregisterActionConverter() { + + ActionConverterFactory.unregisterActionConverter(mockActionConverter); + ActionConverter unregisteredResult = ActionConverterFactory.getActionConverter(actionType); + Assert.assertNull(unregisteredResult); + } + + @Test(dependsOnMethods = {"testUnregisterActionConverter"}) + public void testGetActionConverterNotFound() { + + ActionConverter result = ActionConverterFactory.getActionConverter(actionType); + Assert.assertNull(result); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java new file mode 100644 index 000000000000..0182f6c95392 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.factory; + +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.model.Action; + +import static org.mockito.Mockito.doReturn; + +/** + * Action Property Resolver Factory Test. + */ +public class ActionPropertyResolverFactoryTest { + + private final Action.ActionTypes actionType = Action.ActionTypes.PRE_UPDATE_PASSWORD; + @Mock + private ActionPropertyResolver mockActionPropertyResolver; + + @BeforeMethod + public void setUp() { + + MockitoAnnotations.openMocks(this); + doReturn(actionType).when(mockActionPropertyResolver).getSupportedActionType(); + } + + @Test + public void testRegisterActionPropertyResolver() { + + ActionPropertyResolverFactory.registerActionPropertyResolver(mockActionPropertyResolver); + ActionPropertyResolver registeredResult = ActionPropertyResolverFactory.getActionPropertyResolver(actionType); + Assert.assertEquals(registeredResult, mockActionPropertyResolver); + } + + @Test(dependsOnMethods = {"testRegisterActionPropertyResolver"}) + public void testUnregisterActionPropertyResolver() { + + ActionPropertyResolverFactory.unregisterActionPropertyResolver(mockActionPropertyResolver); + ActionPropertyResolver unregisteredResult = ActionPropertyResolverFactory.getActionPropertyResolver(actionType); + Assert.assertNull(unregisteredResult); + } + + @Test(dependsOnMethods = {"testUnregisterActionPropertyResolver"}) + public void testGetActionPropertyResolverNotFound() { + + ActionPropertyResolver result = ActionPropertyResolverFactory.getActionPropertyResolver(actionType); + Assert.assertNull(result); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java index 562eb041a6bc..16e6a5152413 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java @@ -18,6 +18,7 @@ package org.wso2.carbon.identity.action.management.service; +import org.apache.commons.lang.StringUtils; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; @@ -46,8 +47,21 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_PATH; -import static org.wso2.carbon.identity.action.management.util.TestUtil.SAMPLE_ACCESS_TOKEN; import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_INVALID_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_INVALID_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; /** * This class is a test suite for the ActionManagementServiceImpl class. @@ -76,7 +90,7 @@ public void setUp() throws SecretManagementException { SecretManagerImpl secretManager = mock(SecretManagerImpl.class); SecretType secretType = mock(SecretType.class); ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); - when(secretType.getId()).thenReturn("secretId"); + when(secretType.getId()).thenReturn(TestUtil.TEST_SECRET_TYPE_ID); when(secretManager.getSecretType(any())).thenReturn(secretType); } @@ -84,10 +98,10 @@ public void setUp() throws SecretManagementException { public void testAddAction() throws ActionMgtException, SecretManagementException { Action creatingAction = TestUtil.buildMockAction( - "PreIssueAccessToken", - "To configure PreIssueAccessToken", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin")); + TEST_ACTION_NAME, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)); preIssueAccessTokenAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); Assert.assertNotNull(preIssueAccessTokenAction.getId()); @@ -117,10 +131,10 @@ public void testAddAction() throws ActionMgtException, SecretManagementException expectedExceptionsMessageRegExp = "Unable to create an Action.") public void testAddActionWithInvalidData() throws ActionMgtException { Action creatingAction = TestUtil.buildMockAction( - "PreIssueAccessToken_#1", - "To configure PreIssueAccessToken", - "https://example.com", - TestUtil.buildMockAPIKeyAuthentication("-test-header", "thisisapikey")); + TEST_INVALID_ACTION_NAME, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockAPIKeyAuthentication(TEST_INVALID_API_KEY_HEADER, TEST_API_KEY_VALUE)); Action action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); Assert.assertNull(action); } @@ -129,10 +143,10 @@ public void testAddActionWithInvalidData() throws ActionMgtException { expectedExceptionsMessageRegExp = "Unable to create an Action.") public void testAddActionWithEmptyData() throws ActionMgtException { Action creatingAction = TestUtil.buildMockAction( - "", - "To configure PreIssueAccessToken", - "https://example.com", - TestUtil.buildMockBasicAuthentication(null, "admin")); + StringUtils.EMPTY, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(null, TEST_PASSWORD)); Action action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); Assert.assertNull(action); } @@ -142,10 +156,10 @@ public void testAddActionWithEmptyData() throws ActionMgtException { public void testAddMaximumActionsPerType() throws ActionMgtException { Action creatingAction = TestUtil.buildMockAction( - "PreIssueAccessToken", - "To configure PreIssueAccessToken", - "https://example.com", - TestUtil.buildMockBasicAuthentication("admin", "admin")); + TEST_ACTION_NAME, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)); preIssueAccessTokenAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); } @@ -226,10 +240,10 @@ public void testGetActionsByActionTypeFromCache() throws ActionMgtException, Sec public void testUpdateAction() throws ActionMgtException, SecretManagementException { Action updatingAction = TestUtil.buildMockAction( - "Pre Issue Access Token", - "To update configuration pre issue access token", - "https://sample.com", - TestUtil.buildMockAPIKeyAuthentication("header", "value")); + TEST_ACTION_NAME_UPDATED, + TEST_ACTION_DESCRIPTION_UPDATED, + TEST_ACTION_URI, + TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, TEST_API_KEY_VALUE)); Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), updatingAction, TENANT_DOMAIN); Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); @@ -286,7 +300,8 @@ public void testGetActionsCountPerType() throws ActionMgtException { public void testUpdateEndpointConfigWithSameAuthenticationType() throws ActionMgtException, SecretManagementException { - Authentication authentication = TestUtil.buildMockAPIKeyAuthentication("newheader", "newvalue"); + Authentication authentication = TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER_UPDATED, + TEST_API_KEY_VALUE_UPDATED); Action result = actionManagementService.updateActionEndpointAuthentication( PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), authentication, TENANT_DOMAIN); Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); @@ -302,7 +317,7 @@ public void testUpdateEndpointConfigWithSameAuthenticationType() throws ActionMg public void testUpdateEndpointConfigWithDifferentAuthenticationType() throws ActionMgtException, SecretManagementException { - Authentication authentication = TestUtil.buildMockBearerAuthentication(SAMPLE_ACCESS_TOKEN); + Authentication authentication = TestUtil.buildMockBearerAuthentication(TEST_ACCESS_TOKEN); Action result = actionManagementService.updateActionEndpointAuthentication( PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), authentication, TENANT_DOMAIN); Assert.assertEquals(Authentication.Type.BEARER, result.getEndpoint().getAuthentication().getType()); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java new file mode 100644 index 000000000000..0b21e5becb30 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.service; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.service.impl.ActionManagementServiceImpl; +import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; +import org.wso2.carbon.identity.action.management.util.TestUtil; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; +import org.wso2.carbon.identity.common.testng.WithH2Database; +import org.wso2.carbon.identity.common.testng.WithRealmService; +import org.wso2.carbon.identity.core.internal.IdentityCoreServiceDataHolder; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_PATH; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; + +/** + * Test class for CacheBackedActionManagement. + */ +@WithCarbonHome +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) +public class CacheBackedActionManagementServiceTest { + + private ActionManagementServiceImpl actionManagementServiceImpl; + private CacheBackedActionManagementService cacheBackedActionManagementService; + + private final List mockedActionsList = new ArrayList<>(); + private Action mockedAction; + + @BeforeClass + public void setUpClass() { + + cacheBackedActionManagementService = CacheBackedActionManagementService.getInstance(); + mockedAction = new Action.ActionResponseBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .status(Action.Status.ACTIVE) + .endpoint(TestUtil.buildMockEndpointConfig(TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD))) + .build(); + mockedActionsList.add(mockedAction); + } + + @BeforeMethod + public void setUp() throws Exception { + + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + when(secretType.getId()).thenReturn(TestUtil.TEST_SECRET_TYPE_ID); + when(secretManager.getSecretType(any())).thenReturn(secretType); + + actionManagementServiceImpl = mock(ActionManagementServiceImpl.class); + // Set ACTION_MGT_SERVICE field using reflection + setFinalField(cacheBackedActionManagementService, "ACTION_MGT_SERVICE", actionManagementServiceImpl); + } + + @Test(priority = 1) + public void testGetActionsByActionTypeFromDB() throws ActionMgtException { + + doReturn(mockedActionsList).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + + List actions = cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, + TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).getActionsByActionType(any(), any()); + Assert.assertEquals(1, actions.size()); + Action result = actions.get(0); + assertAction(result); + } + + @Test(priority = 2, dependsOnMethods = "testGetActionsByActionTypeFromDB") + public void testGetActionsByActionTypeFromCache() throws ActionMgtException { + + doReturn(null).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + + List actions = cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, + TENANT_DOMAIN); + verify(actionManagementServiceImpl, never()).getActionsByActionType(any(), any()); + Assert.assertNotNull(actions); + Assert.assertEquals(1, actions.size()); + Action result = actions.get(0); + assertAction(result); + } + + @Test(priority = 3, dependsOnMethods = "testGetActionsByActionTypeFromDB") + public void testGetActionsByActionIdFromCache() throws ActionMgtException { + + doReturn(null).when(actionManagementServiceImpl).getActionByActionId(any(), any(), any()); + + Action action = cacheBackedActionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, never()).getActionByActionId(any(), any(), any()); + Assert.assertNotNull(action); + assertAction(action); + } + + @Test(priority = 4) + public void testAddAction() throws ActionMgtException { + + doReturn(mockedAction).when(actionManagementServiceImpl).addAction(any(), any(), any()); + + Action action = cacheBackedActionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + mockedAction, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).addAction(any(), any(), any()); + Assert.assertNotNull(action); + checkCacheInvalidation(); + } + + @Test(priority = 5) + public void testGetActionsByActionIdFromDB() throws ActionMgtException { + + doReturn(mockedAction).when(actionManagementServiceImpl).getActionByActionId(any(), any(), any()); + + Action action = cacheBackedActionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).getActionByActionId(any(), any(), any()); + Assert.assertNotNull(action); + assertAction(action); + } + + @Test(priority = 6) + public void testUpdateAction() throws ActionMgtException { + + doReturn(mockedAction).when(actionManagementServiceImpl).updateAction(any(), any(), any(), any()); + + Action action = cacheBackedActionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, mockedAction, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).updateAction(any(), any(), any(), any()); + Assert.assertNotNull(action); + checkCacheInvalidation(); + } + + @Test(priority = 7) + public void testDeactivateAction() throws ActionMgtException { + + // Update cache. + doReturn(mockedActionsList).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); + + cacheBackedActionManagementService.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).deactivateAction(any(), any(), any()); + checkCacheInvalidation(); + } + + @Test(priority = 8) + public void testActivateAction() throws ActionMgtException { + + // Update cache. + doReturn(mockedActionsList).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); + + cacheBackedActionManagementService.activateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).activateAction(any(), any(), any()); + checkCacheInvalidation(); + } + + @Test(priority = 9) + public void testUpdateActionEndpointAuthentication() throws ActionMgtException { + + // Update cache. + doReturn(mockedAction).when(actionManagementServiceImpl).updateActionEndpointAuthentication(any(), any(), + any(), any()); + + Action action = cacheBackedActionManagementService.updateActionEndpointAuthentication( + PRE_ISSUE_ACCESS_TOKEN_PATH, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + mockedAction.getEndpoint().getAuthentication(), TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).updateActionEndpointAuthentication(any(), + any(), any(), any()); + Assert.assertNotNull(action); + checkCacheInvalidation(); + } + + @Test(priority = 14) + public void testDeleteAction() throws ActionMgtException { + + // Update cache. + doNothing().when(actionManagementServiceImpl).deleteAction(any(), any(), any()); + + cacheBackedActionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, mockedAction.getId(), + TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).deleteAction(any(), any(), any()); + checkCacheInvalidation(); + } + + @Test(priority = 10) + public void testGetActionsCountPerType() throws ActionMgtException { + + Map mockedActionMap = new HashMap<>(); + mockedActionMap.put(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), 1); + mockedActionMap.put(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType(), 2); + doReturn(mockedActionMap).when(actionManagementServiceImpl).getActionsCountPerType(any()); + + Map actionMap = cacheBackedActionManagementService.getActionsCountPerType(TENANT_DOMAIN); + Assert.assertNotNull(actionMap.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType())); + Assert.assertNotNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PROFILE.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_REGISTRATION.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.AUTHENTICATION.getActionType())); + + Assert.assertEquals(actionMap.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType()).intValue(), 1); + Assert.assertEquals(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType()).intValue(), 2); + } + + private void checkCacheInvalidation() throws ActionMgtException { + + reset(actionManagementServiceImpl); + doReturn(null).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + doReturn(null).when(actionManagementServiceImpl).getActionByActionId(any(), any(), any()); + + List actions = cacheBackedActionManagementService.getActionsByActionType( + mockedAction.getType().getPathParam(), TENANT_DOMAIN); + Assert.assertNull(actions); + verify(actionManagementServiceImpl, times(1)).getActionsByActionType(any(), any()); + + Action action = cacheBackedActionManagementService.getActionByActionId(mockedAction.getType().getPathParam(), + mockedAction.getId(), TENANT_DOMAIN); + Assert.assertNull(action); + verify(actionManagementServiceImpl, times(1)).getActionByActionId(any(), any(), any()); + } + + private void assertAction(Action action) { + + Assert.assertEquals(action.getId(), mockedAction.getId()); + Assert.assertEquals(action.getName(), mockedAction.getName()); + Assert.assertEquals(action.getDescription(), mockedAction.getDescription()); + Assert.assertEquals(action.getType(), mockedAction.getType()); + Assert.assertEquals(action.getStatus(), mockedAction.getStatus()); + Assert.assertEquals(action.getEndpoint().getUri(), mockedAction.getEndpoint().getUri()); + Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), + mockedAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(action.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME) + .getValue(), + mockedAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME) + .getValue()); + Assert.assertEquals(action.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD) + .getValue(), + mockedAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD) + .getValue()); + } + + private void setFinalField(Object target, String fieldName, Object value) throws Exception { + + Field field; + try { + field = target.getClass().getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + field = target.getClass().getSuperclass().getDeclaredField(fieldName); + } + + field.setAccessible(true); + + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + + field.set(target, value); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index cb230b72f8eb..13aa0c49cf84 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -21,9 +21,6 @@ import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction; -import org.wso2.carbon.identity.action.management.model.PreUpdatePasswordAction.PasswordFormat; -import org.wso2.carbon.identity.certificate.management.model.Certificate; import java.util.UUID; @@ -39,7 +36,6 @@ public class TestUtil { public static final String PRE_UPDATE_PASSWORD_TYPE = Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType(); public static final String PRE_ISSUE_ACCESS_TOKEN_PATH = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getPathParam(); - public static final String PRE_UPDATE_PASSWORD_PATH = Action.ActionTypes.PRE_UPDATE_PASSWORD.getPathParam(); public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); @@ -47,43 +43,44 @@ public class TestUtil { public static final String TEST_SECRET_TYPE_ID = "fcaf81a9-0d58-4cf4-98c8-fde2f3ba8df2"; public static final String TEST_ACTION_NAME = "Test Action Name"; + public static final String TEST_ACTION_NAME_UPDATED = "Updated Test Action Name"; + public static final String TEST_INVALID_ACTION_NAME = "PreIssueAccessToken_#1"; public static final String TEST_ACTION_DESCRIPTION = "Test Action description"; + public static final String TEST_ACTION_DESCRIPTION_UPDATED = "Updated Test Action description"; public static final String TEST_ACTION_URI = "https://example.com"; + public static final String TEST_ACTION_URI_UPDATED = "https://sample.com"; + public static final String TEST_USERNAME = "sampleUsername"; public static final String TEST_USERNAME_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.BASIC.getName(), Authentication.Property.USERNAME.getName()); public static final String TEST_PASSWORD = "samplePassword"; public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.BASIC.getName(), Authentication.Property.PASSWORD.getName()); + public static final String TEST_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName()); public static final String TEST_API_KEY_HEADER = "sampleHeader"; public static final String TEST_API_KEY_HEADER_UPDATED = "UpdatedSampleHeader"; + public static final String TEST_INVALID_API_KEY_HEADER = "-test-header"; + public static final String TEST_API_KEY_VALUE = "sampleValue"; + public static final String TEST_API_KEY_VALUE_UPDATED = "UpdatedSampleValue"; public static final String TEST_API_KEY_VALUE_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY.getName(), Authentication.Property.VALUE.getName()); + public static final String TEST_ACTION_PROPERTY_NAME_1 = "samplePropertyName"; public static final String TEST_ACTION_PROPERTY_VALUE_1 = "samplePropertyValue"; + public static final String TEST_ACTION_PROPERTY_VALUE_1_UPDATED = "UpdatedSamplePropertyValue"; public static final String TEST_ACTION_PROPERTY_NAME_2 = "samplePropertyName2"; public static final String TEST_ACTION_PROPERTY_VALUE_2 = "samplePropertyValue2"; + public static final String TEST_ACTION_PROPERTY_VALUE_2_UPDATED = "UpdatedSamplePropertyValue2"; public static final String PASSWORD_SHARING_TYPE_PROPERTY_NAME = "passwordSharingType"; public static final String TEST_PASSWORD_SHARING_TYPE = "PLAIN_TEXT"; public static final String TEST_PASSWORD_SHARING_TYPE_UPDATED = "SHA256_HASHED"; public static final String CERTIFICATE_PROPERTY_NAME = "certificate"; public static final String TEST_CERTIFICATE = "sampleCertificate"; public static final String TEST_CERTIFICATE_UPDATED = "UpdatedSampleCertificate"; - - public static final String TEST_ACTION_NAME_UPDATED = "Updated Test Action Name"; - public static final String TEST_ACTION_DESCRIPTION_UPDATED = "Updated Test Action description"; - public static final String TEST_ACTION_URI_UPDATED = "https://sample.com"; - public static final String TEST_ACTION_PROPERTY_VALUE_1_UPDATED = "UpdatedSamplePropertyValue"; - public static final String TEST_ACTION_PROPERTY_VALUE_2_UPDATED = "UpdatedSamplePropertyValue2"; - - - public static final String SAMPLE_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; public static final String CERTIFICATE_ID = String.valueOf(UUID.randomUUID()); public static final String CERTIFICATE_NAME = "ACTIONS:" + PRE_UPDATE_PASSWORD_ACTION_ID; - public static final String CERTIFICATE = "sample-certificate"; - public static final String UPDATED_CERTIFICATE = "updated-sample-certificate"; public static Action buildMockAction(String name, String description, String uri, Authentication authentication) { @@ -99,20 +96,6 @@ public static String buildSecretName(String actionId, String authType, String au return TEST_SECRET_TYPE_ID + ":" + actionId + ":" + authType + ":" + authPropertyName; } - public static PreUpdatePasswordAction buildMockPreUpdatePasswordAction(String name, String description, String uri, - Authentication authentication, - PasswordFormat passwordSharingFormat, - String certificate) { - - return new PreUpdatePasswordAction.RequestBuilder() - .name(name) - .description(description) - .endpoint(buildMockEndpointConfig(uri, authentication)) - .passwordSharingFormat(passwordSharingFormat) - .certificate(new Certificate.Builder().certificateContent(certificate).build()) - .build(); - } - public static Authentication buildMockBasicAuthentication(String username, String password) { return new Authentication.BasicAuthBuilder(username, password).build(); @@ -128,12 +111,7 @@ public static Authentication buildMockAPIKeyAuthentication(String header, String return new Authentication.APIKeyAuthBuilder(header, value).build(); } - public static Authentication buildMockNoneAuthentication() { - - return new Authentication.NoneAuthBuilder().build(); - } - - private static EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { + public static EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { if (uri == null && authentication == null) { return null; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index cb1fe221091d..0342b55f0169 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -21,11 +21,15 @@ - - - - + + + + + + + + From 55fdd279598afe2cdd9847fc5504e357bbbb5f0a Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:23:40 +0530 Subject: [PATCH 17/34] Update scripts --- .../resources/dbscripts/db2.sql | 2 +- .../resources/dbscripts/h2.sql | 2 +- .../resources/dbscripts/mssql.sql | 2 +- .../resources/dbscripts/mysql-cluster.sql | 2 +- .../resources/dbscripts/mysql.sql | 2 +- .../resources/dbscripts/oracle.sql | 2 +- .../resources/dbscripts/oracle_rac.sql | 2 +- .../resources/dbscripts/postgresql.sql | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql index 0bb70a35e5db..065ca3719ae4 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql @@ -2267,7 +2267,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql index c56053cc5c86..a0b0af42fb59 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql @@ -1487,7 +1487,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- XACML -- CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql index 231e0ff73ddc..adafc091efae 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql @@ -1638,7 +1638,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql index 50ea8ebf6164..bd88f410cfbd 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql @@ -1679,7 +1679,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql index 5c331ab54f25..b2eb12391d97 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql @@ -1515,7 +1515,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql index 6636a2717308..7fa6d49d06e0 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql @@ -2324,7 +2324,7 @@ CREATE INDEX IDX_CON_FILE_RES_ID ON IDN_CONFIG_FILE (RESOURCE_ID) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql index 2d9c97707a7d..b7d2a6901480 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql @@ -2229,7 +2229,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql index a62b056d12f9..e79f5d721dfa 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql @@ -1762,7 +1762,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); From 95223b94ec5624d96150767e4510d1d8aea16596 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 26 Nov 2024 16:39:18 +0530 Subject: [PATCH 18/34] Refactor file locations --- .../management/dao/impl/ActionManagementDAOFacade.java | 3 +-- .../impl}/ActionPropertyResolverFactory.java | 4 ++-- .../management/internal/ActionMgtServiceComponent.java | 8 ++++---- .../action/management/{ => service}/ActionConverter.java | 2 +- .../management/{ => service}/ActionPropertyResolver.java | 2 +- .../{factory => service/impl}/ActionConverterFactory.java | 4 ++-- .../service/impl/ActionManagementServiceImpl.java | 7 +++---- .../management/dao/ActionManagementDAOFacadeTest.java | 4 ++-- .../ActionPropertyResolverFactoryTest.java | 5 +++-- .../{factory => service}/ActionConverterFactoryTest.java | 4 ++-- .../src/test/resources/testng.xml | 4 ++-- 11 files changed, 23 insertions(+), 24 deletions(-) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{factory => dao/impl}/ActionPropertyResolverFactory.java (93%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{ => service}/ActionConverter.java (97%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{ => service}/ActionPropertyResolver.java (97%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/{factory => service/impl}/ActionConverterFactory.java (92%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/{factory => dao}/ActionPropertyResolverFactoryTest.java (91%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/{factory => service}/ActionConverterFactoryTest.java (93%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index fe6a354e0411..2f3df54d130c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -22,16 +22,15 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; -import org.wso2.carbon.identity.action.management.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; -import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java similarity index 93% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java index acd35e7c0914..23d7b0151af3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java @@ -16,10 +16,10 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.factory; +package org.wso2.carbon.identity.action.management.dao.impl; -import org.wso2.carbon.identity.action.management.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import java.util.HashMap; import java.util.Map; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index 6aeb12247242..4f8888ceac5c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -28,11 +28,11 @@ 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.action.management.ActionConverter; -import org.wso2.carbon.identity.action.management.ActionPropertyResolver; -import org.wso2.carbon.identity.action.management.factory.ActionConverterFactory; -import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.service.ActionConverter; import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.impl.ActionConverterFactory; import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionConverter.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java similarity index 97% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionConverter.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java index 7083993cd839..fea88b8da1ed 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionConverter.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Action; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java similarity index 97% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java index 4f54a85892ee..fe6a000b9e2b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java similarity index 92% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java index d8517a2c9010..eb5dae5f2f7f 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java @@ -16,10 +16,10 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.factory; +package org.wso2.carbon.identity.action.management.service.impl; -import org.wso2.carbon.identity.action.management.ActionConverter; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.ActionConverter; import java.util.HashMap; import java.util.Map; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index d3f058523e11..cead66159e97 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -20,21 +20,20 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.action.management.ActionConverter; -import org.wso2.carbon.identity.action.management.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; +import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.factory.ActionConverterFactory; -import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionConverter; import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; import org.wso2.carbon.identity.action.management.util.ActionValidator; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index 1e457eb10f48..dc7d5950f690 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -26,17 +26,17 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.identity.action.management.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; -import org.wso2.carbon.identity.action.management.factory.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.certificate.management.model.Certificate; import org.wso2.carbon.identity.common.testng.WithCarbonHome; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionPropertyResolverFactoryTest.java similarity index 91% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionPropertyResolverFactoryTest.java index 0182f6c95392..5754267584dd 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionPropertyResolverFactoryTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionPropertyResolverFactoryTest.java @@ -16,15 +16,16 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.factory; +package org.wso2.carbon.identity.action.management.dao; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.identity.action.management.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import static org.mockito.Mockito.doReturn; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionConverterFactoryTest.java similarity index 93% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionConverterFactoryTest.java index 49487b032778..424926205532 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/factory/ActionConverterFactoryTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionConverterFactoryTest.java @@ -16,15 +16,15 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.factory; +package org.wso2.carbon.identity.action.management.service; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.identity.action.management.ActionConverter; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.impl.ActionConverterFactory; import static org.mockito.Mockito.doReturn; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index 0342b55f0169..219573bd6ba6 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -21,8 +21,8 @@ - - + + From b37fc70df0e27502a85d8b53e5f42f8a93ef4591 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 27 Nov 2024 15:39:08 +0530 Subject: [PATCH 19/34] Add ActionSecretProcessorTest --- .../util/ActionSecretProcessorTest.java | 222 ++++++++++++++++++ .../src/test/resources/testng.xml | 1 + 2 files changed, 223 insertions(+) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java new file mode 100644 index 000000000000..d9095d67a952 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.util; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.AuthProperty; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.secret.mgt.core.SecretManager; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import org.wso2.carbon.identity.secret.mgt.core.model.ResolvedSecret; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.util.Arrays; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_SECRET_TYPE_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildMockAPIKeyAuthentication; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildMockBasicAuthentication; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildMockBearerAuthentication; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildSecretName; + +/** + * Test class for Action secrets processor. + */ +public class ActionSecretProcessorTest { + + private SecretManager secretManager; + private SecretResolveManager secretResolveManager; + private ActionSecretProcessor actionSecretProcessor; + + @BeforeClass + public void setUpClass() { + + actionSecretProcessor = new ActionSecretProcessor(); + } + + @BeforeMethod + public void setUp() throws SecretManagementException { + + secretManager = mock(SecretManagerImpl.class); + secretResolveManager = mock(SecretResolveManager.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(secretResolveManager); + + SecretType secretType = mock(SecretType.class); + doReturn(TEST_SECRET_TYPE_ID).when(secretType).getId(); + doReturn(secretType).when(secretManager).getSecretType(any()); + + } + + @DataProvider + public Object[] provideAuthentication() { + + return new Object[]{ + buildMockBearerAuthentication(TEST_ACCESS_TOKEN), + buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD), + buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, TEST_API_KEY_VALUE) + }; + } + + @Test(dataProvider = "provideAuthentication") + public void testEncryptAssociatedSecrets(Authentication authentication) throws SecretManagementException { + + doReturn(false).when(secretManager).isSecretExist(any(), any()); + doReturn(null).when(secretManager).addSecret(any(), any()); + + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + Assert.assertEquals(encryptedProperties.size(), authentication.getProperties().size()); + for (AuthProperty authProperty : encryptedProperties) { + + Authentication.Property property = Arrays.stream(Authentication.Property.values()) + .filter(prop -> prop.getName().equals(authProperty.getName())) + .findFirst() + .orElse(null); + AuthProperty inputAuthProperty = authentication.getProperty(property); + + Assert.assertEquals(authProperty.getName(), authentication.getProperty(property).getName()); + Assert.assertEquals(authProperty.getIsConfidential(), inputAuthProperty.getIsConfidential()); + if (authProperty.getIsConfidential()) { + Assert.assertEquals(authProperty.getValue(), TestUtil.buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + authentication.getType().name(), inputAuthProperty.getName())); + } else { + Assert.assertEquals(authProperty.getValue(), inputAuthProperty.getValue()); + } + } + } + + @Test + public void testUpdateSecret() throws SecretManagementException { + + ResolvedSecret resolvedSecret = mock(ResolvedSecret.class); + doReturn(TEST_ACCESS_TOKEN).when(resolvedSecret).getResolvedSecretValue(); + doReturn(resolvedSecret).when(secretResolveManager).getResolvedSecret(any(), any()); + doReturn(true).when(secretManager).isSecretExist(any(), any()); + doReturn(null).when(secretManager).updateSecretValue(any(), any(), any()); + + Authentication authentication = buildMockBearerAuthentication(TEST_ACCESS_TOKEN_UPDATED); + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + Assert.assertEquals(encryptedProperties.size(), authentication.getProperties().size()); + Assert.assertEquals(encryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); + Assert.assertEquals(encryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); + Assert.assertEquals(encryptedProperties.get(0).getValue(), buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName())); + } + + @Test + public void testDecryptAssociatedSecrets() throws SecretManagementException { + + ResolvedSecret resolvedSecret = mock(ResolvedSecret.class); + doReturn(TEST_ACCESS_TOKEN).when(resolvedSecret).getResolvedSecretValue(); + doReturn(resolvedSecret).when(secretResolveManager).getResolvedSecret(any(), any()); + doReturn(true).when(secretManager).isSecretExist(any(), any()); + + Authentication authentication = buildMockBearerAuthentication(buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName())); + + List decryptedProperties = actionSecretProcessor.decryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + Assert.assertEquals(decryptedProperties.size(), authentication.getProperties().size()); + Assert.assertEquals(decryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); + Assert.assertEquals(decryptedProperties.get(0).getIsConfidential(), + authentication.getProperties().get(0).getIsConfidential()); + Assert.assertEquals(decryptedProperties.get(0).getValue(), TEST_ACCESS_TOKEN); + } + + @Test + public void testDecryptAssociatedSecretsForNonSecret() throws SecretManagementException { + + ResolvedSecret resolvedSecret = mock(ResolvedSecret.class); + doReturn(TEST_API_KEY_VALUE).when(resolvedSecret).getResolvedSecretValue(); + doReturn(resolvedSecret).when(secretResolveManager).getResolvedSecret(any(), any()); + doReturn(true).when(secretManager).isSecretExist(any(), any()); + + Authentication authentication = buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, + buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY.getName(), + Authentication.Property.VALUE.getName())); + + List decryptedProperties = actionSecretProcessor.decryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + for (AuthProperty authProperty : decryptedProperties) { + Authentication.Property property = Arrays.stream(Authentication.Property.values()) + .filter(prop -> prop.getName().equals(authProperty.getName())) + .findFirst() + .orElse(null); + AuthProperty inputAuthProperty = authentication.getProperty(property); + + Assert.assertEquals(authProperty.getName(), authentication.getProperty(property).getName()); + Assert.assertEquals(authProperty.getIsConfidential(), inputAuthProperty.getIsConfidential()); + if (authProperty.getIsConfidential()) { + Assert.assertEquals(authProperty.getValue(), TEST_API_KEY_VALUE); + } else { + Assert.assertEquals(authProperty.getValue(), TEST_API_KEY_HEADER); + } + } + } + + @Test(expectedExceptions = SecretManagementException.class) + public void testDecryptAssociatedSecretsForNonExistingSecret() throws SecretManagementException { + + doReturn(false).when(secretManager).isSecretExist(any(), any()); + Authentication authentication = buildMockBearerAuthentication(buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName())); + + actionSecretProcessor.decryptAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + } + + @Test + public void testDeleteAssociatedSecrets() throws SecretManagementException { + + doReturn(true).when(secretManager).isSecretExist(any(), any()); + doNothing().when(secretManager).deleteSecret(any(), any()); + + Authentication authentication = buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, + buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY.getName(), + Authentication.Property.VALUE.getName())); + + actionSecretProcessor.deleteAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + verify(secretManager, times(1)).deleteSecret(any(), any()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index 219573bd6ba6..128d48e9d440 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -24,6 +24,7 @@ + From 0288ba0d31cb9a9c5fd518566e94add9f844ae44 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 27 Nov 2024 15:40:38 +0530 Subject: [PATCH 20/34] Modify other tests --- .../pom.xml | 7 +- .../constant/ActionMgtConstants.java | 3 + .../dao/impl/ActionManagementDAOImpl.java | 3 - .../impl/ActionPropertyResolverFactory.java | 8 +- .../action/management/model/Action.java | 6 - .../management/model/Authentication.java | 2 +- .../service/impl/ActionConverterFactory.java | 8 +- .../impl/ActionManagementServiceImpl.java | 3 + .../util/ActionSecretProcessor.java | 8 +- .../dao/ActionManagementDAOFacadeTest.java | 8 +- .../dao/ActionManagementDAOImplTest.java | 10 +- .../ActionManagementServiceImplTest.java | 247 ++++++++---------- ...acheBackedActionManagementServiceTest.java | 19 +- .../action/management/util/TestUtil.java | 1 + 14 files changed, 153 insertions(+), 180 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index 15022b8ea587..82d9e8703c4d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -180,16 +180,11 @@ LINE COVEREDRATIO - - 0.77 + 0.80 COMPLEXITY COVEREDRATIO - 0.60 diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index 2dc669ebfbdf..9da7b6b3f5c3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -35,4 +35,7 @@ public class ActionMgtConstants { public static final String ACCESS_TOKEN_FIELD = "Access token"; public static final String API_KEY_HEADER_FIELD = "API key header name"; public static final String API_KEY_VALUE_FIELD = "API key value"; + + private ActionMgtConstants() { + } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 016612cf11cb..f7d387737271 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -53,9 +53,6 @@ */ public class ActionManagementDAOImpl implements ActionManagementDAO { - public ActionManagementDAOImpl() { - } - @Override public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java index 23d7b0151af3..b100659ffc4b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java @@ -21,7 +21,7 @@ import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; -import java.util.HashMap; +import java.util.EnumMap; import java.util.Map; /** @@ -31,7 +31,11 @@ */ public class ActionPropertyResolverFactory { - private static final Map actionPropertyResolvers = new HashMap<>(); + private static final Map actionPropertyResolvers = + new EnumMap<>(Action.ActionTypes.class); + + private ActionPropertyResolverFactory() { + } public static ActionPropertyResolver getActionPropertyResolver(Action.ActionTypes actionType) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java index 9cc7dfe40052..dc1f3030bf47 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java @@ -19,7 +19,6 @@ package org.wso2.carbon.identity.action.management.model; import java.util.Arrays; -import java.util.Map; /** * Action. @@ -183,11 +182,6 @@ public EndpointConfig getEndpoint() { return endpointConfig; } - public Map getProperties() { - - return null; - } - /** * ActionResponseBuilder. */ diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java index a987e450cd7e..29839a3d7372 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java @@ -140,7 +140,7 @@ public List getPropertiesWithDecryptedValues(String actionId) thro try { return CollectionUtils.isEmpty(properties) ? properties : - secretProcessor.decryptAssociatedSecrets(properties, type.getName(), actionId); + secretProcessor.decryptAssociatedSecrets(this, actionId); } catch (SecretManagementException e) { throw ActionManagementUtil.handleServerException( ErrorMessage.ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES, e); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java index eb5dae5f2f7f..43388a915d6c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java @@ -21,7 +21,7 @@ import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.service.ActionConverter; -import java.util.HashMap; +import java.util.EnumMap; import java.util.Map; /** @@ -31,7 +31,11 @@ */ public class ActionConverterFactory { - private static final Map actionConverters = new HashMap<>(); + private static final Map actionConverters = + new EnumMap<>(Action.ActionTypes.class); + + private ActionConverterFactory() { + } public static ActionConverter getActionConverter(Action.ActionTypes actionType) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index cead66159e97..629d364932d8 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -407,6 +407,9 @@ private void doEndpointAuthenticationValidation(Authentication authentication) t ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.API_KEY_VALUE_FIELD, authentication.getProperty(Authentication.Property.VALUE).getValue()); break; + case NONE: + default: + break; } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java index ca0b44d26b4d..f518b720b765 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java @@ -54,15 +54,15 @@ public List encryptAssociatedSecrets(Authentication authentication return encryptedAuthProperties; } - public List decryptAssociatedSecrets(List authProperties, String authType, - String actionId) throws SecretManagementException { + public List decryptAssociatedSecrets(Authentication authentication, String actionId) + throws SecretManagementException { List decryptedAuthProperties = new ArrayList<>(); - for (AuthProperty authProperty : authProperties) { + for (AuthProperty authProperty : authentication.getProperties()) { if (!authProperty.getIsConfidential()) { decryptedAuthProperties.add(authProperty); } else { - decryptedAuthProperties.add(decryptProperty(authProperty, authType, actionId)); + decryptedAuthProperties.add(decryptProperty(authProperty, authentication.getType().name(), actionId)); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index dc7d5950f690..94a49a5c091f 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -308,10 +308,10 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty @Test(priority = 4) public void testDeactivateAction() throws ActionMgtException { - Assert.assertEquals(Action.Status.ACTIVE, createdActionDTO.getStatus()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); ActionDTO deactivatedActionDTO = daoFacade.deactivateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.INACTIVE, deactivatedActionDTO.getStatus()); + Assert.assertEquals(deactivatedActionDTO.getStatus(), Action.Status.INACTIVE); } @Test(priority = 5) @@ -319,7 +319,7 @@ public void testActivateAction() throws ActionMgtException { ActionDTO activatedActionDTO = daoFacade.activateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.ACTIVE, activatedActionDTO.getStatus()); + Assert.assertEquals(activatedActionDTO.getStatus(), Action.Status.ACTIVE); } @Test(priority = 6) @@ -327,7 +327,7 @@ public void testGetActionsCountPerType() throws ActionMgtException { Map actionMap = daoFacade.getActionsCountPerType(TENANT_ID); Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); - Assert.assertEquals(1, actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue()); + Assert.assertEquals(actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue(), 1); } @Test(priority = 7) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index ca76a131054b..5f57f1087f73 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -506,10 +506,10 @@ public void testUpdateActionProperties() throws ActionMgtException { @Test(priority = 14) public void testDeactivateAction() throws ActionMgtException { - Assert.assertEquals(Action.Status.ACTIVE, createdActionDTO.getStatus()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); ActionDTO deactivatedActionDTO = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdActionDTO.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.INACTIVE, deactivatedActionDTO.getStatus()); + Assert.assertEquals(deactivatedActionDTO.getStatus(), Action.Status.INACTIVE); } @Test(priority = 15) @@ -517,7 +517,7 @@ public void testActivateAction() throws ActionMgtException { ActionDTO activatedActionDTO = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdActionDTO.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.ACTIVE, activatedActionDTO.getStatus()); + Assert.assertEquals(activatedActionDTO.getStatus(), Action.Status.ACTIVE); } @Test(priority = 16) @@ -539,9 +539,9 @@ public void testGetActionsCountPerType() throws ActionMgtException { Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); Assert.assertTrue(actionMap.containsKey(PRE_ISSUE_ACCESS_TOKEN_TYPE)); - Assert.assertEquals(1, actionMap.get(PRE_ISSUE_ACCESS_TOKEN_TYPE).intValue()); + Assert.assertEquals(actionMap.get(PRE_ISSUE_ACCESS_TOKEN_TYPE).intValue(), 1); Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); - Assert.assertEquals(1, actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue()); + Assert.assertEquals(actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue(), 1); daoImpl.deleteAction(createdPreUpdatePasswordActionDTO, TENANT_ID); daoImpl.deleteAction(createdActionDTO, TENANT_ID); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java index 16e6a5152413..edf18102d2a1 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java @@ -75,8 +75,7 @@ public class ActionManagementServiceImplTest { private ActionManagementService actionManagementService; - private Action preIssueAccessTokenAction; - private Map secretProperties; + private Action sampleAction; @BeforeClass public void setUpClass() { @@ -102,28 +101,24 @@ public void testAddAction() throws ActionMgtException, SecretManagementException TEST_ACTION_DESCRIPTION, TEST_ACTION_URI, TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)); - preIssueAccessTokenAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, - TENANT_DOMAIN); - Assert.assertNotNull(preIssueAccessTokenAction.getId()); - Assert.assertEquals(creatingAction.getName(), preIssueAccessTokenAction.getName()); - Assert.assertEquals(creatingAction.getDescription(), preIssueAccessTokenAction.getDescription()); - Assert.assertEquals(Action.Status.ACTIVE, preIssueAccessTokenAction.getStatus()); - Assert.assertEquals(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), - preIssueAccessTokenAction.getType().getActionType()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), preIssueAccessTokenAction.getEndpoint().getUri()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - preIssueAccessTokenAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getProperties().size(), - preIssueAccessTokenAction.getEndpoint().getAuthentication().getProperties().size()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getProperties().size(), - preIssueAccessTokenAction.getEndpoint().getAuthentication().getPropertiesWithSecretReferences( - preIssueAccessTokenAction.getId()).size()); - secretProperties = mapActionAuthPropertiesWithSecrets(preIssueAccessTokenAction); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication() - .getProperty(Authentication.Property.USERNAME).getValue(), + sampleAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); + + Assert.assertNotNull(sampleAction.getId()); + Assert.assertEquals(sampleAction.getName(), creatingAction.getName()); + Assert.assertEquals(sampleAction.getDescription(), creatingAction.getDescription()); + Assert.assertEquals(sampleAction.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(sampleAction.getType(), Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); + Assert.assertEquals(sampleAction.getEndpoint().getUri(), creatingAction.getEndpoint().getUri()); + + Authentication sampleActionAuth = sampleAction.getEndpoint().getAuthentication(); + Authentication creatingActionAuth = creatingAction.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(creatingActionAuth, sampleAction.getId()); + + Assert.assertEquals(sampleActionAuth.getType(), creatingActionAuth.getType()); + Assert.assertEquals(sampleActionAuth.getProperties().size(), creatingActionAuth.getProperties().size()); + Assert.assertEquals(sampleActionAuth.getProperty(Authentication.Property.USERNAME).getValue(), secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication() - .getProperty(Authentication.Property.PASSWORD).getValue(), + Assert.assertEquals(sampleActionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), secretProperties.get(Authentication.Property.PASSWORD.getName())); } @@ -160,7 +155,7 @@ public void testAddMaximumActionsPerType() throws ActionMgtException { TEST_ACTION_DESCRIPTION, TEST_ACTION_URI, TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)); - preIssueAccessTokenAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, + sampleAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); } @@ -170,73 +165,47 @@ public void testGetActionsByActionType() throws ActionMgtException, SecretManage List actions = actionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); Assert.assertEquals(1, actions.size()); - for (Action result: actions) { - Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); - Assert.assertEquals(preIssueAccessTokenAction.getName(), result.getName()); - Assert.assertEquals(preIssueAccessTokenAction.getDescription(), result.getDescription()); - Assert.assertEquals(preIssueAccessTokenAction.getType().getActionType(), result.getType().getActionType()); - Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); - } + Action result = actions.get(0); + Assert.assertEquals(result.getId(), sampleAction.getId()); + Assert.assertEquals(result.getName(), sampleAction.getName()); + Assert.assertEquals(result.getDescription(), sampleAction.getDescription()); + Assert.assertEquals(result.getType().getActionType(), sampleAction.getType().getActionType()); + Assert.assertEquals(result.getStatus(), sampleAction.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), sampleAction.getEndpoint().getUri()); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Authentication sampleActionAuth = sampleAction.getEndpoint().getAuthentication(); + + Assert.assertEquals(resultActionAuth.getType(), sampleActionAuth.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + sampleActionAuth.getProperty(Authentication.Property.USERNAME).getValue()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + sampleActionAuth.getProperty(Authentication.Property.PASSWORD).getValue()); } @Test(priority = 6) public void testGetActionByActionId() throws ActionMgtException, SecretManagementException { - Action result = actionManagementService.getActionByActionId(preIssueAccessTokenAction.getType().getPathParam(), - preIssueAccessTokenAction.getId(), TENANT_DOMAIN); - Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); - Assert.assertEquals(preIssueAccessTokenAction.getName(), result.getName()); - Assert.assertEquals(preIssueAccessTokenAction.getDescription(), result.getDescription()); - Assert.assertEquals(preIssueAccessTokenAction.getType(), result.getType()); - Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); + Action result = actionManagementService.getActionByActionId(sampleAction.getType().getPathParam(), + sampleAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(result.getId(), sampleAction.getId()); + Assert.assertEquals(result.getName(), sampleAction.getName()); + Assert.assertEquals(result.getDescription(), sampleAction.getDescription()); + Assert.assertEquals(result.getType(), sampleAction.getType()); + Assert.assertEquals(result.getStatus(), sampleAction.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), sampleAction.getEndpoint().getUri()); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Authentication sampleActionAuth = sampleAction.getEndpoint().getAuthentication(); + + Assert.assertEquals(resultActionAuth.getType(), sampleActionAuth.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + sampleActionAuth.getProperty(Authentication.Property.USERNAME).getValue()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + sampleActionAuth.getProperty(Authentication.Property.PASSWORD).getValue()); } @Test(priority = 7) - public void testGetActionsByActionTypeFromCache() throws ActionMgtException, SecretManagementException { - - // Verify that the action is retrieved from the cache based on action type. - List actions = actionManagementService.getActionsByActionType( - PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); - Assert.assertEquals(1, actions.size()); - Action result = actions.get(0); - Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); - Assert.assertEquals(preIssueAccessTokenAction.getName(), result.getName()); - Assert.assertEquals(preIssueAccessTokenAction.getDescription(), result.getDescription()); - Assert.assertEquals(preIssueAccessTokenAction.getType(), result.getType()); - Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(preIssueAccessTokenAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); - } - - @Test(priority = 8) public void testUpdateAction() throws ActionMgtException, SecretManagementException { Action updatingAction = TestUtil.buildMockAction( @@ -244,45 +213,46 @@ public void testUpdateAction() throws ActionMgtException, SecretManagementExcept TEST_ACTION_DESCRIPTION_UPDATED, TEST_ACTION_URI, TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, TEST_API_KEY_VALUE)); - Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, - preIssueAccessTokenAction.getId(), updatingAction, TENANT_DOMAIN); - Assert.assertEquals(preIssueAccessTokenAction.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(preIssueAccessTokenAction.getType(), result.getType()); - Assert.assertEquals(preIssueAccessTokenAction.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), + Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, sampleAction.getId(), + updatingAction, TENANT_DOMAIN); + + Assert.assertEquals(result.getId(), sampleAction.getId()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getType(), sampleAction.getType()); + Assert.assertEquals(result.getStatus(), sampleAction.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Authentication updatingActionAuth = updatingAction.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(updatingActionAuth, sampleAction.getId()); + + Assert.assertEquals(resultActionAuth.getType(), updatingActionAuth.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.HEADER).getValue(), + secretProperties.get(Authentication.Property.HEADER.getName())); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.VALUE).getValue(), secretProperties.get(Authentication.Property.VALUE.getName())); - preIssueAccessTokenAction = result; + sampleAction = result; } - @Test(priority = 9) + @Test(priority = 8) public void testDeactivateAction() throws ActionMgtException { - Assert.assertEquals(Action.Status.ACTIVE, preIssueAccessTokenAction.getStatus()); - Action deactivatedAction = actionManagementService.deactivateAction( - PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), TENANT_DOMAIN); - Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); + Assert.assertEquals(sampleAction.getStatus(), Action.Status.ACTIVE); + Action deactivatedAction = actionManagementService.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(deactivatedAction.getStatus(), Action.Status.INACTIVE); } - @Test(priority = 10) + @Test(priority = 9) public void testActivateAction() throws ActionMgtException { - Action result = actionManagementService.activateAction( - PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), TENANT_DOMAIN); - Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); + Action activatedAction = actionManagementService.activateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(activatedAction.getStatus(), Action.Status.ACTIVE); } - @Test(priority = 11) + @Test(priority = 10) public void testGetActionsCountPerType() throws ActionMgtException { Map actionMap = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); @@ -296,52 +266,55 @@ public void testGetActionsCountPerType() throws ActionMgtException { } } - @Test(priority = 12) + @Test(priority = 11) public void testUpdateEndpointConfigWithSameAuthenticationType() throws ActionMgtException, SecretManagementException { - Authentication authentication = TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER_UPDATED, + Authentication updatingAuthentication = TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER_UPDATED, TEST_API_KEY_VALUE_UPDATED); - Action result = actionManagementService.updateActionEndpointAuthentication( - PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), authentication, TENANT_DOMAIN); - Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(authentication.getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), + Action result = actionManagementService.updateActionEndpointAuthentication(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), updatingAuthentication, TENANT_DOMAIN); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(updatingAuthentication, sampleAction.getId()); + + Assert.assertEquals(resultActionAuth.getType(), updatingAuthentication.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.HEADER).getValue(), + secretProperties.get(Authentication.Property.HEADER.getName())); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.VALUE).getValue(), secretProperties.get(Authentication.Property.VALUE.getName())); } - @Test(priority = 13) + @Test(priority = 12) public void testUpdateEndpointConfigWithDifferentAuthenticationType() throws ActionMgtException, SecretManagementException { - Authentication authentication = TestUtil.buildMockBearerAuthentication(TEST_ACCESS_TOKEN); - Action result = actionManagementService.updateActionEndpointAuthentication( - PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), authentication, TENANT_DOMAIN); - Assert.assertEquals(Authentication.Type.BEARER, result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + Authentication updatingAuthentication = TestUtil.buildMockBearerAuthentication(TEST_ACCESS_TOKEN); + Action result = actionManagementService.updateActionEndpointAuthentication(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), updatingAuthentication, TENANT_DOMAIN); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(updatingAuthentication, sampleAction.getId()); + + Assert.assertEquals(resultActionAuth.getType(), updatingAuthentication.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), secretProperties.get(Authentication.Property.ACCESS_TOKEN.getName())); } - @Test(priority = 14) + @Test(priority = 13) public void testDeleteAction() throws ActionMgtException { - actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, preIssueAccessTokenAction.getId(), - TENANT_DOMAIN); - Assert.assertNull(actionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, - preIssueAccessTokenAction.getId(), TENANT_DOMAIN)); + actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, sampleAction.getId(), TENANT_DOMAIN); + Assert.assertNull(actionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, sampleAction.getId(), + TENANT_DOMAIN)); Map actions = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); Assert.assertNull(actions.get(PRE_ISSUE_ACCESS_TOKEN_PATH)); } - private Map mapActionAuthPropertiesWithSecrets(Action action) throws SecretManagementException { + private Map resolveAuthPropertiesMap(Authentication authentication, String actionId) + throws SecretManagementException { - return action.getEndpoint().getAuthentication() - .getPropertiesWithSecretReferences(action.getId()) + return authentication.getPropertiesWithSecretReferences(actionId) .stream() .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java index 0b21e5becb30..59d8cf7d7061 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java @@ -278,16 +278,15 @@ private void assertAction(Action action) { Assert.assertEquals(action.getType(), mockedAction.getType()); Assert.assertEquals(action.getStatus(), mockedAction.getStatus()); Assert.assertEquals(action.getEndpoint().getUri(), mockedAction.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - mockedAction.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME) - .getValue(), - mockedAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME) - .getValue()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD) - .getValue(), - mockedAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD) - .getValue()); + + Authentication actionAuth = action.getEndpoint().getAuthentication(); + Authentication mockedActionAuth = mockedAction.getEndpoint().getAuthentication(); + + Assert.assertEquals(actionAuth.getType(), mockedActionAuth.getType()); + Assert.assertEquals(actionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + mockedActionAuth.getProperty(Authentication.Property.USERNAME).getValue()); + Assert.assertEquals(actionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + mockedActionAuth.getProperty(Authentication.Property.PASSWORD).getValue()); } private void setFinalField(Object target, String fieldName, Object value) throws Exception { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index 13aa0c49cf84..00779bbb0623 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -57,6 +57,7 @@ public class TestUtil { public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.BASIC.getName(), Authentication.Property.PASSWORD.getName()); public static final String TEST_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; + public static final String TEST_ACCESS_TOKEN_UPDATED = "fe326c2a-e83a-41fe-bc6a-ee79e1feabba"; public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName()); public static final String TEST_API_KEY_HEADER = "sampleHeader"; From fa32db09d494b319f7341338f0850d2ec4a6425e Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 27 Nov 2024 16:19:07 +0530 Subject: [PATCH 21/34] Fix exposing packages --- .../impl/ActionExecutorServiceImplTest.java | 2 +- .../pom.xml | 17 ++++++++--------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java index 4dc8a5033bca..bbfcd583fe32 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java @@ -60,11 +60,11 @@ import org.wso2.carbon.identity.action.execution.util.ActionExecutionDiagnosticLogger; import org.wso2.carbon.identity.action.execution.util.ActionExecutorConfig; import org.wso2.carbon.identity.action.execution.util.RequestFilter; -import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import java.lang.reflect.Field; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index 82d9e8703c4d..331984bf7235 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -89,19 +89,18 @@ ${project.artifactId} - org.wso2.carbon.identity.action.management.internal, org.wso2.carbon.identity.action.management.cache, - org.wso2.carbon.identity.action.management.dao, - org.wso2.carbon.identity.action.management.dao.impl, + org.wso2.carbon.identity.action.management.constant, + org.wso2.carbon.identity.action.management.dao.*, + org.wso2.carbon.identity.action.management.internal, + org.wso2.carbon.identity.action.management.service.impl, org.wso2.carbon.identity.action.management.util - !org.wso2.carbon.identity.action.management.internal, - !org.wso2.carbon.identity.action.management.cache, - !org.wso2.carbon.identity.action.management.dao, - !org.wso2.carbon.identity.action.management.dao.impl, - !org.wso2.carbon.identity.action.management.util, - org.wso2.carbon.identity.action.management.*; version="${carbon.identity.package.export.version}" + org.wso2.carbon.identity.action.management.constant.error, + org.wso2.carbon.identity.action.management.exception, + org.wso2.carbon.identity.action.management.model, + org.wso2.carbon.identity.action.management.service; version="${carbon.identity.package.export.version}" org.apache.commons.lang; version="${commons-lang.wso2.osgi.version.range}", From 931588f41d06bd38d14dd21ecff6b83e13fcc841 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 27 Nov 2024 21:03:03 +0530 Subject: [PATCH 22/34] Improve tests for failure cases --- .../constant/error/ErrorMessage.java | 10 +- .../dao/impl/ActionManagementDAOFacade.java | 31 ++- .../dao/impl/ActionManagementDAOImpl.java | 4 +- .../exception/ActionMgtClientException.java | 5 - .../exception/ActionMgtException.java | 16 -- .../exception/ActionMgtServerException.java | 21 +- ...ActionPropertyResolverClientException.java | 32 ++++ .../ActionPropertyResolverException.java | 2 +- ...ActionPropertyResolverServerException.java | 36 ++++ .../management/model/Authentication.java | 4 +- .../model/PreUpdatePasswordAction.java | 181 ------------------ .../service/ActionPropertyResolver.java | 7 - .../impl/ActionManagementServiceImpl.java | 64 +++---- ... => ActionManagementExceptionHandler.java} | 14 +- .../util/ActionSecretProcessor.java | 3 - .../management/util/ActionValidator.java | 21 +- .../dao/ActionManagementDAOFacadeTest.java | 158 +++++++++++---- .../ActionManagementServiceImplTest.java | 18 +- ...acheBackedActionManagementServiceTest.java | 4 +- .../util/ActionSecretProcessorTest.java | 20 +- .../action/management/util/TestUtil.java | 13 +- 21 files changed, 285 insertions(+), 379 deletions(-) create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java delete mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/{ActionManagementUtil.java => ActionManagementExceptionHandler.java} (83%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java index 11e370f1d8d7..f13e723d0110 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java @@ -28,13 +28,11 @@ public enum ErrorMessage { "Invalid action type used for path parameter."), ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED("60002", "Unable to create an Action.", "Maximum number of actions per action type is reached."), - ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID("60003", - "Unable to perform the operation.", + ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID("60003", "Unable to perform the operation.", "No Action is configured on the given Action Type and Id."), - ERROR_EMPTY_ACTION_REQUEST_FIELD("60004", "Invalid request.", - "%s is empty."), - ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", - "%s is invalid."), + ERROR_EMPTY_ACTION_REQUEST_FIELD("60004", "Invalid request.", "%s is empty."), + ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", "%s is invalid."), + ERROR_INVALID_ACTION_PROPERTIES("60006", "Provided Action Properties are invalid.", "%s"), // Server errors. ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index 2f3df54d130c..64257b20cd33 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -25,13 +25,15 @@ import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverClientException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; @@ -73,10 +75,11 @@ public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtExc return null; }); } catch (TransactionException e) { + handleActionPropertyResolverClientException(e.getCause()); LOG.debug("Error while creating the Action of Action Type: " + actionDTO.getType().getDisplayName() + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + ". Rolling back created action information, authentication secrets and action properties."); - throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_ADDING_ACTION, e); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_ADDING_ACTION, e); } } @@ -89,7 +92,7 @@ public List getActionsByActionType(String actionType, Integer tenantI return actionDTOS; } catch (ActionMgtException | ActionPropertyResolverException e) { - throw ActionManagementUtil.handleServerException( + throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); } } @@ -107,7 +110,8 @@ public ActionDTO getActionByActionId(String actionType, String actionId, Integer return actionDTO; } catch (ActionMgtException | ActionPropertyResolverException e) { - throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); } } @@ -127,11 +131,12 @@ public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDT return null; }); } catch (TransactionException e) { + handleActionPropertyResolverClientException(e.getCause()); LOG.debug("Error while updating the Action of Action Type: " + updatingActionDTO.getType().getDisplayName() + " and Action ID: " + updatingActionDTO.getId() + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + ". Rolling back updated action information"); - throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_UPDATING_ACTION, e); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_UPDATING_ACTION, e); } } @@ -154,7 +159,7 @@ public void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws A deletingActionDTO.getType().getDisplayName() + " and Action ID: " + deletingActionDTO.getId() + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + ". Rolling back deleted action information"); - throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_DELETING_ACTION, e); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_DELETING_ACTION, e); } } @@ -164,7 +169,7 @@ public ActionDTO activateAction(String actionType, String actionId, Integer tena try { return actionManagementDAO.activateAction(actionType, actionId, tenantId); } catch (ActionMgtException e) { - throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_ACTIVATING_ACTION, e); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_ACTIVATING_ACTION, e); } } @@ -174,7 +179,8 @@ public ActionDTO deactivateAction(String actionType, String actionId, Integer te try { return actionManagementDAO.deactivateAction(actionType, actionId, tenantId); } catch (ActionMgtException e) { - throw ActionManagementUtil.handleServerException(ErrorMessage.ERROR_WHILE_DEACTIVATING_ACTION, e); + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_DEACTIVATING_ACTION, e); } } @@ -295,4 +301,13 @@ private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) IdentityTenantUtil.getTenantDomain(tenantId)); } } + + private static void handleActionPropertyResolverClientException(Throwable throwable) + throws ActionMgtClientException { + + if (throwable instanceof ActionPropertyResolverClientException) { + throw ActionManagementExceptionHandler.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES, + throwable.getMessage()); + } + } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index f7d387737271..6c1a72fa51e0 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -32,7 +32,7 @@ import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import java.sql.Connection; @@ -171,7 +171,7 @@ public Map getActionsCountPerType(Integer tenantId) throws Acti return actionTypesCountMap; } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( + throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtClientException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtClientException.java index bd085eb43999..551c2ce2e59a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtClientException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtClientException.java @@ -27,9 +27,4 @@ public ActionMgtClientException(String message, String description, String error super(message, description, errorCode); } - - public ActionMgtClientException(String message, String description, String errorCode, Throwable cause) { - - super(message, description, errorCode, cause); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java index 6d987f39d273..dc7ebd6886da 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java @@ -36,12 +36,6 @@ public ActionMgtException(String message, Throwable cause) { super(message, cause); } - public ActionMgtException(String message, String errorCode, Throwable cause) { - - super(message, cause); - this.errorCode = errorCode; - } - public ActionMgtException(String message, String description, String errorCode) { super(message); @@ -61,18 +55,8 @@ public String getErrorCode() { return this.errorCode; } - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - public String getDescription() { return this.description; } - - public void setDescription(String description) { - - this.description = description; - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java index a1b9a95309ca..95a83586ad8a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java @@ -23,29 +23,18 @@ */ public class ActionMgtServerException extends ActionMgtException { - public ActionMgtServerException(String message, Throwable cause) { - - super(message, cause); - } - - public ActionMgtServerException(String message, String description, String errorCode) { + public ActionMgtServerException(String message) { - super(message, description, errorCode); + super(message); } - public ActionMgtServerException(String message, String errorCode, Throwable cause) { + public ActionMgtServerException(String message, Throwable cause) { - super(message, errorCode, cause); + super(message, cause); } - public ActionMgtServerException(String message, String description, String errorCode, - Throwable cause) { + public ActionMgtServerException(String message, String description, String errorCode, Throwable cause) { super(message, description, errorCode, cause); } - - public ActionMgtServerException(String message) { - - super(message); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java new file mode 100644 index 000000000000..22601fba1001 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.exception; + +/** + * Client Exception class for Action Property Resolver. + * This exception is thrown when there is any validation failures or client error in performing action type + * specific operations. + */ +public class ActionPropertyResolverClientException extends ActionPropertyResolverException { + + public ActionPropertyResolverClientException(String message) { + + super(message); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java index f8801dcc5efb..783640ed1329 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java @@ -19,7 +19,7 @@ package org.wso2.carbon.identity.action.management.exception; /** - * Exception class for Action Resolver. + * Exception class for Action Property Resolver. * This exception is thrown when there is an issue in performing action type specific operations. */ public class ActionPropertyResolverException extends Exception { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java new file mode 100644 index 000000000000..1b064c1e10f6 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.exception; + +/** + * Server Exception class for Action Property Resolver. + * This exception is thrown when there is an issue in performing action type specific operations in the system. + */ +public class ActionPropertyResolverServerException extends ActionPropertyResolverException { + + public ActionPropertyResolverServerException(String message) { + + super(message); + } + + public ActionPropertyResolverServerException(String message, Throwable cause) { + + super(message, cause); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java index 29839a3d7372..98f34f31adcd 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java @@ -22,7 +22,7 @@ import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; @@ -142,7 +142,7 @@ public List getPropertiesWithDecryptedValues(String actionId) thro return CollectionUtils.isEmpty(properties) ? properties : secretProcessor.decryptAssociatedSecrets(this, actionId); } catch (SecretManagementException e) { - throw ActionManagementUtil.handleServerException( + throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES, e); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java deleted file mode 100644 index f1731179603b..000000000000 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/PreUpdatePasswordAction.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.action.management.model; - -import org.wso2.carbon.identity.certificate.management.model.Certificate; - -/** - * PreUpdatePasswordAction. - */ -public class PreUpdatePasswordAction extends Action { - - /** - * Password Format Enum. - * Defines the category of the password sharing types. - */ - public enum PasswordFormat { - - PLAIN_TEXT, - SHA256_HASHED; - } - - private final PasswordFormat passwordSharingFormat; - private final Certificate certificate; - - public PreUpdatePasswordAction(ResponseBuilder responseBuilder) { - - super(responseBuilder); - this.passwordSharingFormat = responseBuilder.passwordSharingFormat; - this.certificate = responseBuilder.certificate; - } - - public PreUpdatePasswordAction(RequestBuilder requestBuilder) { - - super(requestBuilder); - this.passwordSharingFormat = requestBuilder.passwordSharingFormat; - this.certificate = requestBuilder.certificate; - } - - public PasswordFormat getPasswordSharingFormat() { - - return passwordSharingFormat; - } - - public Certificate getCertificate() { - - return certificate; - } - - /** - * Response Builder for PreUpdatePasswordAction. - */ - public static class ResponseBuilder extends ActionResponseBuilder { - - private PasswordFormat passwordSharingFormat; - private Certificate certificate; - - public ResponseBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat) { - - this.passwordSharingFormat = passwordSharingFormat; - return this; - } - - public ResponseBuilder certificate(Certificate certificate) { - - this.certificate = certificate; - return this; - } - - @Override - public ResponseBuilder id(String id) { - - super.id(id); - return this; - } - - @Override - public ResponseBuilder type(ActionTypes type) { - - super.type(type); - return this; - } - - @Override - public ResponseBuilder name(String name) { - - super.name(name); - return this; - } - - @Override - public ResponseBuilder description(String description) { - - super.description(description); - return this; - } - - @Override - public ResponseBuilder status(Status status) { - - super.status(status); - return this; - } - - @Override - public ResponseBuilder endpoint(EndpointConfig endpoint) { - - super.endpoint(endpoint); - return this; - } - - @Override - public PreUpdatePasswordAction build() { - - return new PreUpdatePasswordAction(this); - } - } - - /** - * Request Builder for PreUpdatePasswordAction. - */ - public static class RequestBuilder extends ActionRequestBuilder { - - private PasswordFormat passwordSharingFormat; - private Certificate certificate; - - public RequestBuilder passwordSharingFormat(PasswordFormat passwordSharingFormat) { - - this.passwordSharingFormat = passwordSharingFormat; - return this; - } - - public RequestBuilder certificate(Certificate certificate) { - - this.certificate = certificate; - return this; - } - - @Override - public RequestBuilder name(String name) { - - super.name(name); - return this; - } - - @Override - public RequestBuilder description(String description) { - - super.description(description); - return this; - } - - @Override - public RequestBuilder endpoint(EndpointConfig endpoint) { - - super.endpoint(endpoint); - return this; - } - - @Override - public PreUpdatePasswordAction build() { - - return new PreUpdatePasswordAction(this); - } - } -} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java index fe6a000b9e2b..d7742b7ed8e0 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java @@ -19,7 +19,6 @@ package org.wso2.carbon.identity.action.management.service; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; -import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; import org.wso2.carbon.identity.action.management.model.Action; @@ -55,10 +54,4 @@ default Map updateProperties(ActionDTO updatingActionDTO, Action default void deleteProperties(ActionDTO deletingActionDTO, String tenantDomain) throws ActionPropertyResolverException { } - - default void doPreAddActionPropertiesValidations(ActionDTO actionDTO) throws ActionMgtClientException { - } - - default void doPreUpdateActionPropertiesValidations(ActionDTO updatingActionDTO) throws ActionMgtClientException { - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index 629d364932d8..f204efc3434b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -24,7 +24,6 @@ import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; -import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; @@ -33,9 +32,8 @@ import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.service.ActionConverter; import org.wso2.carbon.identity.action.management.service.ActionManagementService; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionValidator; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; @@ -78,11 +76,11 @@ public Action addAction(String actionType, Action action, String tenantDomain) t LOG.debug(String.format("Adding Action for Action Type: %s.", actionType)); } String resolvedActionType = getActionTypeFromPath(actionType); + doPreAddActionValidations(action); // Check whether the maximum allowed actions per type is reached. validateMaxActionsPerType(resolvedActionType, tenantDomain); String generatedActionId = UUID.randomUUID().toString(); ActionDTO resolvedActionDTO = buildActionDTO(resolvedActionType, generatedActionId, action); - doPreAddActionValidations(resolvedActionType, resolvedActionDTO); daoFacade.addAction(resolvedActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); Action createdAction = getActionByActionId(actionType, generatedActionId, tenantDomain); @@ -158,9 +156,9 @@ public Action updateAction(String actionType, String actionId, Action action, St LOG.debug(String.format("Updating Action for Action Type: %s and Action ID: %s.", actionType, actionId)); } String resolvedActionType = getActionTypeFromPath(actionType); + doPreUpdateActionValidations(action); ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); ActionDTO updatingActionDTO = buildActionDTO(resolvedActionType, actionId, action); - doPreUpdateActionValidations(resolvedActionType, updatingActionDTO); daoFacade.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, action); @@ -286,7 +284,8 @@ private String getActionTypeFromPath(String actionType) throws ActionMgtClientEx .filter(type -> type.getPathParam().equals(actionType)) .map(Action.ActionTypes::getActionType) .findFirst() - .orElseThrow(() -> ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_TYPE)); + .orElseThrow(() -> + ActionManagementExceptionHandler.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_TYPE)); } /** @@ -301,7 +300,7 @@ private void validateMaxActionsPerType(String actionType, String tenantDomain) t Map actionsCountPerType = getActionsCountPerType(tenantDomain); if (actionsCountPerType.containsKey(actionType) && actionsCountPerType.get(actionType) >= IdentityUtil.getMaximumActionsPerActionType()) { - throw ActionManagementUtil.handleClientException( + throw ActionManagementExceptionHandler.handleClientException( ErrorMessage.ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED); } } @@ -321,7 +320,7 @@ private ActionDTO checkIfActionExists(String actionType, String actionId, String ActionDTO actionDTO = daoFacade.getActionByActionId(actionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); if (actionDTO == null || !actionType.equals(actionDTO.getType().name())) { - throw ActionManagementUtil.handleClientException( + throw ActionManagementExceptionHandler.handleClientException( ErrorMessage.ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID); } @@ -331,50 +330,35 @@ private ActionDTO checkIfActionExists(String actionType, String actionId, String /** * Perform pre validations on action model when creating an action. * - * @param actionType Action type. - * @param actionDTO Action create model. + * @param action Action creation model. * @throws ActionMgtClientException if action model is invalid. */ - private void doPreAddActionValidations(String actionType, ActionDTO actionDTO) throws ActionMgtClientException { - - ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ACTION_NAME_FIELD, actionDTO.getName()); - ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ENDPOINT_URI_FIELD, actionDTO.getEndpoint().getUri()); - ACTION_VALIDATOR.validateActionName(actionDTO.getName()); - ACTION_VALIDATOR.validateEndpointUri(actionDTO.getEndpoint().getUri()); - doEndpointAuthenticationValidation(actionDTO.getEndpoint().getAuthentication()); - - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); - if (actionPropertyResolver != null) { - actionPropertyResolver.doPreAddActionPropertiesValidations(actionDTO); - } + private void doPreAddActionValidations(Action action) throws ActionMgtClientException { + + ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ACTION_NAME_FIELD, action.getName()); + ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.ENDPOINT_URI_FIELD, action.getEndpoint().getUri()); + ACTION_VALIDATOR.validateActionName(action.getName()); + ACTION_VALIDATOR.validateEndpointUri(action.getEndpoint().getUri()); + doEndpointAuthenticationValidation(action.getEndpoint().getAuthentication()); } /** * Perform pre validations on action model when updating an existing action. - * This is specifically used during HTTP PATCH operation and - * only validate non-null and non-empty fields. + * This is specifically used during HTTP PATCH operation and only validate non-null and non-empty fields. * - * @param actionType Action type. - * @param actionDTO Action update model. + * @param action Action update model. * @throws ActionMgtClientException if action model is invalid. */ - private void doPreUpdateActionValidations(String actionType, ActionDTO actionDTO) throws ActionMgtClientException { + private void doPreUpdateActionValidations(Action action) throws ActionMgtClientException { - if (actionDTO.getName() != null) { - ACTION_VALIDATOR.validateActionName(actionDTO.getName()); + if (action.getName() != null) { + ACTION_VALIDATOR.validateActionName(action.getName()); } - if (actionDTO.getEndpoint() != null && actionDTO.getEndpoint().getUri() != null) { - ACTION_VALIDATOR.validateEndpointUri(actionDTO.getEndpoint().getUri()); + if (action.getEndpoint() != null && action.getEndpoint().getUri() != null) { + ACTION_VALIDATOR.validateEndpointUri(action.getEndpoint().getUri()); } - if (actionDTO.getEndpoint() != null && actionDTO.getEndpoint().getAuthentication() != null) { - doEndpointAuthenticationValidation(actionDTO.getEndpoint().getAuthentication()); - } - - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); - if (actionPropertyResolver != null) { - actionPropertyResolver.doPreUpdateActionPropertiesValidations(actionDTO); + if (action.getEndpoint() != null && action.getEndpoint().getAuthentication() != null) { + doEndpointAuthenticationValidation(action.getEndpoint().getAuthentication()); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java similarity index 83% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java index 1acfaddfab8e..e3f09f2fffa2 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java @@ -26,7 +26,7 @@ /** * Utility class for Action Management. */ -public class ActionManagementUtil { +public class ActionManagementExceptionHandler { /** * Handle Action Management client exceptions. @@ -45,18 +45,6 @@ public static ActionMgtClientException handleClientException(ErrorMessage error, return new ActionMgtClientException(error.getMessage(), description, error.getCode()); } - /** - * Handle Action Management client exceptions. - * - * @param error Error message. - * @param e Throwable. - * @return ActionMgtClientException. - */ - public static ActionMgtClientException handleClientException(ErrorMessage error, Throwable e) { - - return new ActionMgtClientException(error.getMessage(), error.getDescription(), error.getCode(), e); - } - /** * Handle Action Management server exceptions. * diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java index f518b720b765..4709faf7d0df 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java @@ -36,9 +36,6 @@ */ public class ActionSecretProcessor { - public ActionSecretProcessor() { - } - public List encryptAssociatedSecrets(Authentication authentication, String actionId) throws SecretManagementException { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java index 672f49cb1be5..54851f654ed2 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java @@ -36,9 +36,9 @@ public class ActionValidator { // and should start with an alphanumeric character. private static final String HEADER_REGEX = "^[a-zA-Z0-9][a-zA-Z0-9-.]+$"; - private Pattern actionNameRegexPattern = Pattern.compile(ACTION_NAME_REGEX); - private Pattern endpointUriRegexPattern = Pattern.compile(ENDPOINT_URI_REGEX); - private Pattern headerRegexPattern = Pattern.compile(HEADER_REGEX); + private final Pattern actionNameRegexPattern = Pattern.compile(ACTION_NAME_REGEX); + private final Pattern endpointUriRegexPattern = Pattern.compile(ENDPOINT_URI_REGEX); + private final Pattern headerRegexPattern = Pattern.compile(HEADER_REGEX); /** * Validate whether required fields exist. @@ -49,7 +49,8 @@ public class ActionValidator { public void validateForBlank(String fieldName, String fieldValue) throws ActionMgtClientException { if (StringUtils.isBlank(fieldValue)) { - throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_EMPTY_ACTION_REQUEST_FIELD, fieldName); + throw ActionManagementExceptionHandler.handleClientException(ErrorMessage.ERROR_EMPTY_ACTION_REQUEST_FIELD, + fieldName); } } @@ -63,8 +64,8 @@ public void validateActionName(String name) throws ActionMgtClientException { boolean isValidName = actionNameRegexPattern.matcher(name).matches(); if (!isValidName) { - throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, - ActionMgtConstants.ACTION_NAME_FIELD); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ACTION_NAME_FIELD); } } @@ -78,8 +79,8 @@ public void validateEndpointUri(String uri) throws ActionMgtClientException { boolean isValidUri = endpointUriRegexPattern.matcher(uri).matches(); if (!isValidUri) { - throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, - ActionMgtConstants.ENDPOINT_URI_FIELD); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ENDPOINT_URI_FIELD); } } @@ -93,8 +94,8 @@ public void validateHeader(String header) throws ActionMgtClientException { boolean isValidHeader = headerRegexPattern.matcher(header).matches(); if (!isValidHeader) { - throw ActionManagementUtil.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, - ActionMgtConstants.API_KEY_HEADER_FIELD); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.API_KEY_HEADER_FIELD); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index 94a49a5c091f..7537d27c3b53 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -26,12 +26,17 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverClientException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; +import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverServerException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; @@ -55,6 +60,8 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; @@ -97,6 +104,7 @@ public class ActionManagementDAOFacadeTest { private MockedStatic identityTenantUtil; private ActionManagementDAOFacade daoFacade; + private ActionDTO creatingActionDTO; private ActionDTO createdActionDTO; @BeforeClass @@ -119,19 +127,11 @@ public void setUp() throws SecretManagementException { MockitoAnnotations.openMocks(this); actionPropertyResolverFactory = mockStatic(ActionPropertyResolverFactory.class); - } - - @AfterMethod - public void tearDown() { - - identityTenantUtil.close(); - actionPropertyResolverFactory.close(); - } - - @Test(priority = 1) - public void testAddAction() throws ActionMgtException, ActionPropertyResolverException { + actionPropertyResolverFactory.when(() -> + ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionPropertyResolver); - ActionDTO creatingActionDTO = new ActionDTO.Builder() + creatingActionDTO = new ActionDTO.Builder() .id(PRE_UPDATE_PASSWORD_ACTION_ID) .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) .name(TEST_ACTION_NAME) @@ -144,14 +144,60 @@ public void testAddAction() throws ActionMgtException, ActionPropertyResolverExc .property(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder().certificateContent(TEST_CERTIFICATE).build()) .build(); + } + + @AfterMethod + public void tearDown() { + + identityTenantUtil.close(); + actionPropertyResolverFactory.close(); + } + + @Test(priority = 1) + public void testAddActionWithActionPropertyResolverClientException() throws ActionPropertyResolverException { + + doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(actionPropertyResolver) + .addProperties(any(), any()); + + try { + daoFacade.addAction(creatingActionDTO, TENANT_ID); + Assert.fail("Successful addition of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtClientException.class); + Assert.assertEquals(e.getErrorCode(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); + Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getMessage()); + Assert.assertEquals(e.getDescription(), "Invalid Certificate."); + } + } + + @Test(priority = 2) + public void testAddActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { + + doThrow(new ActionPropertyResolverServerException("Error adding Certificate.", new Throwable())) + .when(actionPropertyResolver).addProperties(any(), any()); + + try { + daoFacade.addAction(creatingActionDTO, TENANT_ID); + Assert.fail("Successful addition of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtServerException.class); + Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_WHILE_ADDING_ACTION.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof ActionPropertyResolverServerException) { + return; + } + } + Assert.fail("Expected ActionPropertyResolverServerException was not found in the exception chain"); + } + } + + @Test(priority = 3) + public void testAddAction() throws ActionMgtException, ActionPropertyResolverException { - actionPropertyResolverFactory.when( - () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) - .thenReturn(actionPropertyResolver); Map properties = new HashMap<>(); properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); properties.put(CERTIFICATE_PROPERTY_NAME, TestUtil.CERTIFICATE_ID); - when(actionPropertyResolver.addProperties(any(), any())).thenReturn(properties); + doReturn(properties).when(actionPropertyResolver).addProperties(any(), any()); try { daoFacade.addAction(creatingActionDTO, TENANT_ID); @@ -164,7 +210,7 @@ public void testAddAction() throws ActionMgtException, ActionPropertyResolverExc retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) .certificateContent(TEST_CERTIFICATE).build()); - when(actionPropertyResolver.getProperties(any(), any())).thenReturn(retrievedProperties); + doReturn(retrievedProperties).when(actionPropertyResolver).getProperties(any(), any()); createdActionDTO = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); @@ -181,11 +227,11 @@ public void testAddAction() throws ActionMgtException, ActionPropertyResolverExc Assert.assertEquals(createdAuthentication.getProperties().size(), creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), - TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC.getName(), - Authentication.Property.USERNAME.getName())); + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC, + Authentication.Property.USERNAME)); Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), - TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC.getName(), - Authentication.Property.PASSWORD.getName())); + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC, + Authentication.Property.PASSWORD)); Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); Assert.assertTrue(createdActionDTO.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); @@ -196,18 +242,15 @@ public void testAddAction() throws ActionMgtException, ActionPropertyResolverExc .getCertificateContent(), TEST_CERTIFICATE); } - @Test(priority = 2) + @Test(priority = 4) public void testGetActionsByType() throws ActionMgtException, ActionPropertyResolverException { - actionPropertyResolverFactory.when( - () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) - .thenReturn(actionPropertyResolver); Map retrievedProperties = new HashMap<>(); retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) .certificateContent(TEST_CERTIFICATE).build()); - when(actionPropertyResolver.getProperties(any(), any())).thenReturn(retrievedProperties); + doReturn(retrievedProperties).when(actionPropertyResolver).getProperties(any(), any()); List actionDTOs = daoFacade.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); ActionDTO result = actionDTOs.get(0); @@ -239,7 +282,45 @@ public void testGetActionsByType() throws ActionMgtException, ActionPropertyReso ((Certificate) createdActionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent()); } - @Test(priority = 3, dependsOnMethods = "testAddAction") + @Test(priority = 5) + public void testUpdateActionPropertyResolverClientException() throws ActionPropertyResolverException { + + doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(actionPropertyResolver) + .updateProperties(any(), any(), any()); + + try { + daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); + Assert.fail("Successful update of the actions without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtClientException.class); + Assert.assertEquals(e.getErrorCode(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); + Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getMessage()); + Assert.assertEquals(e.getDescription(), "Invalid Certificate."); + } + } + + @Test(priority = 6) + public void testUpdateActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { + + doThrow(new ActionPropertyResolverServerException("Error updating Certificate.")).when(actionPropertyResolver) + .updateProperties(any(), any(), any()); + + try { + daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); + Assert.fail("Successful update of the actions without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtServerException.class); + Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_WHILE_UPDATING_ACTION.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof ActionPropertyResolverServerException) { + return; + } + } + Assert.fail("Expected ActionPropertyResolverServerException was not found in the exception chain"); + } + } + + @Test(priority = 7, dependsOnMethods = "testAddAction") public void testUpdateCompleteAction() throws ActionMgtException, ActionPropertyResolverException { ActionDTO updatingAction = new ActionDTO.Builder() @@ -255,14 +336,10 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty .property(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder().certificateContent(TEST_CERTIFICATE_UPDATED).build()) .build(); - - actionPropertyResolverFactory.when( - () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) - .thenReturn(actionPropertyResolver); Map properties = new HashMap<>(); properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED); properties.put(CERTIFICATE_PROPERTY_NAME, CERTIFICATE_ID); - when(actionPropertyResolver.updateProperties(any(), any(), anyString())).thenReturn(properties); + doReturn(properties).when(actionPropertyResolver).updateProperties(any(), any(), anyString()); try { daoFacade.updateAction(updatingAction, createdActionDTO, TENANT_ID); @@ -275,7 +352,7 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) .certificateContent(TEST_CERTIFICATE_UPDATED).build()); - when(actionPropertyResolver.getProperties(any(), any())).thenReturn(retrievedProperties); + doReturn(retrievedProperties).when(actionPropertyResolver).getProperties(any(), any()); ActionDTO result = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, updatingAction.getId(), TENANT_ID); Assert.assertEquals(result.getId(), createdActionDTO.getId()); @@ -291,8 +368,8 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty Assert.assertEquals(updatedAuthentication.getProperties().size(), updatingAction.getEndpoint().getAuthentication().getProperties().size()); Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), - TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BEARER.getName(), - Authentication.Property.ACCESS_TOKEN.getName())); + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BEARER, + Authentication.Property.ACCESS_TOKEN)); Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); @@ -305,7 +382,7 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty createdActionDTO = result; } - @Test(priority = 4) + @Test(priority = 8) public void testDeactivateAction() throws ActionMgtException { Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); @@ -314,7 +391,7 @@ public void testDeactivateAction() throws ActionMgtException { Assert.assertEquals(deactivatedActionDTO.getStatus(), Action.Status.INACTIVE); } - @Test(priority = 5) + @Test(priority = 9) public void testActivateAction() throws ActionMgtException { ActionDTO activatedActionDTO = daoFacade.activateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), @@ -322,7 +399,7 @@ public void testActivateAction() throws ActionMgtException { Assert.assertEquals(activatedActionDTO.getStatus(), Action.Status.ACTIVE); } - @Test(priority = 6) + @Test(priority = 10) public void testGetActionsCountPerType() throws ActionMgtException { Map actionMap = daoFacade.getActionsCountPerType(TENANT_ID); @@ -330,12 +407,9 @@ public void testGetActionsCountPerType() throws ActionMgtException { Assert.assertEquals(actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue(), 1); } - @Test(priority = 7) + @Test(priority = 11) public void testDeleteAction() throws ActionMgtException, ActionPropertyResolverException { - actionPropertyResolverFactory.when( - () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) - .thenReturn(actionPropertyResolver); doNothing().when(actionPropertyResolver).deleteProperties(any(), anyString()); try { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java index edf18102d2a1..ceaa300f87db 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java @@ -24,6 +24,7 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; @@ -74,7 +75,6 @@ public class ActionManagementServiceImplTest { private ActionManagementService actionManagementService; - private Action sampleAction; @BeforeClass @@ -122,8 +122,8 @@ public void testAddAction() throws ActionMgtException, SecretManagementException secretProperties.get(Authentication.Property.PASSWORD.getName())); } - @Test(priority = 2, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Unable to create an Action.") + @Test(priority = 2, expectedExceptions = ActionMgtClientException.class, + expectedExceptionsMessageRegExp = "Invalid request.") public void testAddActionWithInvalidData() throws ActionMgtException { Action creatingAction = TestUtil.buildMockAction( TEST_INVALID_ACTION_NAME, @@ -134,8 +134,8 @@ public void testAddActionWithInvalidData() throws ActionMgtException { Assert.assertNull(action); } - @Test(priority = 3, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Unable to create an Action.") + @Test(priority = 3, expectedExceptions = ActionMgtClientException.class, + expectedExceptionsMessageRegExp = "Invalid request.") public void testAddActionWithEmptyData() throws ActionMgtException { Action creatingAction = TestUtil.buildMockAction( StringUtils.EMPTY, @@ -160,11 +160,11 @@ public void testAddMaximumActionsPerType() throws ActionMgtException { } @Test(priority = 5) - public void testGetActionsByActionType() throws ActionMgtException, SecretManagementException { + public void testGetActionsByActionType() throws ActionMgtException { List actions = actionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); - Assert.assertEquals(1, actions.size()); + Assert.assertEquals(actions.size(), 1); Action result = actions.get(0); Assert.assertEquals(result.getId(), sampleAction.getId()); Assert.assertEquals(result.getName(), sampleAction.getName()); @@ -184,7 +184,7 @@ public void testGetActionsByActionType() throws ActionMgtException, SecretManage } @Test(priority = 6) - public void testGetActionByActionId() throws ActionMgtException, SecretManagementException { + public void testGetActionByActionId() throws ActionMgtException { Action result = actionManagementService.getActionByActionId(sampleAction.getType().getPathParam(), sampleAction.getId(), TENANT_DOMAIN); @@ -262,7 +262,7 @@ public void testGetActionsCountPerType() throws ActionMgtException { Assert.assertNull(actionMap.get(Action.ActionTypes.AUTHENTICATION.getActionType())); for (Map.Entry entry: actionMap.entrySet()) { Assert.assertEquals(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), entry.getKey()); - Assert.assertEquals(1, entry.getValue().intValue()); + Assert.assertEquals(entry.getValue().intValue(), 1); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java index 59d8cf7d7061..29fb849cac01 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java @@ -113,7 +113,7 @@ public void testGetActionsByActionTypeFromDB() throws ActionMgtException { List actions = cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); verify(actionManagementServiceImpl, times(1)).getActionsByActionType(any(), any()); - Assert.assertEquals(1, actions.size()); + Assert.assertEquals(actions.size(), mockedActionsList.size()); Action result = actions.get(0); assertAction(result); } @@ -127,7 +127,7 @@ public void testGetActionsByActionTypeFromCache() throws ActionMgtException { TENANT_DOMAIN); verify(actionManagementServiceImpl, never()).getActionsByActionType(any(), any()); Assert.assertNotNull(actions); - Assert.assertEquals(1, actions.size()); + Assert.assertEquals(actions.size(), mockedActionsList.size()); Action result = actions.get(0); assertAction(result); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java index d9095d67a952..ef38040fe208 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java @@ -105,18 +105,18 @@ public void testEncryptAssociatedSecrets(Authentication authentication) throws S Assert.assertEquals(encryptedProperties.size(), authentication.getProperties().size()); for (AuthProperty authProperty : encryptedProperties) { - Authentication.Property property = Arrays.stream(Authentication.Property.values()) .filter(prop -> prop.getName().equals(authProperty.getName())) .findFirst() .orElse(null); AuthProperty inputAuthProperty = authentication.getProperty(property); + Assert.assertNotNull(property); Assert.assertEquals(authProperty.getName(), authentication.getProperty(property).getName()); Assert.assertEquals(authProperty.getIsConfidential(), inputAuthProperty.getIsConfidential()); if (authProperty.getIsConfidential()) { - Assert.assertEquals(authProperty.getValue(), TestUtil.buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - authentication.getType().name(), inputAuthProperty.getName())); + Assert.assertEquals(authProperty.getValue(), + TestUtil.buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, authentication.getType(), property)); } else { Assert.assertEquals(authProperty.getValue(), inputAuthProperty.getValue()); } @@ -140,7 +140,7 @@ public void testUpdateSecret() throws SecretManagementException { Assert.assertEquals(encryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); Assert.assertEquals(encryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); Assert.assertEquals(encryptedProperties.get(0).getValue(), buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName())); + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); } @Test @@ -152,7 +152,7 @@ public void testDecryptAssociatedSecrets() throws SecretManagementException { doReturn(true).when(secretManager).isSecretExist(any(), any()); Authentication authentication = buildMockBearerAuthentication(buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName())); + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); List decryptedProperties = actionSecretProcessor.decryptAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); @@ -173,8 +173,8 @@ public void testDecryptAssociatedSecretsForNonSecret() throws SecretManagementEx doReturn(true).when(secretManager).isSecretExist(any(), any()); Authentication authentication = buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, - buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY.getName(), - Authentication.Property.VALUE.getName())); + buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY, + Authentication.Property.VALUE)); List decryptedProperties = actionSecretProcessor.decryptAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); @@ -201,7 +201,7 @@ public void testDecryptAssociatedSecretsForNonExistingSecret() throws SecretMana doReturn(false).when(secretManager).isSecretExist(any(), any()); Authentication authentication = buildMockBearerAuthentication(buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName())); + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); actionSecretProcessor.decryptAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); } @@ -213,8 +213,8 @@ public void testDeleteAssociatedSecrets() throws SecretManagementException { doNothing().when(secretManager).deleteSecret(any(), any()); Authentication authentication = buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, - buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY.getName(), - Authentication.Property.VALUE.getName())); + buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY, + Authentication.Property.VALUE)); actionSecretProcessor.deleteAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); verify(secretManager, times(1)).deleteSecret(any(), any()); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java index 00779bbb0623..a235877c7147 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -52,21 +52,21 @@ public class TestUtil { public static final String TEST_USERNAME = "sampleUsername"; public static final String TEST_USERNAME_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.BASIC.getName(), Authentication.Property.USERNAME.getName()); + Authentication.Type.BASIC, Authentication.Property.USERNAME); public static final String TEST_PASSWORD = "samplePassword"; public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.BASIC.getName(), Authentication.Property.PASSWORD.getName()); + Authentication.Type.BASIC, Authentication.Property.PASSWORD); public static final String TEST_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; public static final String TEST_ACCESS_TOKEN_UPDATED = "fe326c2a-e83a-41fe-bc6a-ee79e1feabba"; public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.BEARER.getName(), Authentication.Property.ACCESS_TOKEN.getName()); + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN); public static final String TEST_API_KEY_HEADER = "sampleHeader"; public static final String TEST_API_KEY_HEADER_UPDATED = "UpdatedSampleHeader"; public static final String TEST_INVALID_API_KEY_HEADER = "-test-header"; public static final String TEST_API_KEY_VALUE = "sampleValue"; public static final String TEST_API_KEY_VALUE_UPDATED = "UpdatedSampleValue"; public static final String TEST_API_KEY_VALUE_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, - Authentication.Type.API_KEY.getName(), Authentication.Property.VALUE.getName()); + Authentication.Type.API_KEY, Authentication.Property.VALUE); public static final String TEST_ACTION_PROPERTY_NAME_1 = "samplePropertyName"; public static final String TEST_ACTION_PROPERTY_VALUE_1 = "samplePropertyValue"; @@ -92,9 +92,10 @@ public static Action buildMockAction(String name, String description, String uri .build(); } - public static String buildSecretName(String actionId, String authType, String authPropertyName) { + public static String buildSecretName(String actionId, Authentication.Type authType, + Authentication.Property authProperty) { - return TEST_SECRET_TYPE_ID + ":" + actionId + ":" + authType + ":" + authPropertyName; + return TEST_SECRET_TYPE_ID + ":" + actionId + ":" + authType.getName() + ":" + authProperty.getName(); } public static Authentication buildMockBasicAuthentication(String username, String password) { From 16418d47471b5fbbb87b2f24387c35078162d257 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Thu, 28 Nov 2024 13:08:44 +0530 Subject: [PATCH 23/34] Fix auditlogger --- .../internal/ActionMgtServiceComponent.java | 7 +- .../service/ActionPropertyResolver.java | 2 +- .../impl/ActionManagementServiceImpl.java | 8 +- .../util/ActionManagementAuditLogger.java | 70 ++++++---- .../ActionManagementExceptionHandler.java | 3 + .../util/ActionManagementAuditLoggerTest.java | 120 ++++++++++-------- .../management/model/Certificate.java | 5 + 7 files changed, 131 insertions(+), 84 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index 4f8888ceac5c..3dce8d3f3968 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -82,10 +82,8 @@ protected void deactivate(ComponentContext context) { ) protected void setActionConverter(ActionConverter actionConverter) { - if (LOG.isDebugEnabled()) { - LOG.debug("Registering ActionConverter: " + actionConverter.getClass().getName() + - " in the ActionMgtServiceComponent."); - } + LOG.debug("Registering ActionConverter: " + actionConverter.getClass().getName() + + " in the ActionMgtServiceComponent."); ActionConverterFactory.registerActionConverter(actionConverter); } @@ -95,6 +93,7 @@ protected void unsetActionConverter(ActionConverter actionConverter) { LOG.debug("Unregistering ActionConverter: " + actionConverter.getClass().getName() + " in the ActionMgtServiceComponent."); } + ActionConverterFactory.unregisterActionConverter(actionConverter); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java index d7742b7ed8e0..11ad9c607e16 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java @@ -42,7 +42,7 @@ default Map addProperties(ActionDTO actionDTO, String tenantDoma default Map getProperties(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { - return null; + return Collections.emptyMap(); } default Map updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index f204efc3434b..4d4437aa4d50 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -80,11 +80,11 @@ public Action addAction(String actionType, Action action, String tenantDomain) t // Check whether the maximum allowed actions per type is reached. validateMaxActionsPerType(resolvedActionType, tenantDomain); String generatedActionId = UUID.randomUUID().toString(); - ActionDTO resolvedActionDTO = buildActionDTO(resolvedActionType, generatedActionId, action); + ActionDTO creatingActionDTO = buildActionDTO(resolvedActionType, generatedActionId, action); - daoFacade.addAction(resolvedActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + daoFacade.addAction(creatingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); Action createdAction = getActionByActionId(actionType, generatedActionId, tenantDomain); - auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ADD, createdAction); + auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ADD, creatingActionDTO); return createdAction; } @@ -161,7 +161,7 @@ public Action updateAction(String actionType, String actionId, Action action, St ActionDTO updatingActionDTO = buildActionDTO(resolvedActionType, actionId, action); daoFacade.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); - auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, action); + auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, updatingActionDTO); return getActionByActionId(actionType, actionId, tenantDomain); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java index e28920ae8f2e..782de796d2a2 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java @@ -22,7 +22,7 @@ import org.json.JSONObject; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; @@ -31,6 +31,8 @@ import org.wso2.carbon.utils.AuditLog; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import java.util.Map; + import static org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils.jsonObjectToMap; import static org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils.triggerAuditLogEvent; @@ -43,14 +45,14 @@ public class ActionManagementAuditLogger { * Print action audit log related to the operation. * * @param operation Operation associated with the state change. - * @param action Action object to be logged. + * @param actionDTO Action object to be logged. */ - public void printAuditLog(Operation operation, Action action) { + public void printAuditLog(Operation operation, ActionDTO actionDTO) { if (!LoggerUtils.isEnableV2AuditLogs()) { return; } - JSONObject data = createAuditLogEntry(action); + JSONObject data = createAuditLogEntry(actionDTO); buildAuditLog(operation, data); } @@ -59,14 +61,14 @@ public void printAuditLog(Operation operation, Action action) { * * @param operation Operation associated with the state change. * @param actionId ID of the action to be logged. - * @param action Action object to be logged. + * @param actionDTO Action object to be logged. */ - public void printAuditLog(Operation operation, String actionId, Action action) { + public void printAuditLog(Operation operation, String actionId, ActionDTO actionDTO) { if (!LoggerUtils.isEnableV2AuditLogs()) { return; } - JSONObject data = createAuditLogEntry(actionId, action); + JSONObject data = createAuditLogEntry(actionId, actionDTO); buildAuditLog(operation, data); } @@ -107,18 +109,19 @@ private void buildAuditLog(Operation operation, JSONObject data) { * Create audit log data with action. * This method expects all the action fields to be non-null/non-empty. * - * @param action Action to be logged. + * @param actionDTO Action to be logged. * @return audit log data. */ - private JSONObject createAuditLogEntry(Action action) { + private JSONObject createAuditLogEntry(ActionDTO actionDTO) { JSONObject data = new JSONObject(); - data.put(LogConstants.ACTION_TYPE_FIELD, action.getType()); - data.put(LogConstants.ACTION_ID_FIELD, action.getId()); - data.put(LogConstants.ACTION_NAME_FIELD, action.getName()); - data.put(LogConstants.ACTION_DESCRIPTION_FIELD, action.getDescription()); - data.put(LogConstants.ACTION_STATUS_FIELD, action.getStatus()); - data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getAllEndpointData(action.getEndpoint())); + data.put(LogConstants.ACTION_TYPE_FIELD, actionDTO.getType()); + data.put(LogConstants.ACTION_ID_FIELD, actionDTO.getId()); + data.put(LogConstants.ACTION_NAME_FIELD, actionDTO.getName()); + data.put(LogConstants.ACTION_DESCRIPTION_FIELD, actionDTO.getDescription()); + data.put(LogConstants.ACTION_STATUS_FIELD, actionDTO.getStatus()); + data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getAllEndpointData(actionDTO.getEndpoint())); + data.put(LogConstants.ACTION_PROPERTIES, getPropertiesData(actionDTO.getProperties())); return data; } @@ -126,21 +129,25 @@ private JSONObject createAuditLogEntry(Action action) { * Create audit log data with action and ID. * This method expects null/empty action fields. * - * @param actionId ID of the action to be logged. - * @param action Action to be logged. + * @param actionId ID of the action to be logged. + * @param actionDTO Action to be logged. * @return audit log data. */ - private JSONObject createAuditLogEntry(String actionId, Action action) { + private JSONObject createAuditLogEntry(String actionId, ActionDTO actionDTO) { JSONObject data = new JSONObject(); - data.put(LogConstants.ACTION_TYPE_FIELD, action.getType() != null ? action.getType() : JSONObject.NULL); + data.put(LogConstants.ACTION_TYPE_FIELD, actionDTO.getType() != null ? actionDTO.getType() : JSONObject.NULL); data.put(LogConstants.ACTION_ID_FIELD, actionId); - data.put(LogConstants.ACTION_NAME_FIELD, action.getName() != null ? action.getName() : JSONObject.NULL); + data.put(LogConstants.ACTION_NAME_FIELD, actionDTO.getName() != null ? actionDTO.getName() : JSONObject.NULL); data.put(LogConstants.ACTION_DESCRIPTION_FIELD, - action.getDescription() != null ? action.getDescription() : JSONObject.NULL); - data.put(LogConstants.ACTION_STATUS_FIELD, action.getStatus() != null ? action.getStatus() : JSONObject.NULL); - if (action.getEndpoint() != null) { - data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getEndpointData(action.getEndpoint())); + actionDTO.getDescription() != null ? actionDTO.getDescription() : JSONObject.NULL); + data.put(LogConstants.ACTION_STATUS_FIELD, actionDTO.getStatus() != null ? actionDTO.getStatus() + : JSONObject.NULL); + if (actionDTO.getEndpoint() != null) { + data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getEndpointData(actionDTO.getEndpoint())); + } + if (actionDTO.getProperties() != null && !actionDTO.getProperties().isEmpty()) { + data.put(LogConstants.ACTION_PROPERTIES, getPropertiesData(actionDTO.getProperties())); } return data; } @@ -193,6 +200,20 @@ private JSONObject getAllEndpointData(EndpointConfig endpointConfig) { return endpointData; } + /** + * Retrieve properties data to be logged. + * All the properties will be masked. + * + * @param properties Properties to be logged. + * @return properties data. + */ + private JSONObject getPropertiesData(Map properties) { + + JSONObject propertiesData = new JSONObject(); + properties.forEach((key, value) -> propertiesData.put(key, LoggerUtils.getMaskedContent(value.toString()))); + return propertiesData; + } + /** * Retrieve endpoint configuration data to be logged. * This method expects null/empty endpoint config fields. @@ -310,6 +331,7 @@ private static class LogConstants { public static final String ACTION_DESCRIPTION_FIELD = "ActionDescription"; public static final String ACTION_STATUS_FIELD = "ActionStatus"; public static final String ENDPOINT_CONFIG_FIELD = "EndpointConfiguration"; + public static final String ACTION_PROPERTIES = "Properties"; public static final String ENDPOINT_URI_FIELD = "EndpointUri"; public static final String AUTHENTICATION_SCHEME_FIELD = "AuthenticationScheme"; public static final String USERNAME_FIELD = "Username"; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java index e3f09f2fffa2..87ece6d5aa6b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java @@ -28,6 +28,9 @@ */ public class ActionManagementExceptionHandler { + private ActionManagementExceptionHandler() { + } + /** * Handle Action Management client exceptions. * diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java index a5b1d64cb194..83300fc2a60b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java @@ -27,10 +27,12 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; +import org.wso2.carbon.identity.certificate.management.model.Certificate; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; @@ -44,6 +46,17 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE; /** * Unit test class for ActionManagementAuditLogger class. @@ -52,7 +65,7 @@ public class ActionManagementAuditLoggerTest { private ActionManagementAuditLogger auditLogger; - private Action action; + private ActionDTO actionDTO; private CarbonContext carbonContext; private MockedStatic carbonContextMockedStatic; private MockedStatic identityUtil; @@ -82,28 +95,33 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { loggerUtilsMockedStatic = mockStatic(LoggerUtils.class); loggerUtilsMockedStatic.when(LoggerUtils::isEnableV2AuditLogs).thenReturn(true); loggerUtilsMockedStatic.when(() -> LoggerUtils.jsonObjectToMap(any(JSONObject.class))).thenCallRealMethod(); - - // Mock Action - action = mock(Action.class); - when(action.getId()).thenReturn("action-test-id"); - when(action.getName()).thenReturn("Test Action"); - when(action.getDescription()).thenReturn("This is a test action."); - when(action.getType()).thenReturn(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); - Map authProperties = new HashMap<>(); - authProperties.put("accessToken", "W*********t"); - Authentication auth = new Authentication.AuthenticationBuilder().type( - Authentication.Type.BEARER).properties(authProperties).build(); - when(action.getEndpoint()).thenReturn(new EndpointConfig.EndpointConfigBuilder(). - uri("https://test.com"). - authentication(auth).build()); - when(action.getStatus()).thenReturn(Action.Status.ACTIVE); + loggerUtilsMockedStatic.when(() -> LoggerUtils.getMaskedContent(any(String.class))).thenCallRealMethod(); + + Map actionProperties = new HashMap<>(); + actionProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); + actionProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE).build()); + + actionDTO = new ActionDTO.Builder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .status(Action.Status.ACTIVE) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(new Authentication.BearerAuthBuilder(TEST_ACCESS_TOKEN).build()) + .build()) + .properties(actionProperties) + .build(); } @AfterMethod public void tearDown() { auditLogger = null; - action = null; + actionDTO = null; carbonContextMockedStatic.close(); identityUtil.close(); identityTenantUtil.close(); @@ -114,7 +132,7 @@ public void tearDown() { public void testPrintAuditLogWithAction() throws NoSuchFieldException, IllegalAccessException { ActionManagementAuditLogger.Operation operation = ActionManagementAuditLogger.Operation.ADD; - auditLogger.printAuditLog(operation, action); + auditLogger.printAuditLog(operation, actionDTO); AuditLog.AuditLogBuilder capturedArg = captureTriggerAuditLogEventArgs(); Assert.assertNotNull(capturedArg); @@ -126,7 +144,7 @@ public void testPrintAuditLogWithAction() throws NoSuchFieldException, IllegalAc public void testPrintAuditLogWithActionId() throws NoSuchFieldException, IllegalAccessException { ActionManagementAuditLogger.Operation operation = ActionManagementAuditLogger.Operation.UPDATE; - auditLogger.printAuditLog(operation, action.getId(), action); + auditLogger.printAuditLog(operation, actionDTO.getId(), actionDTO); AuditLog.AuditLogBuilder capturedArg = captureTriggerAuditLogEventArgs(); Assert.assertNotNull(capturedArg); @@ -138,11 +156,11 @@ public void testPrintAuditLogWithActionId() throws NoSuchFieldException, Illegal public void testPrintAuditLogWithActionTypeAndId() throws NoSuchFieldException, IllegalAccessException { ActionManagementAuditLogger.Operation operation = ActionManagementAuditLogger.Operation.DELETE; - auditLogger.printAuditLog(operation, action.getType().name(), action.getId()); + auditLogger.printAuditLog(operation, actionDTO.getType().name(), actionDTO.getId()); AuditLog.AuditLogBuilder capturedArg = captureTriggerAuditLogEventArgs(); Assert.assertNotNull(capturedArg); - Assert.assertEquals(extractMapByField("ActionId", capturedArg), "action-test-id"); + Assert.assertEquals(extractMapByField("ActionId", capturedArg), actionDTO.getId()); Assert.assertEquals(extractMapByField("ActionType", capturedArg), Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType()); assertAuditLoggerData(capturedArg, DELETE_ACTION); @@ -182,25 +200,6 @@ private String extractMapByField(String fieldName, AuditLog.AuditLogBuilder audi return (String) dataMap.get(fieldName); } - /** - * Extract the specific field name from the provided map. - * - * @param fieldName Name of the field to be extracted. - * @param auditLogBuilder {@link AuditLog.AuditLogBuilder} instance. - * @return Value of the extracted field. - * @throws NoSuchFieldException if the provided field does not exist. - * @throws IllegalAccessException if the provided field is not accessible. - */ - private String extractEndpointMapByField(String fieldName, AuditLog.AuditLogBuilder auditLogBuilder) - throws NoSuchFieldException, IllegalAccessException { - - Field dataField = AuditLog.AuditLogBuilder.class.getDeclaredField("data"); - dataField.setAccessible(true); - Map dataMap = (Map) dataField.get(auditLogBuilder); - Map endpointConfigMap = (Map) dataMap.get("EndpointConfiguration"); - return (String) endpointConfigMap.get(fieldName); - } - /** * Extract field. * @@ -225,20 +224,39 @@ private String extractField(String fieldName, AuditLog.AuditLogBuilder auditLogB * @throws NoSuchFieldException if the provided field does not exist. * @throws IllegalAccessException if the provided field is not accessible. */ - private void assertActionData(AuditLog.AuditLogBuilder auditLogBuilder) - throws NoSuchFieldException, IllegalAccessException { + private void assertActionData(AuditLog.AuditLogBuilder auditLogBuilder) throws NoSuchFieldException, + IllegalAccessException { + + Field dataField = AuditLog.AuditLogBuilder.class.getDeclaredField("data"); + dataField.setAccessible(true); + Map dataMap = (Map) dataField.get(auditLogBuilder); + Map endpointConfigMap = (Map) dataMap.get("EndpointConfiguration"); + Map propertiesMap = (Map) dataMap.get("Properties"); - Assert.assertEquals(extractMapByField("ActionId", auditLogBuilder), "action-test-id"); - Assert.assertEquals(extractMapByField("ActionName", auditLogBuilder), "Test Action"); - Assert.assertEquals(extractMapByField("ActionType", auditLogBuilder), + Assert.assertEquals(dataMap.get("ActionId").toString(), PRE_UPDATE_PASSWORD_ACTION_ID); + Assert.assertEquals(dataMap.get("ActionName").toString(), TEST_ACTION_NAME); + Assert.assertEquals(dataMap.get("ActionType").toString(), Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType()); - Assert.assertEquals(extractMapByField("ActionStatus", auditLogBuilder), Action.Status.ACTIVE.name()); - Assert.assertEquals(extractMapByField("ActionDescription", auditLogBuilder), - "This is a test action."); - Assert.assertEquals(extractEndpointMapByField("AuthenticationScheme", auditLogBuilder), + Assert.assertEquals(dataMap.get("ActionStatus").toString(), Action.Status.ACTIVE.name()); + Assert.assertEquals(dataMap.get("ActionDescription").toString(), TEST_ACTION_DESCRIPTION); + + Assert.assertEquals(endpointConfigMap.get("EndpointUri").toString(), TEST_ACTION_URI); + Assert.assertEquals(endpointConfigMap.get("AuthenticationScheme").toString(), Authentication.Type.BEARER.getName()); - Assert.assertEquals(extractEndpointMapByField("EndpointUri", auditLogBuilder), - "https://test.com"); + assertMasked(endpointConfigMap.get("AccessToken").toString()); + + assertMasked(propertiesMap.get(PASSWORD_SHARING_TYPE_PROPERTY_NAME).toString()); + assertMasked(propertiesMap.get(CERTIFICATE_PROPERTY_NAME).toString()); + } + + /** + * Assert masked data fields. + * + * @param value Value to be asserted. + */ + private void assertMasked(String value) { + + Assert.assertTrue(value.contains("*")); } /** diff --git a/components/certificate-mgt/org.wso2.carbon.identity.certificate.management/src/main/java/org/wso2/carbon/identity/certificate/management/model/Certificate.java b/components/certificate-mgt/org.wso2.carbon.identity.certificate.management/src/main/java/org/wso2/carbon/identity/certificate/management/model/Certificate.java index 788a462e1f6f..aac90d4464a5 100644 --- a/components/certificate-mgt/org.wso2.carbon.identity.certificate.management/src/main/java/org/wso2/carbon/identity/certificate/management/model/Certificate.java +++ b/components/certificate-mgt/org.wso2.carbon.identity.certificate.management/src/main/java/org/wso2/carbon/identity/certificate/management/model/Certificate.java @@ -50,6 +50,11 @@ public String getCertificateContent() { return certificateContent; } + public String toString() { + + return certificateContent; + } + /** * Certificate builder. */ From edeb975693380b404a45f24842338951d17c1695 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Fri, 29 Nov 2024 17:10:10 +0530 Subject: [PATCH 24/34] Address comments --- .../management/dao/ActionManagementDAO.java | 2 +- .../dao/impl/ActionManagementDAOFacade.java | 137 +++++----- .../dao/impl/ActionManagementDAOImpl.java | 48 ++-- .../management/dao/model/ActionDTO.java | 238 ------------------ .../action/management/model/ActionDTO.java | 136 ++++++++++ .../management/service/ActionConverter.java | 11 +- .../service/ActionPropertyResolver.java | 25 +- .../impl/ActionManagementServiceImpl.java | 21 +- .../management/util/ActionDTOBuilder.java | 208 +++++++++++++++ .../util/ActionManagementAuditLogger.java | 2 +- .../dao/ActionManagementDAOFacadeTest.java | 119 ++++----- .../dao/ActionManagementDAOImplTest.java | 29 ++- .../dao/TestActionPropertyResolver.java | 105 ++++++++ .../util/ActionManagementAuditLoggerTest.java | 4 +- .../resources/dbscripts/h2.sql | 9 - 15 files changed, 649 insertions(+), 445 deletions(-) delete mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java create mode 100644 components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java index 4680886cd859..d61a94d5932d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java @@ -18,8 +18,8 @@ package org.wso2.carbon.identity.action.management.dao; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import java.util.List; import java.util.Map; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index 64257b20cd33..acfc43ac5785 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -24,15 +24,18 @@ import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverClientException; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; @@ -66,12 +69,14 @@ public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtExc NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { jdbcTemplate.withTransaction(template -> { + ActionDTOBuilder actionDTOBuilder = new ActionDTOBuilder(actionDTO); // Encrypt authentication secrets - encryptAuthenticationSecrets(actionDTO); + encryptAddingAuthSecrets(actionDTOBuilder); // Resolve action properties - addProperties(actionDTO, tenantId); + ActionDTO resolvedActionDTO = getActionDTOWithResolvedAddingProperties(actionDTOBuilder.build(), + tenantId); - actionManagementDAO.addAction(actionDTO, tenantId); + actionManagementDAO.addAction(resolvedActionDTO, tenantId); return null; }); } catch (TransactionException e) { @@ -88,9 +93,8 @@ public List getActionsByActionType(String actionType, Integer tenantI try { List actionDTOS = actionManagementDAO.getActionsByActionType(actionType, tenantId); - getPropertiesOfActionDTOs(actionType, actionDTOS, tenantId); - return actionDTOS; + return getActionDTOsWithPopulatedProperties(actionType, actionDTOS, tenantId); } catch (ActionMgtException | ActionPropertyResolverException e) { throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); @@ -103,12 +107,12 @@ public ActionDTO getActionByActionId(String actionType, String actionId, Integer try { ActionDTO actionDTO = actionManagementDAO.getActionByActionId(actionType, actionId, tenantId); - if (actionDTO != null) { - // Resolve action properties - getProperties(actionDTO, tenantId); + if (actionDTO == null) { + return null; } - return actionDTO; + // Populate action properties + return getActionDTOWithPopulatedProperties(actionDTO, tenantId); } catch (ActionMgtException | ActionPropertyResolverException e) { throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); @@ -122,12 +126,15 @@ public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDT NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { jdbcTemplate.withTransaction(template -> { + ActionDTOBuilder updatingActionDTOBuilder = new ActionDTOBuilder(updatingActionDTO); // Encrypt authentication secrets - updateAuthenticationSecrets(updatingActionDTO, existingActionDTO); + encryptUpdatingAuthSecrets(updatingActionDTOBuilder, existingActionDTO); // Resolve action properties - updateProperties(updatingActionDTO, existingActionDTO, tenantId); + ActionDTO resolvedUpdatingActionDTO = + getActionDTOWithResolvedUpdatingProperties(updatingActionDTOBuilder.build(), existingActionDTO, + tenantId); - actionManagementDAO.updateAction(updatingActionDTO, existingActionDTO, tenantId); + actionManagementDAO.updateAction(resolvedUpdatingActionDTO, existingActionDTO, tenantId); return null; }); } catch (TransactionException e) { @@ -187,28 +194,36 @@ public ActionDTO deactivateAction(String actionType, String actionId, Integer te @Override public Map getActionsCountPerType(Integer tenantId) throws ActionMgtException { - return actionManagementDAO.getActionsCountPerType(tenantId); + try { + return actionManagementDAO.getActionsCountPerType(tenantId); + } catch (ActionMgtException e) { + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); + } } - private void encryptAuthenticationSecrets(ActionDTO actionDTO) throws ActionMgtException { + private void encryptAddingAuthSecrets(ActionDTOBuilder actionDTOBuilder) throws ActionMgtException { try { List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets( - actionDTO.getEndpoint().getAuthentication(), actionDTO.getId()); - actionDTO.setAuthenticationProperties(encryptedProperties); + actionDTOBuilder.getEndpoint().getAuthentication(), actionDTOBuilder.getId()); + + addEncryptedAuthSecretsToBuilder(actionDTOBuilder, encryptedProperties); } catch (SecretManagementException e) { throw new ActionMgtServerException("Error while encrypting Action Endpoint Authentication Secrets.", e); } } - private void updateAuthenticationSecrets(ActionDTO updatingActionDTO, ActionDTO existingActionDTO) + private void encryptUpdatingAuthSecrets(ActionDTOBuilder updatingActionDTOBuilder, + ActionDTO existingActionDTO) throws ActionMgtException { - if (updatingActionDTO.getEndpoint() == null || updatingActionDTO.getEndpoint().getAuthentication() == null) { + if (updatingActionDTOBuilder.getEndpoint() == null || + updatingActionDTOBuilder.getEndpoint().getAuthentication() == null) { return; } - Authentication updatingAuthentication = updatingActionDTO.getEndpoint().getAuthentication(); + Authentication updatingAuthentication = updatingActionDTOBuilder.getEndpoint().getAuthentication(); Authentication existingAuthentication = existingActionDTO.getEndpoint().getAuthentication(); try { @@ -216,8 +231,9 @@ private void updateAuthenticationSecrets(ActionDTO updatingActionDTO, ActionDTO actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, existingActionDTO.getId()); } List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets( - updatingAuthentication, updatingActionDTO.getId()); - updatingActionDTO.setAuthenticationProperties(encryptedProperties); + updatingAuthentication, updatingActionDTOBuilder.getId()); + + addEncryptedAuthSecretsToBuilder(updatingActionDTOBuilder, encryptedProperties); } catch (SecretManagementException e) { throw new ActionMgtServerException("Error while updating Action Endpoint Authentication Secrets.", e); } @@ -233,61 +249,70 @@ private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws Act } } - private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { + private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, + List encryptedProperties) { + + Map encryptedPropertyMap = encryptedProperties.stream() + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + + actionDTOBuilder.endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(actionDTOBuilder.getEndpoint().getUri()) + .authentication(new Authentication.AuthenticationBuilder() + .type(actionDTOBuilder.getEndpoint().getAuthentication().getType()) + .properties(encryptedPropertyMap) + .build()) + .build()); + } + + private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, Integer tenantId) + throws ActionPropertyResolverException { - Map properties = null; ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); - - if (actionPropertyResolver != null) { - properties = actionPropertyResolver.addProperties(actionDTO, - IdentityTenantUtil.getTenantDomain(tenantId)); - } - if (properties != null) { - actionDTO.setProperties(properties.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + if (actionPropertyResolver == null) { + return actionDTO; } + + return actionPropertyResolver.resolveAddingProperties(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } - private void getPropertiesOfActionDTOs(String actionType, List actionDTOS, Integer tenantId) + private List getActionDTOsWithPopulatedProperties(String actionType, List actionDTOS, + Integer tenantId) throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver( - org.wso2.carbon.identity.action.management.model.Action.ActionTypes.valueOf(actionType)); + ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); if (actionPropertyResolver == null) { - return; + return actionDTOS; } - for (ActionDTO actionDTO : actionDTOS) { - actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, - IdentityTenantUtil.getTenantDomain(tenantId))); - } + return actionPropertyResolver.populateProperties(actionDTOS, IdentityTenantUtil.getTenantDomain(tenantId)); } - private void getProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { + private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integer tenantId) + throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); - - if (actionPropertyResolver != null) { - actionDTO.setProperties(actionPropertyResolver.getProperties(actionDTO, - IdentityTenantUtil.getTenantDomain(tenantId))); + if (actionPropertyResolver == null) { + return actionDTO; } + + return actionPropertyResolver.populateProperties(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } - private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingActionDTO, + ActionDTO existingActionDTO, Integer tenantId) throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(updatingActionDTO.getType()); - - if (actionPropertyResolver != null) { - Map properties = actionPropertyResolver.updateProperties(updatingActionDTO, - existingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); - updatingActionDTO.setProperties(properties.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + if (actionPropertyResolver == null) { + return updatingActionDTO; } + + return actionPropertyResolver.resolveUpdatingProperties(updatingActionDTO, existingActionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); } private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) @@ -295,11 +320,11 @@ private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(deletingActionDTO.getType()); - - if (actionPropertyResolver != null) { - actionPropertyResolver.deleteProperties(deletingActionDTO, - IdentityTenantUtil.getTenantDomain(tenantId)); + if (actionPropertyResolver == null) { + return; } + + actionPropertyResolver.deleteProperties(deletingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } private static void handleActionPropertyResolverClientException(Throwable throwable) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 6c1a72fa51e0..42cb23c9dee4 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -23,16 +23,15 @@ import org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException; import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; import org.wso2.carbon.identity.action.management.constant.ActionMgtSQLConstants; -import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import java.sql.Connection; @@ -78,24 +77,25 @@ public List getActionsByActionType(String actionType, Integer tenantI try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { String actionId = rs.getString(ActionMgtSQLConstants.Column.ACTION_UUID); - - ActionDTO.Builder actionBuilder = new ActionDTO.Builder() + ActionDTO actionDTO = new ActionDTOBuilder() .id(actionId) .type(org.wso2.carbon.identity.action.management.model.Action.ActionTypes.valueOf( rs.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) .name(rs.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) .description(rs.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) .status(org.wso2.carbon.identity.action.management.model.Action.Status.valueOf( - rs.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))); - actionBuilder.setEndpointAndProperties(getActionPropertiesFromDB(actionId, tenantId)); + rs.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) + .setEndpointAndProperties(getActionPropertiesFromDB(actionId, tenantId)) + .build(); - actionDTOS.add(actionBuilder.build()); + actionDTOS.add(actionDTO); } } return actionDTOS; } catch (SQLException e) { - throw new ActionMgtServerException("Error while retrieving Actions Basic information by Action Type.", e); + throw new ActionMgtServerException("Error while retrieving Actions information by Action Type from " + + "the system.", e); } } @@ -103,7 +103,7 @@ public List getActionsByActionType(String actionType, Integer tenantI public ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException { - ActionDTO.Builder actionBuilder = getBasicInfo(actionType, actionId, tenantId); + ActionDTOBuilder actionBuilder = getBasicInfo(actionType, actionId, tenantId); if (actionBuilder == null) { return null; } @@ -141,7 +141,7 @@ public void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws A return null; }); } catch (TransactionException e) { - throw new ActionMgtServerException("Error while deleting Action.", e); + throw new ActionMgtServerException("Error while deleting Action information in the system.", e); } } @@ -171,8 +171,8 @@ public Map getActionsCountPerType(Integer tenantId) throws Acti return actionTypesCountMap; } catch (DataAccessException e) { - throw ActionManagementExceptionHandler.handleServerException( - ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); + throw new ActionMgtServerException("Error while retrieving Actions count per Action Type from the system.", + e); } } @@ -197,7 +197,7 @@ private void addBasicInfo(ActionDTO actionDTO, Integer tenantId) throws ActionMg return null; }); } catch (TransactionException e) { - throw new ActionMgtServerException("Error while adding Action Basic information.", e); + throw new ActionMgtServerException("Error while adding Action Basic information in the system.", e); } } @@ -231,7 +231,7 @@ private void updateBasicInfo(ActionDTO updatingActionDTO, ActionDTO existingActi statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); } catch (DataAccessException e) { - throw new ActionMgtServerException("Error while updating Action Basic information.", e); + throw new ActionMgtServerException("Error while updating Action Basic information in the system.", e); } } @@ -240,16 +240,16 @@ private void updateBasicInfo(ActionDTO updatingActionDTO, ActionDTO existingActi * * @param actionId UUID of the created Action. * @param tenantId Tenant ID. - * @return Action Response Builder with action basic information. + * @return ActionDTO Builder with action basic information. * @throws ActionMgtException If an error occurs while retrieving action basic info from the database. */ - private ActionDTO.Builder getBasicInfo(String actionType, String actionId, Integer tenantId) + private ActionDTOBuilder getBasicInfo(String actionType, String actionId, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { return jdbcTemplate.fetchSingleRecord(ActionMgtSQLConstants.Query.GET_ACTION_BASIC_INFO_BY_ID, - (resultSet, rowNumber) -> new ActionDTO.Builder() + (resultSet, rowNumber) -> new ActionDTOBuilder() .id(actionId) .type(Action.ActionTypes.valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) @@ -261,7 +261,7 @@ private ActionDTO.Builder getBasicInfo(String actionType, String actionId, Integ statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); } catch (DataAccessException e) { - throw new ActionMgtServerException("Error while retrieving Action Basic information.", e); + throw new ActionMgtServerException("Error while retrieving Action Basic information from the system.", e); } } @@ -277,7 +277,7 @@ private void addEndpoint(ActionDTO actionDTO, Integer tenantId) throws ActionMgt addActionPropertiesToDB(actionDTO.getId(), endpointProperties, tenantId); } catch (TransactionException e) { - throw new ActionMgtServerException("Error while adding Action Endpoint configurations.", e); + throw new ActionMgtServerException("Error while adding Action Endpoint configurations in the system.", e); } } @@ -298,7 +298,7 @@ private void updateEndpoint(ActionDTO updatingActionDTO, ActionDTO existingActio updateEndpointAuthentication(updatingActionDTO.getId(), updatingEndpoint.getAuthentication(), existingActionDTO.getEndpoint().getAuthentication(), tenantId); } catch (ActionMgtException | TransactionException e) { - throw new ActionMgtServerException("Error while updating Action Endpoint.", e); + throw new ActionMgtServerException("Error while updating Action Endpoint information in the system.", e); } } @@ -367,7 +367,7 @@ private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionM try { addActionPropertiesToDB(actionDTO.getId(), actionProperties, tenantId); } catch (TransactionException e) { - throw new ActionMgtServerException("Error while adding Action Properties.", e); + throw new ActionMgtServerException("Error while adding Action Properties in the system.", e); } } @@ -388,7 +388,7 @@ private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingAct // Add updated properties. addActionPropertiesToDB(updatingActionDTO.getId(), updatingProperties, tenantId); } catch (TransactionException e) { - throw new ActionMgtServerException("Error while updating Action Properties.", e); + throw new ActionMgtServerException("Error while updating Action Properties in the system.", e); } } @@ -448,7 +448,7 @@ private Map getActionPropertiesFromDB(String actionId, Integer t return actionEndpointProperties; } catch (DataAccessException e) { - throw new ActionMgtServerException("Error while retrieving Action Properties.", e); + throw new ActionMgtServerException("Error while retrieving Action Properties from the system.", e); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java deleted file mode 100644 index 2179a9aacb1d..000000000000 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/model/ActionDTO.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.identity.action.management.dao.model; - -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; -import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; -import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.AuthProperty; -import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Action Data Transfer Object. - */ -public class ActionDTO { - - private String id; - private Action.ActionTypes type; - private final String name; - private final String description; - private final Action.Status status; - private EndpointConfig endpoint; - private Map properties; - - public ActionDTO(Builder builder) { - - this.id = builder.id; - this.type = builder.type; - this.name = builder.name; - this.description = builder.description; - this.status = builder.status; - this.endpoint = builder.endpoint; - this.properties = builder.properties; - } - - public void setId(String id) { - - this.id = id; - } - - public String getId() { - - return id; - } - - public void setType(Action.ActionTypes type) { - - this.type = type; - } - - public Action.ActionTypes getType() { - - return type; - } - - public String getName() { - - return name; - } - - public String getDescription() { - - return description; - } - - public org.wso2.carbon.identity.action.management.model.Action.Status getStatus() { - - return status; - } - - public EndpointConfig getEndpoint() { - - return endpoint; - } - - public void setAuthenticationProperties(List authProperties) { - - if (this.endpoint != null && this.endpoint.getAuthentication() != null) { - Map propertyMap = authProperties.stream() - .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); - - this.endpoint = new EndpointConfig.EndpointConfigBuilder() - .uri(this.endpoint.getUri()) - .authentication(new Authentication.AuthenticationBuilder() - .type(this.endpoint.getAuthentication().getType()) - .properties(propertyMap) - .build()) - .build(); - } - } - - public void setProperties(Map properties) { - - this.properties = properties; - } - - public Map getProperties() { - - return properties; - } - - public Object getProperty(String propertyName) { - - if (properties == null) { - return null; - } - - return properties.get(propertyName); - } - - /** - * Builder for Extended Action. - */ - public static class Builder { - - private String id; - private Action.ActionTypes type; - private String name; - private String description; - private Action.Status status; - private EndpointConfig endpoint; - private Map properties; - - public Builder id(String id) { - - this.id = id; - return this; - } - - public Builder type(Action.ActionTypes type) { - - this.type = type; - return this; - } - - public Builder name(String name) { - - this.name = name; - return this; - } - - public Builder description(String description) { - - this.description = description; - return this; - } - - public Builder status(Action.Status status) { - - this.status = status; - return this; - } - - public Builder endpoint(EndpointConfig endpoint) { - - this.endpoint = endpoint; - return this; - } - - public void setEndpointAndProperties(Map properties) throws ActionMgtException { - - Authentication authentication; - Authentication.Type authnType = - Authentication.Type.valueOf(properties.remove(ActionMgtConstants.AUTHN_TYPE_PROPERTY)); - switch (authnType) { - case BASIC: - authentication = new Authentication.BasicAuthBuilder( - properties.remove(Authentication.Property.USERNAME.getName()), - properties.remove(Authentication.Property.PASSWORD.getName())).build(); - break; - case BEARER: - authentication = new Authentication.BearerAuthBuilder( - properties.remove(Authentication.Property.ACCESS_TOKEN.getName())).build(); - break; - case API_KEY: - authentication = new Authentication.APIKeyAuthBuilder( - properties.remove(Authentication.Property.HEADER.getName()), - properties.remove(Authentication.Property.VALUE.getName())).build(); - break; - case NONE: - authentication = new Authentication.NoneAuthBuilder().build(); - break; - default: - throw new ActionMgtServerException("Authentication type is not defined for the Action Endpoint."); - } - - this.endpoint = new EndpointConfig.EndpointConfigBuilder() - .uri(properties.remove(ActionMgtConstants.URI_PROPERTY)) - .authentication(authentication) - .build(); - // Add remaining properties as action properties. - this.properties = properties.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - } - - public Builder properties(Map properties) { - - this.properties = properties; - return this; - } - - public Builder property(String propertyName, Object propertyValue) { - - if (this.properties == null) { - this.properties = new HashMap<>(); - } - this.properties.put(propertyName, propertyValue); - return this; - } - - public ActionDTO build() { - - return new ActionDTO(this); - } - } -} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java new file mode 100644 index 000000000000..3351ee606f1b --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.model; + +import java.util.Map; + +/** + * Action Data Transfer Object. + */ +public class ActionDTO { + + private final String id; + private final Action.ActionTypes type; + private final String name; + private final String description; + private final Action.Status status; + private final EndpointConfig endpoint; + private final Map properties; + + public ActionDTO(Builder builder) { + + this.id = builder.id; + this.type = builder.type; + this.name = builder.name; + this.description = builder.description; + this.status = builder.status; + this.endpoint = builder.endpoint; + this.properties = builder.properties; + } + + public String getId() { + + return id; + } + + public Action.ActionTypes getType() { + + return type; + } + + public String getName() { + + return name; + } + + public String getDescription() { + + return description; + } + + public Action.Status getStatus() { + + return status; + } + + public EndpointConfig getEndpoint() { + + return endpoint; + } + + public Map getProperties() { + + return properties; + } + + public Object getProperty(String propertyName) { + + if (properties == null) { + return null; + } + + return properties.get(propertyName); + } + + /** + * Builder for ActionDTO. + */ + public static class Builder { + + private final String id; + private final Action.ActionTypes type; + private final String name; + private final String description; + private final Action.Status status; + private final EndpointConfig endpoint; + private Map properties; + + public Builder(ActionDTO actionDTO) { + + this.id = actionDTO.getId(); + this.type = actionDTO.getType(); + this.name = actionDTO.getName(); + this.description = actionDTO.getDescription(); + this.status = actionDTO.getStatus(); + this.endpoint = actionDTO.getEndpoint(); + this.properties = actionDTO.getProperties(); + } + + public Builder(Action action) { + + this.id = action.getId(); + this.type = action.getType(); + this.name = action.getName(); + this.description = action.getDescription(); + this.status = action.getStatus(); + this.endpoint = action.getEndpoint(); + } + + public Builder properties(Map properties) { + + this.properties = properties; + return this; + } + + public ActionDTO build() { + + return new ActionDTO(this); + } + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java index fea88b8da1ed..c4e4d17628ad 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java @@ -18,8 +18,8 @@ package org.wso2.carbon.identity.action.management.service; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; /** * This interface defines the Action ActionConverter. @@ -38,14 +38,7 @@ public interface ActionConverter { */ default ActionDTO buildActionDTO(Action action) { - return new ActionDTO.Builder() - .id(action.getId()) - .type(action.getType()) - .name(action.getName()) - .description(action.getDescription()) - .status(action.getStatus()) - .endpoint(action.getEndpoint()) - .build(); + return new ActionDTO.Builder(action).build(); } /** * Convert ActionDTO object into Action object. diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java index 11ad9c607e16..a9ca40a75e98 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java @@ -18,12 +18,11 @@ package org.wso2.carbon.identity.action.management.service; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; -import java.util.Collections; -import java.util.Map; +import java.util.List; /** * This interface defines the Action Property Resolver. @@ -33,22 +32,28 @@ public interface ActionPropertyResolver { Action.ActionTypes getSupportedActionType(); - default Map addProperties(ActionDTO actionDTO, String tenantDomain) + default ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { - return Collections.emptyMap(); + return actionDTO; } - default Map getProperties(ActionDTO actionDTO, String tenantDomain) + default ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { - return Collections.emptyMap(); + return actionDTO; } - default Map updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, - String tenantDomain) throws ActionPropertyResolverException { + default List populateProperties(List actionDTOList, String tenantDomain) + throws ActionPropertyResolverException { + + return actionDTOList; + } + + default ActionDTO resolveUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + String tenantDomain) throws ActionPropertyResolverException { - return Collections.emptyMap(); + return updatingActionDTO; } default void deleteProperties(ActionDTO deletingActionDTO, String tenantDomain) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index 4d4437aa4d50..94a419b658e4 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -24,14 +24,15 @@ import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.service.ActionConverter; import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionValidator; @@ -403,20 +404,16 @@ private ActionDTO buildActionDTO(String actionType, String actionId, Action acti ActionConverterFactory.getActionConverter(Action.ActionTypes.valueOf(actionType)); if (actionConverter != null) { ActionDTO actionDTO = actionConverter.buildActionDTO(action); - actionDTO.setId(actionId); - actionDTO.setType(Action.ActionTypes.valueOf(actionType)); - return actionDTO; + return new ActionDTOBuilder(actionDTO) + .id(actionId) + .type(Action.ActionTypes.valueOf(actionType)) + .build(); } - return new ActionDTO.Builder() - .id(action.getId() != null ? action.getId() : actionId) - .type(action.getType() != null ? action.getType() : Action.ActionTypes.valueOf(actionType)) - .name(action.getName()) - .description(action.getDescription()) - .status(action.getStatus()) - .endpoint(action.getEndpoint()) - .properties(null) + return new ActionDTOBuilder(action) + .id(actionId) + .type(Action.ActionTypes.valueOf(actionType)) .build(); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java new file mode 100644 index 000000000000..9e852ee1aee2 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.util; + +import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Internal Builder class for ActionDTO. + */ +public class ActionDTOBuilder { + + private String id; + private Action.ActionTypes type; + private String name; + private String description; + private Action.Status status; + private EndpointConfig endpoint; + private Map properties; + + public ActionDTOBuilder() { + + } + + public ActionDTOBuilder(ActionDTO actionDTO) { + + this.id = actionDTO.getId(); + this.type = actionDTO.getType(); + this.name = actionDTO.getName(); + this.description = actionDTO.getDescription(); + this.status = actionDTO.getStatus(); + this.endpoint = actionDTO.getEndpoint(); + this.properties = actionDTO.getProperties(); + } + + public ActionDTOBuilder(Action action) { + + this.id = action.getId(); + this.type = action.getType(); + this.name = action.getName(); + this.description = action.getDescription(); + this.status = action.getStatus(); + this.endpoint = action.getEndpoint(); + } + + public ActionDTOBuilder id(String id) { + + this.id = id; + return this; + } + + public String getId() { + + return this.id; + } + + public ActionDTOBuilder type(Action.ActionTypes type) { + + this.type = type; + return this; + } + + public Action.ActionTypes getType() { + + return this.type; + } + + public ActionDTOBuilder name(String name) { + + this.name = name; + return this; + } + + public String getName() { + + return this.name; + } + + public ActionDTOBuilder description(String description) { + + this.description = description; + return this; + } + + public String getDescription() { + + return this.description; + } + + public ActionDTOBuilder status(Action.Status status) { + + this.status = status; + return this; + } + + public Action.Status getStatus() { + + return this.status; + } + + public ActionDTOBuilder endpoint(EndpointConfig endpoint) { + + this.endpoint = endpoint; + return this; + } + + public EndpointConfig getEndpoint() { + + return this.endpoint; + } + + public ActionDTOBuilder setEndpointAndProperties(Map properties) throws + ActionMgtException { + + Authentication authentication; + Authentication.Type authnType = + Authentication.Type.valueOf(properties.remove(ActionMgtConstants.AUTHN_TYPE_PROPERTY)); + switch (authnType) { + case BASIC: + authentication = new Authentication.BasicAuthBuilder( + properties.remove(Authentication.Property.USERNAME.getName()), + properties.remove(Authentication.Property.PASSWORD.getName())).build(); + break; + case BEARER: + authentication = new Authentication.BearerAuthBuilder( + properties.remove(Authentication.Property.ACCESS_TOKEN.getName())).build(); + break; + case API_KEY: + authentication = new Authentication.APIKeyAuthBuilder( + properties.remove(Authentication.Property.HEADER.getName()), + properties.remove(Authentication.Property.VALUE.getName())).build(); + break; + case NONE: + authentication = new Authentication.NoneAuthBuilder().build(); + break; + default: + throw new ActionMgtServerException("Authentication type is not defined for the Action Endpoint."); + } + + this.endpoint = new EndpointConfig.EndpointConfigBuilder() + .uri(properties.remove(ActionMgtConstants.URI_PROPERTY)) + .authentication(authentication) + .build(); + // Add remaining properties as action properties. + this.properties = properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return this; + } + + public ActionDTOBuilder properties(Map properties) { + + this.properties = properties; + return this; + } + + public Map getProperties() { + + return this.properties; + } + + public ActionDTOBuilder property(String propertyName, Object propertyValue) { + + if (this.properties == null) { + this.properties = new HashMap<>(); + } + this.properties.put(propertyName, propertyValue); + return this; + } + + public ActionDTO build() { + + Action action = new Action.ActionResponseBuilder() + .id(this.id) + .type(this.type) + .name(this.name) + .description(this.description) + .status(this.status) + .endpoint(this.endpoint) + .build(); + + return new ActionDTO.Builder(action).properties(this.properties).build(); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java index 782de796d2a2..fd881bdcedaf 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java @@ -22,7 +22,7 @@ import org.json.JSONObject; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index 7537d27c3b53..a144da1b2fa5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -18,6 +18,7 @@ package org.wso2.carbon.identity.action.management.dao; +import org.apache.commons.lang.StringUtils; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; @@ -30,7 +31,6 @@ import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; @@ -39,9 +39,11 @@ import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverServerException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.certificate.management.model.Certificate; import org.wso2.carbon.identity.common.testng.WithCarbonHome; @@ -52,21 +54,15 @@ import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; -import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; @@ -83,7 +79,6 @@ import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI_UPDATED; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; -import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE_UPDATED; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE; import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE_UPDATED; @@ -99,7 +94,8 @@ public class ActionManagementDAOFacadeTest { @Mock - private ActionPropertyResolver actionPropertyResolver; + private ActionPropertyResolver mockedActionPropertyResolver; + private TestActionPropertyResolver testActionPropertyResolver; private MockedStatic actionPropertyResolverFactory; private MockedStatic identityTenantUtil; @@ -111,6 +107,20 @@ public class ActionManagementDAOFacadeTest { public void setUpClass() { daoFacade = new ActionManagementDAOFacade(new ActionManagementDAOImpl()); + creatingActionDTO = new ActionDTOBuilder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)) + .build()) + .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE) + .property(CERTIFICATE_PROPERTY_NAME, + new Certificate.Builder().certificateContent(TEST_CERTIFICATE).build()) + .build(); + testActionPropertyResolver = new TestActionPropertyResolver(); } @BeforeMethod @@ -127,28 +137,12 @@ public void setUp() throws SecretManagementException { MockitoAnnotations.openMocks(this); actionPropertyResolverFactory = mockStatic(ActionPropertyResolverFactory.class); - actionPropertyResolverFactory.when(() -> - ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) - .thenReturn(actionPropertyResolver); - - creatingActionDTO = new ActionDTO.Builder() - .id(PRE_UPDATE_PASSWORD_ACTION_ID) - .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) - .name(TEST_ACTION_NAME) - .description(TEST_ACTION_DESCRIPTION) - .endpoint(new EndpointConfig.EndpointConfigBuilder() - .uri(TEST_ACTION_URI) - .authentication(TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)) - .build()) - .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE) - .property(CERTIFICATE_PROPERTY_NAME, - new Certificate.Builder().certificateContent(TEST_CERTIFICATE).build()) - .build(); } @AfterMethod public void tearDown() { + mockedActionPropertyResolver = null; identityTenantUtil.close(); actionPropertyResolverFactory.close(); } @@ -156,8 +150,9 @@ public void tearDown() { @Test(priority = 1) public void testAddActionWithActionPropertyResolverClientException() throws ActionPropertyResolverException { - doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(actionPropertyResolver) - .addProperties(any(), any()); + mockActionPropertyResolver(mockedActionPropertyResolver); + doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(mockedActionPropertyResolver) + .resolveAddingProperties(any(), any()); try { daoFacade.addAction(creatingActionDTO, TENANT_ID); @@ -173,8 +168,9 @@ public void testAddActionWithActionPropertyResolverClientException() throws Acti @Test(priority = 2) public void testAddActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { + mockActionPropertyResolver(mockedActionPropertyResolver); doThrow(new ActionPropertyResolverServerException("Error adding Certificate.", new Throwable())) - .when(actionPropertyResolver).addProperties(any(), any()); + .when(mockedActionPropertyResolver).resolveAddingProperties(any(), any()); try { daoFacade.addAction(creatingActionDTO, TENANT_ID); @@ -194,24 +190,13 @@ public void testAddActionWithActionPropertyResolverServerException() throws Acti @Test(priority = 3) public void testAddAction() throws ActionMgtException, ActionPropertyResolverException { - Map properties = new HashMap<>(); - properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); - properties.put(CERTIFICATE_PROPERTY_NAME, TestUtil.CERTIFICATE_ID); - doReturn(properties).when(actionPropertyResolver).addProperties(any(), any()); - + mockActionPropertyResolver(testActionPropertyResolver); try { daoFacade.addAction(creatingActionDTO, TENANT_ID); } catch (Exception e) { Assert.fail(); } - Map retrievedProperties = new HashMap<>(); - retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); - retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() - .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) - .certificateContent(TEST_CERTIFICATE).build()); - doReturn(retrievedProperties).when(actionPropertyResolver).getProperties(any(), any()); - createdActionDTO = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); @@ -245,13 +230,7 @@ public void testAddAction() throws ActionMgtException, ActionPropertyResolverExc @Test(priority = 4) public void testGetActionsByType() throws ActionMgtException, ActionPropertyResolverException { - Map retrievedProperties = new HashMap<>(); - retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); - retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() - .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) - .certificateContent(TEST_CERTIFICATE).build()); - doReturn(retrievedProperties).when(actionPropertyResolver).getProperties(any(), any()); - + mockActionPropertyResolver(testActionPropertyResolver); List actionDTOs = daoFacade.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); ActionDTO result = actionDTOs.get(0); Assert.assertEquals(result.getId(), createdActionDTO.getId()); @@ -285,8 +264,9 @@ public void testGetActionsByType() throws ActionMgtException, ActionPropertyReso @Test(priority = 5) public void testUpdateActionPropertyResolverClientException() throws ActionPropertyResolverException { - doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(actionPropertyResolver) - .updateProperties(any(), any(), any()); + mockActionPropertyResolver(mockedActionPropertyResolver); + doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(mockedActionPropertyResolver) + .resolveUpdatingProperties(any(), any(), any()); try { daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); @@ -302,8 +282,10 @@ public void testUpdateActionPropertyResolverClientException() throws ActionPrope @Test(priority = 6) public void testUpdateActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { - doThrow(new ActionPropertyResolverServerException("Error updating Certificate.")).when(actionPropertyResolver) - .updateProperties(any(), any(), any()); + mockActionPropertyResolver(mockedActionPropertyResolver); + doThrow(new ActionPropertyResolverServerException("Error updating Certificate.")).when( + mockedActionPropertyResolver) + .resolveUpdatingProperties(any(), any(), any()); try { daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); @@ -323,7 +305,9 @@ public void testUpdateActionWithActionPropertyResolverServerException() throws A @Test(priority = 7, dependsOnMethods = "testAddAction") public void testUpdateCompleteAction() throws ActionMgtException, ActionPropertyResolverException { - ActionDTO updatingAction = new ActionDTO.Builder() + mockActionPropertyResolver(testActionPropertyResolver); + // Update action with certificate property deletion. + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) .name(TEST_ACTION_NAME_UPDATED) @@ -334,12 +318,8 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty .build()) .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED) .property(CERTIFICATE_PROPERTY_NAME, - new Certificate.Builder().certificateContent(TEST_CERTIFICATE_UPDATED).build()) + new Certificate.Builder().certificateContent(StringUtils.EMPTY).build()) .build(); - Map properties = new HashMap<>(); - properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED); - properties.put(CERTIFICATE_PROPERTY_NAME, CERTIFICATE_ID); - doReturn(properties).when(actionPropertyResolver).updateProperties(any(), any(), anyString()); try { daoFacade.updateAction(updatingAction, createdActionDTO, TENANT_ID); @@ -347,13 +327,6 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty Assert.fail(); } - Map retrievedProperties = new HashMap<>(); - retrievedProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED); - retrievedProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() - .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) - .certificateContent(TEST_CERTIFICATE_UPDATED).build()); - doReturn(retrievedProperties).when(actionPropertyResolver).getProperties(any(), any()); - ActionDTO result = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, updatingAction.getId(), TENANT_ID); Assert.assertEquals(result.getId(), createdActionDTO.getId()); Assert.assertEquals(result.getType(), createdActionDTO.getType()); @@ -371,14 +344,14 @@ public void testUpdateCompleteAction() throws ActionMgtException, ActionProperty TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); - Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); + // Check whether the certificate is removed. + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size() - 1); Assert.assertTrue(updatingAction.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); Assert.assertTrue(updatingAction.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); Assert.assertEquals(result.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), updatingAction.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); - Assert.assertEquals(((Certificate) result.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent(), - TEST_CERTIFICATE_UPDATED); + Assert.assertNull(result.getProperty(CERTIFICATE_PROPERTY_NAME)); createdActionDTO = result; } @@ -410,8 +383,7 @@ public void testGetActionsCountPerType() throws ActionMgtException { @Test(priority = 11) public void testDeleteAction() throws ActionMgtException, ActionPropertyResolverException { - doNothing().when(actionPropertyResolver).deleteProperties(any(), anyString()); - + mockActionPropertyResolver(testActionPropertyResolver); try { daoFacade.deleteAction(createdActionDTO, TENANT_ID); } catch (Exception e) { @@ -421,4 +393,11 @@ public void testDeleteAction() throws ActionMgtException, ActionPropertyResolver TENANT_ID)); Assert.assertEquals(daoFacade.getActionsCountPerType(TENANT_ID), Collections.emptyMap()); } + + private void mockActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + + actionPropertyResolverFactory.when( + () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionPropertyResolver); + } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index 5f57f1087f73..ab716801d95b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -22,11 +22,12 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; @@ -44,6 +45,8 @@ /** * This class is a test suite for the ActionManagementDAOImpl class. * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOImpl class. + * This test class will utilize {@link TestActionPropertyResolver} class as the test implementation for + * ActionPropertyResolver interface. */ @WithH2Database(files = {"dbscripts/h2.sql"}) @WithCarbonHome @@ -61,7 +64,7 @@ public void setUpClass() { @Test(priority = 1) public void testAddAction() throws ActionMgtException { - ActionDTO creatingActionDTO = new ActionDTO.Builder() + ActionDTO creatingActionDTO = new ActionDTOBuilder() .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .name(TestUtil.TEST_ACTION_NAME) @@ -107,10 +110,10 @@ public void testAddAction() throws ActionMgtException { } @Test(priority = 2, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Error while adding Action Basic information.") + expectedExceptionsMessageRegExp = "Error while adding Action Basic information in the system.") public void testAddActionWithoutName() throws ActionMgtException { - ActionDTO creatingActionDTO = new ActionDTO.Builder() + ActionDTO creatingActionDTO = new ActionDTOBuilder() .id(String.valueOf(UUID.randomUUID())) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .name(null) @@ -171,7 +174,7 @@ public void testDeleteAction() throws ActionMgtException { @Test(priority = 5) public void testAddActionWithoutDescription() throws ActionMgtException { - ActionDTO creatingActionDTO = new ActionDTO.Builder() + ActionDTO creatingActionDTO = new ActionDTOBuilder() .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .name(TestUtil.TEST_ACTION_NAME) @@ -217,7 +220,7 @@ public void testAddActionWithoutDescription() throws ActionMgtException { @Test(priority = 7, dependsOnMethods = "testAddActionWithoutDescription") public void testUpdateCompleteAction() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .name(TestUtil.TEST_ACTION_NAME_UPDATED) @@ -262,7 +265,7 @@ public void testUpdateCompleteAction() throws ActionMgtException { @Test(priority = 8) public void testUpdateActionBasicInfo() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .name(TestUtil.TEST_ACTION_NAME) @@ -301,7 +304,7 @@ public void testUpdateActionBasicInfo() throws ActionMgtException { @Test(priority = 9) public void testUpdateActionEndpoint() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .endpoint(new EndpointConfig.EndpointConfigBuilder() @@ -345,7 +348,7 @@ public void testUpdateActionEndpoint() throws ActionMgtException { @Test(priority = 10) public void testUpdateActionEndpointUri() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .endpoint(new EndpointConfig.EndpointConfigBuilder() @@ -387,7 +390,7 @@ public void testUpdateActionEndpointUri() throws ActionMgtException { @Test(priority = 11) public void testUpdateActionEndpointAuthenticationWithSameAuthType() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .endpoint(new EndpointConfig.EndpointConfigBuilder() @@ -430,7 +433,7 @@ public void testUpdateActionEndpointAuthenticationWithSameAuthType() throws Acti @Test(priority = 12) public void testUpdateActionEndpointAuthenticationWithDifferentAuthType() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .endpoint(new EndpointConfig.EndpointConfigBuilder() @@ -468,7 +471,7 @@ public void testUpdateActionEndpointAuthenticationWithDifferentAuthType() throws @Test(priority = 13) public void testUpdateActionProperties() throws ActionMgtException { - ActionDTO updatingAction = new ActionDTO.Builder() + ActionDTO updatingAction = new ActionDTOBuilder() .id(createdActionDTO.getId()) .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) @@ -523,7 +526,7 @@ public void testActivateAction() throws ActionMgtException { @Test(priority = 16) public void testGetActionsCountPerType() throws ActionMgtException { - ActionDTO creatingPreUpdatePasswordActionDTO = new ActionDTO.Builder() + ActionDTO creatingPreUpdatePasswordActionDTO = new ActionDTOBuilder() .id(PRE_UPDATE_PASSWORD_ACTION_ID) .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) .name(TestUtil.TEST_ACTION_NAME) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java new file mode 100644 index 000000000000..d5fb57d5f07f --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.identity.action.management.dao; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.util.TestUtil; +import org.wso2.carbon.identity.certificate.management.model.Certificate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; + +/** + * Test implementation of ActionPropertyResolver. + */ +public class TestActionPropertyResolver implements ActionPropertyResolver { + + @Override + public Action.ActionTypes getSupportedActionType() { + + return Action.ActionTypes.PRE_UPDATE_PASSWORD; + } + + @Override + public ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDomain) { + + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + properties.put(CERTIFICATE_PROPERTY_NAME, TestUtil.CERTIFICATE_ID); + + return new ActionDTO.Builder(actionDTO).properties(properties).build(); + } + + @Override + public ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) { + + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, + actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + if (actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME) != null) { + properties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id((String) actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)) + .name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE) + .build()); + } + + return new ActionDTO.Builder(actionDTO).properties(properties).build(); + } + + @Override + public List populateProperties(List actionDTOList, String tenantDomain) { + + List resolvedActionDTOList = new ArrayList<>(); + for (ActionDTO actionDTO : actionDTOList) { + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, + actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + properties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id((String) actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)) + .name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE) + .build()); + + resolvedActionDTOList.add(new ActionDTO.Builder(actionDTO).properties(properties).build()); + } + + return resolvedActionDTOList; + } + + @Override + public ActionDTO resolveUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + String tenantDomain) { + + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, + updatingActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + + return new ActionDTO.Builder(updatingActionDTO).properties(properties).build(); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java index 83300fc2a60b..651af80185ac 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java @@ -27,8 +27,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.action.management.dao.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; @@ -103,7 +103,7 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) .certificateContent(TEST_CERTIFICATE).build()); - actionDTO = new ActionDTO.Builder() + actionDTO = new ActionDTOBuilder() .id(PRE_UPDATE_PASSWORD_ACTION_ID) .name(TEST_ACTION_NAME) .description(TEST_ACTION_DESCRIPTION) diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql index a0b0af42fb59..5e8b74e153c4 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql @@ -1489,15 +1489,6 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); --- XACML -- -CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_POLICY_EDITOR_DATA_FK ON IDN_XACML_POLICY_EDITOR_DATA (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_POLICY_REF ON IDN_XACML_POLICY_REFERENCE (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_POLICY_SET_REF ON IDN_XACML_POLICY_SET_REFERENCE (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_SUBSCRIBER_PROPERTY ON IDN_XACML_SUBSCRIBER_PROPERTY (SUBSCRIBER_ID, TENANT_ID); -CREATE INDEX IDX_XACML_SUBSCRIBER_STATUS ON IDN_XACML_SUBSCRIBER_STATUS (SUBSCRIBER_ID, TENANT_ID); -CREATE INDEX IDX_XACML_POLICY_STATUS ON IDN_XACML_POLICY_STATUS (POLICY_ID, POLICY_VERSION, TENANT_ID); - -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); CREATE INDEX IDX_IDN_CERTIFICATE_UUID_TID ON IDN_CERTIFICATE (UUID, TENANT_ID); From dab9dd75643167cc04aa5d35aec2f044d59a58d4 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Fri, 29 Nov 2024 17:18:27 +0530 Subject: [PATCH 25/34] Minor fix --- .../constant/ActionMgtSQLConstants.java | 14 ++++------ .../dao/impl/ActionManagementDAOImpl.java | 28 +++++++++---------- .../dao/ActionManagementDAOFacadeTest.java | 8 +++--- 3 files changed, 24 insertions(+), 26 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java index 38f97e330a1a..8f6ae2c77200 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java @@ -38,9 +38,9 @@ public static class Column { public static final String ACTION_DESCRIPTION = "DESCRIPTION"; public static final String ACTION_STATUS = "STATUS"; public static final String ACTION_COUNT = "COUNT"; - public static final String ACTION_ENDPOINT_UUID = "ACTION_UUID"; - public static final String ACTION_ENDPOINT_PROPERTY_NAME = "PROPERTY_NAME"; - public static final String ACTION_ENDPOINT_PROPERTY_VALUE = "PROPERTY_VALUE"; + public static final String ACTION_PROPERTIES_UUID = "ACTION_UUID"; + public static final String ACTION_PROPERTIES_PROPERTY_NAME = "PROPERTY_NAME"; + public static final String ACTION_PROPERTIES_PROPERTY_VALUE = "PROPERTY_VALUE"; public static final String TENANT_ID = "TENANT_ID"; private Column() { @@ -55,19 +55,17 @@ public static class Query { public static final String ADD_ACTION_TO_ACTION_TYPE = "INSERT INTO IDN_ACTION (UUID, TYPE, NAME, " + "DESCRIPTION, STATUS, TENANT_ID) VALUES (:UUID;, :TYPE;, :NAME;, :DESCRIPTION;, :STATUS;, :TENANT_ID;)"; - public static final String ADD_ACTION_ENDPOINT_PROPERTIES = "INSERT INTO IDN_ACTION_PROPERTIES (ACTION_UUID, " + + public static final String ADD_ACTION_PROPERTIES = "INSERT INTO IDN_ACTION_PROPERTIES (ACTION_UUID, " + "PROPERTY_NAME, PROPERTY_VALUE, TENANT_ID) VALUES (:ACTION_UUID;, :PROPERTY_NAME;, :PROPERTY_VALUE;, " + ":TENANT_ID;)"; public static final String GET_ACTION_BASIC_INFO_BY_ID = "SELECT TYPE, NAME, DESCRIPTION, STATUS FROM " + "IDN_ACTION WHERE TYPE = :TYPE; AND UUID = :UUID; AND TENANT_ID = :TENANT_ID;"; - public static final String GET_ACTION_ENDPOINT_INFO_BY_ID = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM " + + public static final String GET_ACTION_PROPERTIES_INFO_BY_ID = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM " + "IDN_ACTION_PROPERTIES WHERE ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE = "SELECT UUID, TYPE, NAME, DESCRIPTION," + " STATUS FROM IDN_ACTION WHERE TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String UPDATE_ACTION_BASIC_INFO = "UPDATE IDN_ACTION SET NAME = :NAME;, DESCRIPTION = " + ":DESCRIPTION; WHERE UUID = :UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; - public static final String DELETE_ACTION_ENDPOINT_PROPERTIES = "DELETE FROM IDN_ACTION_PROPERTIES WHERE " + - "ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String DELETE_ACTION_PROPERTY = "DELETE FROM IDN_ACTION_PROPERTIES WHERE " + "PROPERTY_NAME = :PROPERTY_NAME; AND ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String DELETE_ACTION = "DELETE FROM IDN_ACTION WHERE UUID = :UUID; AND TYPE = :TYPE;" + @@ -76,7 +74,7 @@ public static class Query { ":UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_COUNT_PER_ACTION_TYPE = "SELECT TYPE, COUNT(UUID) AS COUNT" + " FROM IDN_ACTION WHERE TENANT_ID = :TENANT_ID; GROUP BY TYPE"; - public static final String UPDATE_ACTION_PROPERTIES = "UPDATE IDN_ACTION_PROPERTIES SET " + + public static final String UPDATE_ACTION_PROPERTY = "UPDATE IDN_ACTION_PROPERTIES SET " + "PROPERTY_VALUE = :PROPERTY_VALUE; WHERE ACTION_UUID = :ACTION_UUID; AND " + "TENANT_ID = :TENANT_ID; AND PROPERTY_NAME = :PROPERTY_NAME;"; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 42cb23c9dee4..30ca85f99528 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -405,14 +405,14 @@ private void addActionPropertiesToDB(String actionId, Map action NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT_PROPERTIES, + template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_PROPERTIES, statement -> { for (Map.Entry property : actionProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE, property.getValue()); statement.addBatch(); } @@ -434,15 +434,15 @@ private Map getActionPropertiesFromDB(String actionId, Integer t NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); Map actionEndpointProperties = new HashMap<>(); try { - jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_ENDPOINT_INFO_BY_ID, + jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_PROPERTIES_INFO_BY_ID, (resultSet, rowNumber) -> { actionEndpointProperties.put( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME), - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE)); + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME), + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE)); return null; }, statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); @@ -465,14 +465,14 @@ private void updateActionPropertiesInDB(String actionId, Map upd NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); jdbcTemplate.withTransaction(template -> - template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_PROPERTIES, + template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_PROPERTY, statement -> { for (Map.Entry property : updatingProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE, property.getValue()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); statement.addBatch(); } @@ -487,9 +487,9 @@ private void deleteActionPropertiesInDB(String actionId, List deletingPr template.executeBatchInsert(ActionMgtSQLConstants.Query.DELETE_ACTION_PROPERTY, statement -> { for (String property : deletingProperties) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, property); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); statement.addBatch(); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index a144da1b2fa5..d59c24fbdeb8 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -188,7 +188,7 @@ public void testAddActionWithActionPropertyResolverServerException() throws Acti } @Test(priority = 3) - public void testAddAction() throws ActionMgtException, ActionPropertyResolverException { + public void testAddAction() throws ActionMgtException { mockActionPropertyResolver(testActionPropertyResolver); try { @@ -228,7 +228,7 @@ public void testAddAction() throws ActionMgtException, ActionPropertyResolverExc } @Test(priority = 4) - public void testGetActionsByType() throws ActionMgtException, ActionPropertyResolverException { + public void testGetActionsByType() throws ActionMgtException { mockActionPropertyResolver(testActionPropertyResolver); List actionDTOs = daoFacade.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); @@ -303,7 +303,7 @@ public void testUpdateActionWithActionPropertyResolverServerException() throws A } @Test(priority = 7, dependsOnMethods = "testAddAction") - public void testUpdateCompleteAction() throws ActionMgtException, ActionPropertyResolverException { + public void testUpdateCompleteAction() throws ActionMgtException { mockActionPropertyResolver(testActionPropertyResolver); // Update action with certificate property deletion. @@ -381,7 +381,7 @@ public void testGetActionsCountPerType() throws ActionMgtException { } @Test(priority = 11) - public void testDeleteAction() throws ActionMgtException, ActionPropertyResolverException { + public void testDeleteAction() throws ActionMgtException { mockActionPropertyResolver(testActionPropertyResolver); try { From 9374c399c262cf1450e779ffc21738825f16c7f6 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 2 Dec 2024 01:19:42 +0530 Subject: [PATCH 26/34] Add method descriptions --- .../dao/impl/ActionManagementDAOFacade.java | 84 ++++++++++++++++++- .../dao/impl/ActionManagementDAOImpl.java | 84 ++++++++++++++++++- .../service/ActionPropertyResolver.java | 55 ++++++++++++ 3 files changed, 216 insertions(+), 7 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index acfc43ac5785..41bd8e9be269 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -202,6 +202,12 @@ public Map getActionsCountPerType(Integer tenantId) throws Acti } } + /** + * Encrypt and store the authentication secrets of the Action Endpoint Authentication. + * + * @param actionDTOBuilder ActionDTOBuilder object. + * @throws ActionMgtException If an error occurs while encrypting the authentication secrets. + */ private void encryptAddingAuthSecrets(ActionDTOBuilder actionDTOBuilder) throws ActionMgtException { try { @@ -214,6 +220,15 @@ private void encryptAddingAuthSecrets(ActionDTOBuilder actionDTOBuilder) throws } } + /** + * Encrypt and update the authentication secrets of the Action Endpoint Authentication. + * If the authentication type is changed, delete the existing authentication secrets and add new secrets. + * If the authentication properties are updated, update the existing authentication secrets. + * + * @param updatingActionDTOBuilder ActionDTOBuilder object. + * @param existingActionDTO Existing ActionDTO object. + * @throws ActionMgtException If an error occurs while encrypting the authentication secrets. + */ private void encryptUpdatingAuthSecrets(ActionDTOBuilder updatingActionDTOBuilder, ActionDTO existingActionDTO) throws ActionMgtException { @@ -239,7 +254,13 @@ private void encryptUpdatingAuthSecrets(ActionDTOBuilder updatingActionDTOBuilde } } - private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws ActionMgtServerException { + /** + * Delete the authentication secrets of the Action Endpoint Authentication. + * + * @param deletingActionDTO ActionDTO object. + * @throws ActionMgtException If an error occurs while deleting the authentication secrets. + */ + private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws ActionMgtException { try { actionSecretProcessor.deleteAssociatedSecrets(deletingActionDTO.getEndpoint().getAuthentication(), @@ -249,6 +270,13 @@ private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws Act } } + /** + * Add the encrypted authentication secrets and replace the input authentication properties in the ActionDTOBuilder + * object. + * + * @param actionDTOBuilder ActionDTOBuilder object. + * @param encryptedProperties List of encrypted AuthProperty objects. + */ private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, List encryptedProperties) { @@ -264,6 +292,14 @@ private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, .build()); } + /** + * Get the ActionDTO with resolved adding properties that needs to be added in the Action Management Service. + * + * @param actionDTO ActionDTO object. + * @param tenantId Tenant ID. + * @return ActionDTO object with resolved adding properties. + * @throws ActionPropertyResolverException If an error occurs while resolving the adding properties. + */ private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { @@ -276,19 +312,37 @@ private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, return actionPropertyResolver.resolveAddingProperties(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } - private List getActionDTOsWithPopulatedProperties(String actionType, List actionDTOS, + /** + * Get the ActionDTO list with populated properties according to the references stored in the Action Management + * Service. + * + * @param actionType Action type. + * @param actionDTOs List of ActionDTO objects. + * @param tenantId Tenant ID. + * @return List of ActionDTO objects with populated properties. + * @throws ActionPropertyResolverException If an error occurs while populating the properties. + */ + private List getActionDTOsWithPopulatedProperties(String actionType, List actionDTOs, Integer tenantId) throws ActionPropertyResolverException { ActionPropertyResolver actionPropertyResolver = ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); if (actionPropertyResolver == null) { - return actionDTOS; + return actionDTOs; } - return actionPropertyResolver.populateProperties(actionDTOS, IdentityTenantUtil.getTenantDomain(tenantId)); + return actionPropertyResolver.populateProperties(actionDTOs, IdentityTenantUtil.getTenantDomain(tenantId)); } + /** + * Get the ActionDTO with populated properties according to the references stored in the Action Management Service. + * + * @param actionDTO ActionDTO object. + * @param tenantId Tenant ID. + * @return ActionDTO object with populated properties. + * @throws ActionPropertyResolverException If an error occurs while populating the properties. + */ private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { @@ -301,6 +355,15 @@ private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integ return actionPropertyResolver.populateProperties(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } + /** + * Get the ActionDTO with resolved updating properties that needs to be updated in the Action Management Service. + * + * @param updatingActionDTO Updating ActionDTO object. + * @param existingActionDTO Existing ActionDTO object. + * @param tenantId Tenant ID. + * @return ActionDTO object with resolved updating properties. + * @throws ActionPropertyResolverException If an error occurs while resolving the updating properties. + */ private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) throws ActionPropertyResolverException { @@ -315,6 +378,13 @@ private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingA IdentityTenantUtil.getTenantDomain(tenantId)); } + /** + * Delete the properties that are deleted in the Action Management Service. + * + * @param deletingActionDTO Deleting ActionDTO object. + * @param tenantId Tenant ID. + * @throws ActionPropertyResolverException If an error occurs while deleting the properties. + */ private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) throws ActionPropertyResolverException { @@ -327,6 +397,12 @@ private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) actionPropertyResolver.deleteProperties(deletingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } + /** + * Handle the ActionPropertyResolverClientException and throw the relevant ActionMgtClientException. + * + * @param throwable Throwable object. + * @throws ActionMgtClientException If an error occurs while handling the ActionPropertyResolverClientException. + */ private static void handleActionPropertyResolverClientException(Throwable throwable) throws ActionMgtClientException { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 30ca85f99528..a4a0816aa217 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -176,6 +176,13 @@ public Map getActionsCountPerType(Integer tenantId) throws Acti } } + /** + * Add Basic Information of an {@link ActionDTO} to the Database. + * + * @param actionDTO ActionDTO object with basic information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while adding action basic information in the database. + */ private void addBasicInfo(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); @@ -207,7 +214,7 @@ private void addBasicInfo(ActionDTO actionDTO, Integer tenantId) throws ActionMg * @param updatingActionDTO Information to be updated. * @param existingActionDTO Existing Action information. * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action basic information. + * @throws ActionMgtException If an error occurs while updating the Action basic information in the database. */ private void updateBasicInfo(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) throws ActionMgtException { @@ -265,6 +272,13 @@ private ActionDTOBuilder getBasicInfo(String actionType, String actionId, Intege } } + /** + * Add Action Endpoint Configurations. + * + * @param actionDTO ActionDTO object with endpoint information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while adding action endpoint. + */ private void addEndpoint(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { EndpointConfig endpoint = actionDTO.getEndpoint(); @@ -281,8 +295,16 @@ private void addEndpoint(ActionDTO actionDTO, Integer tenantId) throws ActionMgt } } + /** + * Update Action Endpoint Configurations. + * + * @param updatingActionDTO Updating ActionDTO object with endpoint information. + * @param existingActionDTO Existing ActionDTO object with endpoint information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating action endpoint. + */ private void updateEndpoint(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) - throws ActionMgtServerException { + throws ActionMgtException { EndpointConfig updatingEndpoint = updatingActionDTO.getEndpoint(); if (updatingEndpoint == null) { @@ -302,6 +324,15 @@ private void updateEndpoint(ActionDTO updatingActionDTO, ActionDTO existingActio } } + /** + * Update Action Endpoint Authentication. + * + * @param actionId UUID of the created Action. + * @param updatingAuthentication Authentication object with updated configurations. + * @param existingAuthentication Existing Authentication object. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating action endpoint authentication. + */ private void updateEndpointAuthentication(String actionId, Authentication updatingAuthentication, Authentication existingAuthentication, Integer tenantId) throws ActionMgtException { @@ -324,6 +355,14 @@ private void updateEndpointAuthentication(String actionId, Authentication updati } } + /** + * Add Authentication Configurations of a new Authentication type. + * + * @param actionId UUID of the created Action. + * @param updatingAuthentication Authentication object with updated configurations. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while adding action authentication. + */ private void addAuthentication(String actionId, Authentication updatingAuthentication, Integer tenantId) throws TransactionException { @@ -334,6 +373,14 @@ private void addAuthentication(String actionId, Authentication updatingAuthentic addActionPropertiesToDB(actionId, authenticationProperties, tenantId); } + /** + * Delete Authentication Configurations of an existing Authentication type. + * + * @param actionId UUID of the created Action. + * @param existingAuthentication Existing Authentication object. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while deleting action authentication. + */ private void deleteAuthentication(String actionId, Authentication existingAuthentication, Integer tenantId) throws TransactionException { @@ -345,6 +392,14 @@ private void deleteAuthentication(String actionId, Authentication existingAuthen deleteActionPropertiesInDB(actionId, deletingProperties, tenantId); } + /** + * Update Authentication Configurations of an existing Authentication type. + * + * @param actionId UUID of the created Action. + * @param updatingAuthentication Authentication object with updated configurations. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while updating action authentication. + */ private void updateAuthentication(String actionId, Authentication updatingAuthentication, Integer tenantId) throws TransactionException { @@ -355,6 +410,13 @@ private void updateAuthentication(String actionId, Authentication updatingAuthen updateActionPropertiesInDB(actionId, nonSecretAuthenticationProperties, tenantId); } + /** + * Add Action properties. + * + * @param actionDTO ActionDTO object with properties. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while adding action properties. + */ private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { Map propertiesMap = actionDTO.getProperties(); @@ -371,6 +433,14 @@ private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionM } } + /** + * Update Action properties. + * + * @param updatingActionDTO Updating ActionDTO object with properties. + * @param existingActionDTO Existing ActionDTO object with properties. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating action properties. + */ private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) throws ActionMgtException { @@ -458,7 +528,7 @@ private Map getActionPropertiesFromDB(String actionId, Integer t * @param actionId UUID of the created Action. * @param updatingProperties Action properties to be updated. * @param tenantId Tenant ID. - * @throws TransactionException If an error occurs while updating the Action properties. + * @throws TransactionException If an error occurs while updating the Action properties in the database. */ private void updateActionPropertiesInDB(String actionId, Map updatingProperties, Integer tenantId) throws TransactionException { @@ -479,6 +549,14 @@ private void updateActionPropertiesInDB(String actionId, Map upd }, null)); } + /** + * Delete the given properties of an {@link ActionDTO} by given Action ID. + * + * @param actionId UUID of the created Action. + * @param deletingProperties Action properties to be deleted. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while deleting the Action properties in the database. + */ private void deleteActionPropertiesInDB(String actionId, List deletingProperties, Integer tenantId) throws TransactionException { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java index a9ca40a75e98..2a64ca7f64f7 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java @@ -32,30 +32,85 @@ public interface ActionPropertyResolver { Action.ActionTypes getSupportedActionType(); + /** + * Resolve the properties that need to be added in the Action Management Service. + * This method is responsible for performing necessary CRUD operations for the properties that need to be added + * using other external services. + * The Action Management Service ensures that only the properties returned by this method are stored. + * + * @param actionDTO ActionDTO object. + * @param tenantDomain Tenant domain. + * @return ActionDTO object with resolved properties. + * @throws ActionPropertyResolverException If an error occurs while resolving the properties. + */ default ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { return actionDTO; } + /** + * Populate the properties according to the references stored in the Action Management Service. + * This method is responsible for populating the properties that need to be retrieved using other external services. + * The Action Management Service ensures that only the properties populated by this method are included in the + * returned ActionDTO object. + * + * @param actionDTO ActionDTO object with properties references. + * @param tenantDomain Tenant domain. + * @return ActionDTO object with populated properties. + * @throws ActionPropertyResolverException If an error occurs while populating the properties. + */ default ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { return actionDTO; } + /** + * Populate the properties of the given ActionDTO list according to the references stored in the Action Management + * Service. + * This method is responsible for populating the properties that need to be retrieved using other external services. + * The Action Management Service ensures that only the properties populated by this method are included in the + * returned ActionDTO object list. + * + * @param actionDTOList List of ActionDTO objects with properties references. + * @param tenantDomain Tenant domain. + * @return List of ActionDTO objects with populated properties. + * @throws ActionPropertyResolverException If an error occurs while populating the properties. + */ default List populateProperties(List actionDTOList, String tenantDomain) throws ActionPropertyResolverException { return actionDTOList; } + /** + * Resolve the properties that need to be updated in the Action Management Service. + * This method is responsible for performing necessary CRUD operations for the properties that need to be updated + * using other external services. + * The Action Management Service ensures that only the properties returned by this method are updated. + * + * @param updatingActionDTO ActionDTO object with updated properties. + * @param existingActionDTO ActionDTO object with existing properties. + * @param tenantDomain Tenant domain. + * @return ActionDTO object with resolved properties. + * @throws ActionPropertyResolverException If an error occurs while resolving the properties. + */ default ActionDTO resolveUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, String tenantDomain) throws ActionPropertyResolverException { return updatingActionDTO; } + /** + * Delete the properties that need to be deleted in the Action Management Service. + * This method is responsible for performing necessary CRUD operations for the properties that need to be deleted + * using other external services. + * + * @param deletingActionDTO ActionDTO object with properties to be deleted. + * @param tenantDomain Tenant domain. + * @throws ActionPropertyResolverException If an error occurs while deleting the properties. + */ default void deleteProperties(ActionDTO deletingActionDTO, String tenantDomain) throws ActionPropertyResolverException { } From 2d1289a369498b88e58048181ecc730cf3265997 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 2 Dec 2024 15:49:16 +0530 Subject: [PATCH 27/34] Address comments --- ...ava => ActionDTOModelResolverFactory.java} | 28 +++++----- .../dao/impl/ActionManagementDAOFacade.java | 50 +++++++++-------- ...ActionPropertyResolverClientException.java | 4 +- .../ActionPropertyResolverException.java | 16 +++++- ...ActionPropertyResolverServerException.java | 4 +- .../internal/ActionMgtServiceComponent.java | 18 +++---- ...olver.java => ActionDTOModelResolver.java} | 12 ++--- ...=> ActionDTOModelResolverFactoryTest.java} | 34 ++++++------ .../dao/ActionManagementDAOFacadeTest.java | 54 +++++++++---------- .../dao/ActionManagementDAOImplTest.java | 2 +- ...r.java => TestActionDTOModelResolver.java} | 16 +++--- .../src/test/resources/testng.xml | 2 +- 12 files changed, 129 insertions(+), 111 deletions(-) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/{ActionPropertyResolverFactory.java => ActionDTOModelResolverFactory.java} (57%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/{ActionPropertyResolver.java => ActionDTOModelResolver.java} (91%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/{ActionPropertyResolverFactoryTest.java => ActionDTOModelResolverFactoryTest.java} (55%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/{TestActionPropertyResolver.java => TestActionDTOModelResolver.java} (87%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionDTOModelResolverFactory.java similarity index 57% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionDTOModelResolverFactory.java index b100659ffc4b..be9285259a11 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionPropertyResolverFactory.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionDTOModelResolverFactory.java @@ -19,43 +19,43 @@ package org.wso2.carbon.identity.action.management.dao.impl; import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; import java.util.EnumMap; import java.util.Map; /** - * This class defines the Action Property Resolver Factory. - * Action Property Resolver Factory is the component that is responsible for providing the - * {@link ActionPropertyResolver} based on the action type. + * This class defines the ActionDTO Model Resolver Factory. + * ActionDTO Model Resolver Factory is the component that is responsible for providing the + * {@link ActionDTOModelResolver} based on the action type. */ -public class ActionPropertyResolverFactory { +public class ActionDTOModelResolverFactory { - private static final Map actionPropertyResolvers = + private static final Map actionDTOModelResolvers = new EnumMap<>(Action.ActionTypes.class); - private ActionPropertyResolverFactory() { + private ActionDTOModelResolverFactory() { } - public static ActionPropertyResolver getActionPropertyResolver(Action.ActionTypes actionType) { + public static ActionDTOModelResolver getActionDTOModelResolver(Action.ActionTypes actionType) { switch (actionType) { case PRE_UPDATE_PASSWORD: - return actionPropertyResolvers.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); + return actionDTOModelResolvers.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); case PRE_ISSUE_ACCESS_TOKEN: - return actionPropertyResolvers.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); + return actionDTOModelResolvers.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); default: return null; } } - public static void registerActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + public static void registerActionDTOModelResolver(ActionDTOModelResolver actionDTOModelResolver) { - actionPropertyResolvers.put(actionPropertyResolver.getSupportedActionType(), actionPropertyResolver); + actionDTOModelResolvers.put(actionDTOModelResolver.getSupportedActionType(), actionDTOModelResolver); } - public static void unregisterActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + public static void unregisterActionDTOModelResolver(ActionDTOModelResolver actionDTOModelResolver) { - actionPropertyResolvers.remove(actionPropertyResolver.getSupportedActionType()); + actionDTOModelResolvers.remove(actionDTOModelResolver.getSupportedActionType()); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index 41bd8e9be269..6bea59c915d6 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -34,7 +34,7 @@ import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; @@ -80,6 +80,7 @@ public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtExc return null; }); } catch (TransactionException e) { + // Since exceptions thrown are wrapped with TransactionException, extracting the actual cause. handleActionPropertyResolverClientException(e.getCause()); LOG.debug("Error while creating the Action of Action Type: " + actionDTO.getType().getDisplayName() + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + @@ -138,6 +139,7 @@ public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDT return null; }); } catch (TransactionException e) { + // Since exceptions thrown are wrapped with TransactionException, extracting the actual cause. handleActionPropertyResolverClientException(e.getCause()); LOG.debug("Error while updating the Action of Action Type: " + updatingActionDTO.getType().getDisplayName() + " and Action ID: " + updatingActionDTO.getId() + @@ -303,13 +305,13 @@ private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); - if (actionPropertyResolver == null) { + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(actionDTO.getType()); + if (actionDTOModelResolver == null) { return actionDTO; } - return actionPropertyResolver.resolveAddingProperties(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + return actionDTOModelResolver.resolveForAddOperation(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } /** @@ -326,13 +328,13 @@ private List getActionDTOsWithPopulatedProperties(String actionType, Integer tenantId) throws ActionPropertyResolverException { - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.valueOf(actionType)); - if (actionPropertyResolver == null) { + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(Action.ActionTypes.valueOf(actionType)); + if (actionDTOModelResolver == null) { return actionDTOs; } - return actionPropertyResolver.populateProperties(actionDTOs, IdentityTenantUtil.getTenantDomain(tenantId)); + return actionDTOModelResolver.resolveForGetOperation(actionDTOs, IdentityTenantUtil.getTenantDomain(tenantId)); } /** @@ -346,13 +348,13 @@ private List getActionDTOsWithPopulatedProperties(String actionType, private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integer tenantId) throws ActionPropertyResolverException { - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(actionDTO.getType()); - if (actionPropertyResolver == null) { + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(actionDTO.getType()); + if (actionDTOModelResolver == null) { return actionDTO; } - return actionPropertyResolver.populateProperties(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + return actionDTOModelResolver.resolveForGetOperation(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } /** @@ -368,13 +370,13 @@ private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingA ActionDTO existingActionDTO, Integer tenantId) throws ActionPropertyResolverException { - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(updatingActionDTO.getType()); - if (actionPropertyResolver == null) { + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(updatingActionDTO.getType()); + if (actionDTOModelResolver == null) { return updatingActionDTO; } - return actionPropertyResolver.resolveUpdatingProperties(updatingActionDTO, existingActionDTO, + return actionDTOModelResolver.resolveForUpdateOperation(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); } @@ -388,13 +390,14 @@ private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingA private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) throws ActionPropertyResolverException { - ActionPropertyResolver actionPropertyResolver = - ActionPropertyResolverFactory.getActionPropertyResolver(deletingActionDTO.getType()); - if (actionPropertyResolver == null) { + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(deletingActionDTO.getType()); + if (actionDTOModelResolver == null) { return; } - actionPropertyResolver.deleteProperties(deletingActionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + actionDTOModelResolver.resolveForDeleteOperation(deletingActionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); } /** @@ -407,8 +410,9 @@ private static void handleActionPropertyResolverClientException(Throwable throwa throws ActionMgtClientException { if (throwable instanceof ActionPropertyResolverClientException) { - throw ActionManagementExceptionHandler.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES, - throwable.getMessage()); + ActionPropertyResolverClientException clientException = (ActionPropertyResolverClientException) throwable; + throw new ActionMgtClientException(clientException.getMessage(), clientException.getDescription(), + ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java index 22601fba1001..88eed37b1881 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java @@ -25,8 +25,8 @@ */ public class ActionPropertyResolverClientException extends ActionPropertyResolverException { - public ActionPropertyResolverClientException(String message) { + public ActionPropertyResolverClientException(String message, String description) { - super(message); + super(message, description); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java index 783640ed1329..fec6dffa5112 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java @@ -24,13 +24,27 @@ */ public class ActionPropertyResolverException extends Exception { + private String description; + public ActionPropertyResolverException(String message) { super(message); } - public ActionPropertyResolverException(String message, Throwable cause) { + public ActionPropertyResolverException(String message, String description) { + + super(message); + this.description = description; + } + + public ActionPropertyResolverException(String message, String description, Throwable cause) { super(message, cause); + this.description = description; + } + + public String getDescription() { + + return this.description; } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java index 1b064c1e10f6..769268347f5c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java @@ -29,8 +29,8 @@ public ActionPropertyResolverServerException(String message) { super(message); } - public ActionPropertyResolverServerException(String message, Throwable cause) { + public ActionPropertyResolverServerException(String message, String description, Throwable cause) { - super(message, cause); + super(message, description, cause); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index 3dce8d3f3968..8da0688e5a86 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -28,10 +28,10 @@ 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.action.management.dao.impl.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; import org.wso2.carbon.identity.action.management.service.ActionConverter; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; import org.wso2.carbon.identity.action.management.service.ActionManagementService; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; import org.wso2.carbon.identity.action.management.service.impl.ActionConverterFactory; import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; @@ -99,27 +99,27 @@ protected void unsetActionConverter(ActionConverter actionConverter) { @Reference( name = "action.property.resolver", - service = ActionPropertyResolver.class, + service = ActionDTOModelResolver.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, unbind = "unsetActionPropertyResolver" ) - protected void setActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + protected void setActionPropertyResolver(ActionDTOModelResolver actionDTOModelResolver) { if (LOG.isDebugEnabled()) { - LOG.debug("Registering ActionPropertyResolver: " + actionPropertyResolver.getClass().getName() + + LOG.debug("Registering ActionPropertyResolver: " + actionDTOModelResolver.getClass().getName() + " in the ActionMgtServiceComponent."); } - ActionPropertyResolverFactory.registerActionPropertyResolver(actionPropertyResolver); + ActionDTOModelResolverFactory.registerActionDTOModelResolver(actionDTOModelResolver); } - protected void unsetActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + protected void unsetActionPropertyResolver(ActionDTOModelResolver actionDTOModelResolver) { if (LOG.isDebugEnabled()) { - LOG.debug("Unregistering ActionPropertyResolver: " + actionPropertyResolver.getClass().getName() + + LOG.debug("Unregistering ActionPropertyResolver: " + actionDTOModelResolver.getClass().getName() + " in the ActionMgtServiceComponent."); } - ActionPropertyResolverFactory.unregisterActionPropertyResolver(actionPropertyResolver); + ActionDTOModelResolverFactory.unregisterActionDTOModelResolver(actionDTOModelResolver); } @Reference( diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java similarity index 91% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java index 2a64ca7f64f7..d76012273fef 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java @@ -28,7 +28,7 @@ * This interface defines the Action Property Resolver. * Action Property Resolver is the component that is responsible for handling action type specific operations. */ -public interface ActionPropertyResolver { +public interface ActionDTOModelResolver { Action.ActionTypes getSupportedActionType(); @@ -43,7 +43,7 @@ public interface ActionPropertyResolver { * @return ActionDTO object with resolved properties. * @throws ActionPropertyResolverException If an error occurs while resolving the properties. */ - default ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDomain) + default ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { return actionDTO; @@ -60,7 +60,7 @@ default ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDoma * @return ActionDTO object with populated properties. * @throws ActionPropertyResolverException If an error occurs while populating the properties. */ - default ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) + default ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) throws ActionPropertyResolverException { return actionDTO; @@ -78,7 +78,7 @@ default ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) * @return List of ActionDTO objects with populated properties. * @throws ActionPropertyResolverException If an error occurs while populating the properties. */ - default List populateProperties(List actionDTOList, String tenantDomain) + default List resolveForGetOperation(List actionDTOList, String tenantDomain) throws ActionPropertyResolverException { return actionDTOList; @@ -96,7 +96,7 @@ default List populateProperties(List actionDTOList, String * @return ActionDTO object with resolved properties. * @throws ActionPropertyResolverException If an error occurs while resolving the properties. */ - default ActionDTO resolveUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + default ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, String tenantDomain) throws ActionPropertyResolverException { return updatingActionDTO; @@ -111,7 +111,7 @@ default ActionDTO resolveUpdatingProperties(ActionDTO updatingActionDTO, ActionD * @param tenantDomain Tenant domain. * @throws ActionPropertyResolverException If an error occurs while deleting the properties. */ - default void deleteProperties(ActionDTO deletingActionDTO, String tenantDomain) + default void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) throws ActionPropertyResolverException { } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionPropertyResolverFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionDTOModelResolverFactoryTest.java similarity index 55% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionPropertyResolverFactoryTest.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionDTOModelResolverFactoryTest.java index 5754267584dd..23171e048ad2 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionPropertyResolverFactoryTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionDTOModelResolverFactoryTest.java @@ -23,48 +23,48 @@ import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; +import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; import static org.mockito.Mockito.doReturn; /** - * Action Property Resolver Factory Test. + * ActionDTO Model Resolver Factory Test. */ -public class ActionPropertyResolverFactoryTest { +public class ActionDTOModelResolverFactoryTest { private final Action.ActionTypes actionType = Action.ActionTypes.PRE_UPDATE_PASSWORD; @Mock - private ActionPropertyResolver mockActionPropertyResolver; + private ActionDTOModelResolver mockActionDTOModelResolver; @BeforeMethod public void setUp() { MockitoAnnotations.openMocks(this); - doReturn(actionType).when(mockActionPropertyResolver).getSupportedActionType(); + doReturn(actionType).when(mockActionDTOModelResolver).getSupportedActionType(); } @Test - public void testRegisterActionPropertyResolver() { + public void testRegisterActionDTOModelResolver() { - ActionPropertyResolverFactory.registerActionPropertyResolver(mockActionPropertyResolver); - ActionPropertyResolver registeredResult = ActionPropertyResolverFactory.getActionPropertyResolver(actionType); - Assert.assertEquals(registeredResult, mockActionPropertyResolver); + ActionDTOModelResolverFactory.registerActionDTOModelResolver(mockActionDTOModelResolver); + ActionDTOModelResolver registeredResult = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionType); + Assert.assertEquals(registeredResult, mockActionDTOModelResolver); } - @Test(dependsOnMethods = {"testRegisterActionPropertyResolver"}) - public void testUnregisterActionPropertyResolver() { + @Test(dependsOnMethods = {"testRegisterActionDTOModelResolver"}) + public void testUnregisterActionDTOModelResolver() { - ActionPropertyResolverFactory.unregisterActionPropertyResolver(mockActionPropertyResolver); - ActionPropertyResolver unregisteredResult = ActionPropertyResolverFactory.getActionPropertyResolver(actionType); + ActionDTOModelResolverFactory.unregisterActionDTOModelResolver(mockActionDTOModelResolver); + ActionDTOModelResolver unregisteredResult = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionType); Assert.assertNull(unregisteredResult); } - @Test(dependsOnMethods = {"testUnregisterActionPropertyResolver"}) - public void testGetActionPropertyResolverNotFound() { + @Test(dependsOnMethods = {"testUnregisterActionDTOModelResolver"}) + public void testGetActionDTOModelResolverNotFound() { - ActionPropertyResolver result = ActionPropertyResolverFactory.getActionPropertyResolver(actionType); + ActionDTOModelResolver result = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionType); Assert.assertNull(result); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index d59c24fbdeb8..ccd28f3d1ba8 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -28,9 +28,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; +import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; -import org.wso2.carbon.identity.action.management.dao.impl.ActionPropertyResolverFactory; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; @@ -42,7 +42,7 @@ import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.certificate.management.model.Certificate; @@ -94,9 +94,9 @@ public class ActionManagementDAOFacadeTest { @Mock - private ActionPropertyResolver mockedActionPropertyResolver; - private TestActionPropertyResolver testActionPropertyResolver; - private MockedStatic actionPropertyResolverFactory; + private ActionDTOModelResolver mockedActionDTOModelResolver; + private TestActionDTOModelResolver testActionPropertyResolver; + private MockedStatic actionPropertyResolverFactory; private MockedStatic identityTenantUtil; private ActionManagementDAOFacade daoFacade; @@ -120,7 +120,7 @@ public void setUpClass() { .property(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder().certificateContent(TEST_CERTIFICATE).build()) .build(); - testActionPropertyResolver = new TestActionPropertyResolver(); + testActionPropertyResolver = new TestActionDTOModelResolver(); } @BeforeMethod @@ -136,13 +136,13 @@ public void setUp() throws SecretManagementException { identityTenantUtil.when(()-> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(TENANT_DOMAIN); MockitoAnnotations.openMocks(this); - actionPropertyResolverFactory = mockStatic(ActionPropertyResolverFactory.class); + actionPropertyResolverFactory = mockStatic(ActionDTOModelResolverFactory.class); } @AfterMethod public void tearDown() { - mockedActionPropertyResolver = null; + mockedActionDTOModelResolver = null; identityTenantUtil.close(); actionPropertyResolverFactory.close(); } @@ -150,9 +150,9 @@ public void tearDown() { @Test(priority = 1) public void testAddActionWithActionPropertyResolverClientException() throws ActionPropertyResolverException { - mockActionPropertyResolver(mockedActionPropertyResolver); - doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(mockedActionPropertyResolver) - .resolveAddingProperties(any(), any()); + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionPropertyResolverClientException("Invalid Certificate.", "Invalid PEM format.")) + .when(mockedActionDTOModelResolver).resolveForAddOperation(any(), any()); try { daoFacade.addAction(creatingActionDTO, TENANT_ID); @@ -160,17 +160,17 @@ public void testAddActionWithActionPropertyResolverClientException() throws Acti } catch (ActionMgtException e) { Assert.assertEquals(e.getClass(), ActionMgtClientException.class); Assert.assertEquals(e.getErrorCode(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); - Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getMessage()); - Assert.assertEquals(e.getDescription(), "Invalid Certificate."); + Assert.assertEquals(e.getMessage(), "Invalid Certificate."); + Assert.assertEquals(e.getDescription(), "Invalid PEM format."); } } @Test(priority = 2) public void testAddActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { - mockActionPropertyResolver(mockedActionPropertyResolver); - doThrow(new ActionPropertyResolverServerException("Error adding Certificate.", new Throwable())) - .when(mockedActionPropertyResolver).resolveAddingProperties(any(), any()); + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionPropertyResolverServerException("Error adding Certificate.", null, new Throwable())) + .when(mockedActionDTOModelResolver).resolveForAddOperation(any(), any()); try { daoFacade.addAction(creatingActionDTO, TENANT_ID); @@ -264,9 +264,9 @@ public void testGetActionsByType() throws ActionMgtException { @Test(priority = 5) public void testUpdateActionPropertyResolverClientException() throws ActionPropertyResolverException { - mockActionPropertyResolver(mockedActionPropertyResolver); - doThrow(new ActionPropertyResolverClientException("Invalid Certificate.")).when(mockedActionPropertyResolver) - .resolveUpdatingProperties(any(), any(), any()); + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionPropertyResolverClientException("Invalid Certificate.", "Invalid PEM format.")) + .when(mockedActionDTOModelResolver).resolveForUpdateOperation(any(), any(), any()); try { daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); @@ -274,18 +274,18 @@ public void testUpdateActionPropertyResolverClientException() throws ActionPrope } catch (ActionMgtException e) { Assert.assertEquals(e.getClass(), ActionMgtClientException.class); Assert.assertEquals(e.getErrorCode(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); - Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getMessage()); - Assert.assertEquals(e.getDescription(), "Invalid Certificate."); + Assert.assertEquals(e.getMessage(), "Invalid Certificate."); + Assert.assertEquals(e.getDescription(), "Invalid PEM format."); } } @Test(priority = 6) public void testUpdateActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { - mockActionPropertyResolver(mockedActionPropertyResolver); + mockActionPropertyResolver(mockedActionDTOModelResolver); doThrow(new ActionPropertyResolverServerException("Error updating Certificate.")).when( - mockedActionPropertyResolver) - .resolveUpdatingProperties(any(), any(), any()); + mockedActionDTOModelResolver) + .resolveForUpdateOperation(any(), any(), any()); try { daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); @@ -394,10 +394,10 @@ public void testDeleteAction() throws ActionMgtException { Assert.assertEquals(daoFacade.getActionsCountPerType(TENANT_ID), Collections.emptyMap()); } - private void mockActionPropertyResolver(ActionPropertyResolver actionPropertyResolver) { + private void mockActionPropertyResolver(ActionDTOModelResolver actionDTOModelResolver) { actionPropertyResolverFactory.when( - () -> ActionPropertyResolverFactory.getActionPropertyResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) - .thenReturn(actionPropertyResolver); + () -> ActionDTOModelResolverFactory.getActionDTOModelResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionDTOModelResolver); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index ab716801d95b..2f40c18b674d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -45,7 +45,7 @@ /** * This class is a test suite for the ActionManagementDAOImpl class. * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOImpl class. - * This test class will utilize {@link TestActionPropertyResolver} class as the test implementation for + * This test class will utilize {@link TestActionDTOModelResolver} class as the test implementation for * ActionPropertyResolver interface. */ @WithH2Database(files = {"dbscripts/h2.sql"}) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java similarity index 87% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java index d5fb57d5f07f..84506f7042ee 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionPropertyResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java @@ -20,7 +20,7 @@ import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.ActionDTO; -import org.wso2.carbon.identity.action.management.service.ActionPropertyResolver; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.certificate.management.model.Certificate; @@ -35,9 +35,9 @@ import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; /** - * Test implementation of ActionPropertyResolver. + * Test implementation of {@link ActionDTOModelResolver}. */ -public class TestActionPropertyResolver implements ActionPropertyResolver { +public class TestActionDTOModelResolver implements ActionDTOModelResolver { @Override public Action.ActionTypes getSupportedActionType() { @@ -46,7 +46,7 @@ public Action.ActionTypes getSupportedActionType() { } @Override - public ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDomain) { + public ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) { Map properties = new HashMap<>(); properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); @@ -56,7 +56,7 @@ public ActionDTO resolveAddingProperties(ActionDTO actionDTO, String tenantDomai } @Override - public ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) { + public ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) { Map properties = new HashMap<>(); properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, @@ -73,7 +73,7 @@ public ActionDTO populateProperties(ActionDTO actionDTO, String tenantDomain) { } @Override - public List populateProperties(List actionDTOList, String tenantDomain) { + public List resolveForGetOperation(List actionDTOList, String tenantDomain) { List resolvedActionDTOList = new ArrayList<>(); for (ActionDTO actionDTO : actionDTOList) { @@ -93,8 +93,8 @@ public List populateProperties(List actionDTOList, String } @Override - public ActionDTO resolveUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, - String tenantDomain) { + public ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + String tenantDomain) { Map properties = new HashMap<>(); properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index 128d48e9d440..d9b62e751a03 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -22,7 +22,7 @@ - + From c1def6bb6d659f9c59a9ed9e45590828b57668b5 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Mon, 2 Dec 2024 16:11:00 +0530 Subject: [PATCH 28/34] Rename Exception files --- .../dao/impl/ActionManagementDAOFacade.java | 32 +++++++++---------- ...ctionDTOModelResolverClientException.java} | 6 ++-- ...a => ActionDTOModelResolverException.java} | 10 +++--- ...ctionDTOModelResolverServerException.java} | 8 ++--- .../service/ActionDTOModelResolver.java | 22 ++++++------- .../impl/ActionManagementServiceImpl.java | 29 +++++++---------- .../CacheBackedActionManagementService.java | 4 +-- .../dao/ActionManagementDAOFacadeTest.java | 26 +++++++-------- .../ActionManagementServiceImplTest.java | 3 +- 9 files changed, 66 insertions(+), 74 deletions(-) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/{ActionPropertyResolverClientException.java => ActionDTOModelResolverClientException.java} (81%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/{ActionPropertyResolverException.java => ActionDTOModelResolverException.java} (79%) rename components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/{ActionPropertyResolverServerException.java => ActionDTOModelResolverServerException.java} (77%) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index 6bea59c915d6..0db0eb881f6a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -24,11 +24,11 @@ import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverClientException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverException; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; -import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverClientException; -import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.AuthProperty; @@ -96,7 +96,7 @@ public List getActionsByActionType(String actionType, Integer tenantI List actionDTOS = actionManagementDAO.getActionsByActionType(actionType, tenantId); return getActionDTOsWithPopulatedProperties(actionType, actionDTOS, tenantId); - } catch (ActionMgtException | ActionPropertyResolverException e) { + } catch (ActionMgtException | ActionDTOModelResolverException e) { throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); } @@ -114,7 +114,7 @@ public ActionDTO getActionByActionId(String actionType, String actionId, Integer // Populate action properties return getActionDTOWithPopulatedProperties(actionDTO, tenantId); - } catch (ActionMgtException | ActionPropertyResolverException e) { + } catch (ActionMgtException | ActionDTOModelResolverException e) { throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); } @@ -300,10 +300,10 @@ private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, * @param actionDTO ActionDTO object. * @param tenantId Tenant ID. * @return ActionDTO object with resolved adding properties. - * @throws ActionPropertyResolverException If an error occurs while resolving the adding properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the adding properties. */ private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, Integer tenantId) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionDTO.getType()); @@ -322,11 +322,11 @@ private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, * @param actionDTOs List of ActionDTO objects. * @param tenantId Tenant ID. * @return List of ActionDTO objects with populated properties. - * @throws ActionPropertyResolverException If an error occurs while populating the properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ private List getActionDTOsWithPopulatedProperties(String actionType, List actionDTOs, Integer tenantId) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = ActionDTOModelResolverFactory.getActionDTOModelResolver(Action.ActionTypes.valueOf(actionType)); @@ -343,10 +343,10 @@ private List getActionDTOsWithPopulatedProperties(String actionType, * @param actionDTO ActionDTO object. * @param tenantId Tenant ID. * @return ActionDTO object with populated properties. - * @throws ActionPropertyResolverException If an error occurs while populating the properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integer tenantId) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionDTO.getType()); @@ -364,11 +364,11 @@ private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integ * @param existingActionDTO Existing ActionDTO object. * @param tenantId Tenant ID. * @return ActionDTO object with resolved updating properties. - * @throws ActionPropertyResolverException If an error occurs while resolving the updating properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the updating properties. */ private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = ActionDTOModelResolverFactory.getActionDTOModelResolver(updatingActionDTO.getType()); @@ -385,10 +385,10 @@ private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingA * * @param deletingActionDTO Deleting ActionDTO object. * @param tenantId Tenant ID. - * @throws ActionPropertyResolverException If an error occurs while deleting the properties. + * @throws ActionDTOModelResolverException If an error occurs while deleting the properties. */ private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = ActionDTOModelResolverFactory.getActionDTOModelResolver(deletingActionDTO.getType()); @@ -409,8 +409,8 @@ private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) private static void handleActionPropertyResolverClientException(Throwable throwable) throws ActionMgtClientException { - if (throwable instanceof ActionPropertyResolverClientException) { - ActionPropertyResolverClientException clientException = (ActionPropertyResolverClientException) throwable; + if (throwable instanceof ActionDTOModelResolverClientException) { + ActionDTOModelResolverClientException clientException = (ActionDTOModelResolverClientException) throwable; throw new ActionMgtClientException(clientException.getMessage(), clientException.getDescription(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverClientException.java similarity index 81% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverClientException.java index 88eed37b1881..f8d4700358d5 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverClientException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverClientException.java @@ -19,13 +19,13 @@ package org.wso2.carbon.identity.action.management.exception; /** - * Client Exception class for Action Property Resolver. + * Client Exception class for ActionDTO Model Resolver. * This exception is thrown when there is any validation failures or client error in performing action type * specific operations. */ -public class ActionPropertyResolverClientException extends ActionPropertyResolverException { +public class ActionDTOModelResolverClientException extends ActionDTOModelResolverException { - public ActionPropertyResolverClientException(String message, String description) { + public ActionDTOModelResolverClientException(String message, String description) { super(message, description); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java similarity index 79% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java index fec6dffa5112..91e2871bc903 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java @@ -19,25 +19,25 @@ package org.wso2.carbon.identity.action.management.exception; /** - * Exception class for Action Property Resolver. + * Exception class for ActionDTO Model Resolver. * This exception is thrown when there is an issue in performing action type specific operations. */ -public class ActionPropertyResolverException extends Exception { +public class ActionDTOModelResolverException extends Exception { private String description; - public ActionPropertyResolverException(String message) { + public ActionDTOModelResolverException(String message) { super(message); } - public ActionPropertyResolverException(String message, String description) { + public ActionDTOModelResolverException(String message, String description) { super(message); this.description = description; } - public ActionPropertyResolverException(String message, String description, Throwable cause) { + public ActionDTOModelResolverException(String message, String description, Throwable cause) { super(message, cause); this.description = description; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java similarity index 77% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java index 769268347f5c..5d074ffbcc6d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionPropertyResolverServerException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java @@ -19,17 +19,17 @@ package org.wso2.carbon.identity.action.management.exception; /** - * Server Exception class for Action Property Resolver. + * Server Exception class for ActionDTO Model Resolver. * This exception is thrown when there is an issue in performing action type specific operations in the system. */ -public class ActionPropertyResolverServerException extends ActionPropertyResolverException { +public class ActionDTOModelResolverServerException extends ActionDTOModelResolverException { - public ActionPropertyResolverServerException(String message) { + public ActionDTOModelResolverServerException(String message) { super(message); } - public ActionPropertyResolverServerException(String message, String description, Throwable cause) { + public ActionDTOModelResolverServerException(String message, String description, Throwable cause) { super(message, description, cause); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java index d76012273fef..2a4a2265fc0b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java @@ -18,7 +18,7 @@ package org.wso2.carbon.identity.action.management.service; -import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.ActionDTO; @@ -41,10 +41,10 @@ public interface ActionDTOModelResolver { * @param actionDTO ActionDTO object. * @param tenantDomain Tenant domain. * @return ActionDTO object with resolved properties. - * @throws ActionPropertyResolverException If an error occurs while resolving the properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the properties. */ default ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { return actionDTO; } @@ -58,10 +58,10 @@ default ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomai * @param actionDTO ActionDTO object with properties references. * @param tenantDomain Tenant domain. * @return ActionDTO object with populated properties. - * @throws ActionPropertyResolverException If an error occurs while populating the properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ default ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { return actionDTO; } @@ -76,10 +76,10 @@ default ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomai * @param actionDTOList List of ActionDTO objects with properties references. * @param tenantDomain Tenant domain. * @return List of ActionDTO objects with populated properties. - * @throws ActionPropertyResolverException If an error occurs while populating the properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ default List resolveForGetOperation(List actionDTOList, String tenantDomain) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { return actionDTOList; } @@ -94,10 +94,10 @@ default List resolveForGetOperation(List actionDTOList, St * @param existingActionDTO ActionDTO object with existing properties. * @param tenantDomain Tenant domain. * @return ActionDTO object with resolved properties. - * @throws ActionPropertyResolverException If an error occurs while resolving the properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the properties. */ default ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, - String tenantDomain) throws ActionPropertyResolverException { + String tenantDomain) throws ActionDTOModelResolverException { return updatingActionDTO; } @@ -109,9 +109,9 @@ default ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionD * * @param deletingActionDTO ActionDTO object with properties to be deleted. * @param tenantDomain Tenant domain. - * @throws ActionPropertyResolverException If an error occurs while deleting the properties. + * @throws ActionDTOModelResolverException If an error occurs while deleting the properties. */ default void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) - throws ActionPropertyResolverException { + throws ActionDTOModelResolverException { } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index 94a419b658e4..56ed76f4262c 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -22,8 +22,8 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; -import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; @@ -51,16 +51,11 @@ public class ActionManagementServiceImpl implements ActionManagementService { private static final Log LOG = LogFactory.getLog(ActionManagementServiceImpl.class); + private static final ActionManagementDAOFacade DAO_FACADE = + new ActionManagementDAOFacade(new ActionManagementDAOImpl()); private static final ActionValidator ACTION_VALIDATOR = new ActionValidator(); private static final ActionManagementAuditLogger auditLogger = new ActionManagementAuditLogger(); - private final ActionManagementDAOFacade daoFacade; - - public ActionManagementServiceImpl(ActionManagementDAO actionManagementDAO) { - - this.daoFacade = new ActionManagementDAOFacade(actionManagementDAO); - } - /** * Create a new action of the specified type in the given tenant. * @@ -83,7 +78,7 @@ public Action addAction(String actionType, Action action, String tenantDomain) t String generatedActionId = UUID.randomUUID().toString(); ActionDTO creatingActionDTO = buildActionDTO(resolvedActionType, generatedActionId, action); - daoFacade.addAction(creatingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + DAO_FACADE.addAction(creatingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); Action createdAction = getActionByActionId(actionType, generatedActionId, tenantDomain); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ADD, creatingActionDTO); @@ -105,7 +100,7 @@ public List getActionsByActionType(String actionType, String tenantDomai LOG.debug(String.format("Retrieving Actions for Action Type: %s.", actionType)); } String resolvedActionType = getActionTypeFromPath(actionType); - List actionDTOS = daoFacade.getActionsByActionType(resolvedActionType, + List actionDTOS = DAO_FACADE.getActionsByActionType(resolvedActionType, IdentityTenantUtil.getTenantId(tenantDomain)); return actionDTOS.stream() @@ -130,7 +125,7 @@ public Action getActionByActionId(String actionType, String actionId, String ten LOG.debug(String.format("Retrieving Action of Action ID: %s", actionId)); } String resolvedActionType = getActionTypeFromPath(actionType); - ActionDTO actionDTO = daoFacade.getActionByActionId(resolvedActionType, actionId, + ActionDTO actionDTO = DAO_FACADE.getActionByActionId(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); return buildAction(resolvedActionType, actionDTO); @@ -161,7 +156,7 @@ public Action updateAction(String actionType, String actionId, Action action, St ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); ActionDTO updatingActionDTO = buildActionDTO(resolvedActionType, actionId, action); - daoFacade.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + DAO_FACADE.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, updatingActionDTO); return getActionByActionId(actionType, actionId, tenantDomain); } @@ -182,7 +177,7 @@ public void deleteAction(String actionType, String actionId, String tenantDomain } String resolvedActionType = getActionTypeFromPath(actionType); ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - daoFacade.deleteAction(existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + DAO_FACADE.deleteAction(existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DELETE, actionType, actionId); } @@ -203,7 +198,7 @@ public Action activateAction(String actionType, String actionId, String tenantDo } String resolvedActionType = getActionTypeFromPath(actionType); checkIfActionExists(resolvedActionType, actionId, tenantDomain); - ActionDTO activatedActionDTO = daoFacade.activateAction(resolvedActionType, actionId, + ActionDTO activatedActionDTO = DAO_FACADE.activateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ACTIVATE, actionType, actionId); return buildAction(resolvedActionType, activatedActionDTO); @@ -227,7 +222,7 @@ public Action deactivateAction(String actionType, String actionId, String tenant } String resolvedActionType = getActionTypeFromPath(actionType); checkIfActionExists(resolvedActionType, actionId, tenantDomain); - ActionDTO deactivatedActionDTO = daoFacade.deactivateAction(resolvedActionType, actionId, + ActionDTO deactivatedActionDTO = DAO_FACADE.deactivateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DEACTIVATE, actionType, actionId); return buildAction(resolvedActionType, deactivatedActionDTO); @@ -246,7 +241,7 @@ public Map getActionsCountPerType(String tenantDomain) throws A if (LOG.isDebugEnabled()) { LOG.debug("Retrieving Actions count per Type."); } - return daoFacade.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); + return DAO_FACADE.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); } /** @@ -318,7 +313,7 @@ private void validateMaxActionsPerType(String actionType, String tenantDomain) t private ActionDTO checkIfActionExists(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - ActionDTO actionDTO = daoFacade.getActionByActionId(actionType, actionId, + ActionDTO actionDTO = DAO_FACADE.getActionByActionId(actionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); if (actionDTO == null || !actionType.equals(actionDTO.getType().name())) { throw ActionManagementExceptionHandler.handleClientException( diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java index e37b36ae33a5..616678aeb8e7 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java @@ -24,7 +24,6 @@ import org.wso2.carbon.identity.action.management.cache.ActionCacheByType; import org.wso2.carbon.identity.action.management.cache.ActionCacheEntry; import org.wso2.carbon.identity.action.management.cache.ActionTypeCacheKey; -import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; @@ -40,8 +39,7 @@ public class CacheBackedActionManagementService implements ActionManagementServi private static final CacheBackedActionManagementService INSTANCE = new CacheBackedActionManagementService(); private static final Log LOG = LogFactory.getLog(CacheBackedActionManagementService.class); - private static final ActionManagementServiceImpl ACTION_MGT_SERVICE = - new ActionManagementServiceImpl(new ActionManagementDAOImpl()); + private static final ActionManagementServiceImpl ACTION_MGT_SERVICE = new ActionManagementServiceImpl(); private final ActionCacheByType actionCacheByType; private CacheBackedActionManagementService() { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index ccd28f3d1ba8..6397de3e6167 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -31,12 +31,12 @@ import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverClientException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverServerException; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; -import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverClientException; -import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverException; -import org.wso2.carbon.identity.action.management.exception.ActionPropertyResolverServerException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.ActionDTO; @@ -148,10 +148,10 @@ public void tearDown() { } @Test(priority = 1) - public void testAddActionWithActionPropertyResolverClientException() throws ActionPropertyResolverException { + public void testAddActionWithActionPropertyResolverClientException() throws ActionDTOModelResolverException { mockActionPropertyResolver(mockedActionDTOModelResolver); - doThrow(new ActionPropertyResolverClientException("Invalid Certificate.", "Invalid PEM format.")) + doThrow(new ActionDTOModelResolverClientException("Invalid Certificate.", "Invalid PEM format.")) .when(mockedActionDTOModelResolver).resolveForAddOperation(any(), any()); try { @@ -166,10 +166,10 @@ public void testAddActionWithActionPropertyResolverClientException() throws Acti } @Test(priority = 2) - public void testAddActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { + public void testAddActionWithActionPropertyResolverServerException() throws ActionDTOModelResolverException { mockActionPropertyResolver(mockedActionDTOModelResolver); - doThrow(new ActionPropertyResolverServerException("Error adding Certificate.", null, new Throwable())) + doThrow(new ActionDTOModelResolverServerException("Error adding Certificate.", null, new Throwable())) .when(mockedActionDTOModelResolver).resolveForAddOperation(any(), any()); try { @@ -179,7 +179,7 @@ public void testAddActionWithActionPropertyResolverServerException() throws Acti Assert.assertEquals(e.getClass(), ActionMgtServerException.class); Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_WHILE_ADDING_ACTION.getMessage()); for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof ActionPropertyResolverServerException) { + if (cause instanceof ActionDTOModelResolverServerException) { return; } } @@ -262,10 +262,10 @@ public void testGetActionsByType() throws ActionMgtException { } @Test(priority = 5) - public void testUpdateActionPropertyResolverClientException() throws ActionPropertyResolverException { + public void testUpdateActionPropertyResolverClientException() throws ActionDTOModelResolverException { mockActionPropertyResolver(mockedActionDTOModelResolver); - doThrow(new ActionPropertyResolverClientException("Invalid Certificate.", "Invalid PEM format.")) + doThrow(new ActionDTOModelResolverClientException("Invalid Certificate.", "Invalid PEM format.")) .when(mockedActionDTOModelResolver).resolveForUpdateOperation(any(), any(), any()); try { @@ -280,10 +280,10 @@ public void testUpdateActionPropertyResolverClientException() throws ActionPrope } @Test(priority = 6) - public void testUpdateActionWithActionPropertyResolverServerException() throws ActionPropertyResolverException { + public void testUpdateActionWithActionPropertyResolverServerException() throws ActionDTOModelResolverException { mockActionPropertyResolver(mockedActionDTOModelResolver); - doThrow(new ActionPropertyResolverServerException("Error updating Certificate.")).when( + doThrow(new ActionDTOModelResolverServerException("Error updating Certificate.")).when( mockedActionDTOModelResolver) .resolveForUpdateOperation(any(), any(), any()); @@ -294,7 +294,7 @@ public void testUpdateActionWithActionPropertyResolverServerException() throws A Assert.assertEquals(e.getClass(), ActionMgtServerException.class); Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_WHILE_UPDATING_ACTION.getMessage()); for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { - if (cause instanceof ActionPropertyResolverServerException) { + if (cause instanceof ActionDTOModelResolverServerException) { return; } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java index ceaa300f87db..aa6b55351516 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java @@ -23,7 +23,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; @@ -80,7 +79,7 @@ public class ActionManagementServiceImplTest { @BeforeClass public void setUpClass() { - actionManagementService = new ActionManagementServiceImpl(new ActionManagementDAOImpl()); + actionManagementService = new ActionManagementServiceImpl(); } @BeforeMethod From 79930933227872d78a9a2d01f278b50507184b99 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 3 Dec 2024 17:59:51 +0530 Subject: [PATCH 29/34] Address comments --- .../dao/impl/ActionManagementDAOFacade.java | 18 +++++------ .../ActionDTOModelResolverException.java | 7 +---- ...ActionDTOModelResolverServerException.java | 4 +-- .../management/service/ActionConverter.java | 16 ++-------- .../service/ActionDTOModelResolver.java | 31 +++++-------------- .../dao/ActionManagementDAOFacadeTest.java | 2 +- .../dao/TestActionDTOModelResolver.java | 5 +++ 7 files changed, 28 insertions(+), 55 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java index 0db0eb881f6a..76ca02ba9aea 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -73,7 +73,7 @@ public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtExc // Encrypt authentication secrets encryptAddingAuthSecrets(actionDTOBuilder); // Resolve action properties - ActionDTO resolvedActionDTO = getActionDTOWithResolvedAddingProperties(actionDTOBuilder.build(), + ActionDTO resolvedActionDTO = getResolvedActionDTOForAddOperation(actionDTOBuilder.build(), tenantId); actionManagementDAO.addAction(resolvedActionDTO, tenantId); @@ -95,7 +95,7 @@ public List getActionsByActionType(String actionType, Integer tenantI try { List actionDTOS = actionManagementDAO.getActionsByActionType(actionType, tenantId); - return getActionDTOsWithPopulatedProperties(actionType, actionDTOS, tenantId); + return getResolvedActionDTOsForGetOperation(actionType, actionDTOS, tenantId); } catch (ActionMgtException | ActionDTOModelResolverException e) { throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); @@ -113,7 +113,7 @@ public ActionDTO getActionByActionId(String actionType, String actionId, Integer } // Populate action properties - return getActionDTOWithPopulatedProperties(actionDTO, tenantId); + return getResolvedActionDTOForGetOperation(actionDTO, tenantId); } catch (ActionMgtException | ActionDTOModelResolverException e) { throw ActionManagementExceptionHandler.handleServerException( ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); @@ -132,7 +132,7 @@ public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDT encryptUpdatingAuthSecrets(updatingActionDTOBuilder, existingActionDTO); // Resolve action properties ActionDTO resolvedUpdatingActionDTO = - getActionDTOWithResolvedUpdatingProperties(updatingActionDTOBuilder.build(), existingActionDTO, + getResolvedActionDTOForUpdateOperation(updatingActionDTOBuilder.build(), existingActionDTO, tenantId); actionManagementDAO.updateAction(resolvedUpdatingActionDTO, existingActionDTO, tenantId); @@ -302,7 +302,7 @@ private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, * @return ActionDTO object with resolved adding properties. * @throws ActionDTOModelResolverException If an error occurs while resolving the adding properties. */ - private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, Integer tenantId) + private ActionDTO getResolvedActionDTOForAddOperation(ActionDTO actionDTO, Integer tenantId) throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = @@ -324,7 +324,7 @@ private ActionDTO getActionDTOWithResolvedAddingProperties(ActionDTO actionDTO, * @return List of ActionDTO objects with populated properties. * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ - private List getActionDTOsWithPopulatedProperties(String actionType, List actionDTOs, + private List getResolvedActionDTOsForGetOperation(String actionType, List actionDTOs, Integer tenantId) throws ActionDTOModelResolverException { @@ -345,7 +345,7 @@ private List getActionDTOsWithPopulatedProperties(String actionType, * @return ActionDTO object with populated properties. * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ - private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integer tenantId) + private ActionDTO getResolvedActionDTOForGetOperation(ActionDTO actionDTO, Integer tenantId) throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = @@ -366,8 +366,8 @@ private ActionDTO getActionDTOWithPopulatedProperties(ActionDTO actionDTO, Integ * @return ActionDTO object with resolved updating properties. * @throws ActionDTOModelResolverException If an error occurs while resolving the updating properties. */ - private ActionDTO getActionDTOWithResolvedUpdatingProperties(ActionDTO updatingActionDTO, - ActionDTO existingActionDTO, Integer tenantId) + private ActionDTO getResolvedActionDTOForUpdateOperation(ActionDTO updatingActionDTO, + ActionDTO existingActionDTO, Integer tenantId) throws ActionDTOModelResolverException { ActionDTOModelResolver actionDTOModelResolver = diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java index 91e2871bc903..c144ff388164 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java @@ -24,12 +24,7 @@ */ public class ActionDTOModelResolverException extends Exception { - private String description; - - public ActionDTOModelResolverException(String message) { - - super(message); - } + private final String description; public ActionDTOModelResolverException(String message, String description) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java index 5d074ffbcc6d..e8861ae0aff1 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java @@ -24,9 +24,9 @@ */ public class ActionDTOModelResolverServerException extends ActionDTOModelResolverException { - public ActionDTOModelResolverServerException(String message) { + public ActionDTOModelResolverServerException(String message, String description) { - super(message); + super(message, description); } public ActionDTOModelResolverServerException(String message, String description, Throwable cause) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java index c4e4d17628ad..dc46635bb5a1 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java @@ -36,25 +36,13 @@ public interface ActionConverter { * @param action Action object. * @return ActionDTO object. */ - default ActionDTO buildActionDTO(Action action) { + ActionDTO buildActionDTO(Action action); - return new ActionDTO.Builder(action).build(); - } /** * Convert ActionDTO object into Action object. * * @param actionDTO ActionDTO object. * @return Action object. */ - default Action buildAction(ActionDTO actionDTO) { - - return new Action.ActionResponseBuilder() - .id(actionDTO.getId()) - .type(actionDTO.getType()) - .name(actionDTO.getName()) - .description(actionDTO.getDescription()) - .status(actionDTO.getStatus()) - .endpoint(actionDTO.getEndpoint()) - .build(); - } + Action buildAction(ActionDTO actionDTO); } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java index 2a4a2265fc0b..abfc30170b09 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java @@ -43,11 +43,7 @@ public interface ActionDTOModelResolver { * @return ActionDTO object with resolved properties. * @throws ActionDTOModelResolverException If an error occurs while resolving the properties. */ - default ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) - throws ActionDTOModelResolverException { - - return actionDTO; - } + ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) throws ActionDTOModelResolverException; /** * Populate the properties according to the references stored in the Action Management Service. @@ -60,11 +56,7 @@ default ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomai * @return ActionDTO object with populated properties. * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ - default ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) - throws ActionDTOModelResolverException { - - return actionDTO; - } + ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) throws ActionDTOModelResolverException; /** * Populate the properties of the given ActionDTO list according to the references stored in the Action Management @@ -78,11 +70,8 @@ default ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomai * @return List of ActionDTO objects with populated properties. * @throws ActionDTOModelResolverException If an error occurs while populating the properties. */ - default List resolveForGetOperation(List actionDTOList, String tenantDomain) - throws ActionDTOModelResolverException { - - return actionDTOList; - } + List resolveForGetOperation(List actionDTOList, String tenantDomain) + throws ActionDTOModelResolverException; /** * Resolve the properties that need to be updated in the Action Management Service. @@ -96,11 +85,8 @@ default List resolveForGetOperation(List actionDTOList, St * @return ActionDTO object with resolved properties. * @throws ActionDTOModelResolverException If an error occurs while resolving the properties. */ - default ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, - String tenantDomain) throws ActionDTOModelResolverException { - - return updatingActionDTO; - } + ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, String tenantDomain) + throws ActionDTOModelResolverException; /** * Delete the properties that need to be deleted in the Action Management Service. @@ -111,7 +97,6 @@ default ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionD * @param tenantDomain Tenant domain. * @throws ActionDTOModelResolverException If an error occurs while deleting the properties. */ - default void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) - throws ActionDTOModelResolverException { - } + void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) + throws ActionDTOModelResolverException; } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java index 6397de3e6167..8aa13fc9e089 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -283,7 +283,7 @@ public void testUpdateActionPropertyResolverClientException() throws ActionDTOMo public void testUpdateActionWithActionPropertyResolverServerException() throws ActionDTOModelResolverException { mockActionPropertyResolver(mockedActionDTOModelResolver); - doThrow(new ActionDTOModelResolverServerException("Error updating Certificate.")).when( + doThrow(new ActionDTOModelResolverServerException("Error updating Certificate.", null)).when( mockedActionDTOModelResolver) .resolveForUpdateOperation(any(), any(), any()); diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java index 84506f7042ee..c6a943034c5e 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java @@ -102,4 +102,9 @@ public ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDT return new ActionDTO.Builder(updatingActionDTO).properties(properties).build(); } + + @Override + public void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) { + + } } From ea0adc842b974547c58463fd91846e3ed220dc76 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Tue, 3 Dec 2024 21:06:20 +0530 Subject: [PATCH 30/34] Modify actionMnagementService imports --- .../management/internal/ActionMgtServiceComponentHolder.java | 2 -- .../carbon/idp/mgt/internal/IdPManagementServiceComponent.java | 2 +- .../carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java | 2 +- .../carbon/idp/mgt/IdentityProviderManagementServiceTest.java | 2 +- .../org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java | 2 +- 5 files changed, 4 insertions(+), 6 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java index 81e889869454..5866841fdbaa 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponentHolder.java @@ -18,7 +18,6 @@ package org.wso2.carbon.identity.action.management.internal; -import org.wso2.carbon.identity.certificate.management.service.CertificateManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -29,7 +28,6 @@ public class ActionMgtServiceComponentHolder { private SecretManager secretManager; private SecretResolveManager secretResolveManager; - private CertificateManagementService certificateMgtService; public static final ActionMgtServiceComponentHolder INSTANCE = new ActionMgtServiceComponentHolder(); diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java index 511ad2a1b1d5..e6d3e590735e 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java @@ -33,7 +33,7 @@ import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java index f86c85fc32de..a46d26abbfe2 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java @@ -19,7 +19,7 @@ package org.wso2.carbon.idp.mgt.internal; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java index 143c0b95204c..be164abfdf08 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java @@ -27,10 +27,10 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.core.util.CryptoUtil; -import org.wso2.carbon.identity.action.management.ActionManagementService; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.ApplicationAuthenticatorService; import org.wso2.carbon.identity.application.common.ProvisioningConnectorService; import org.wso2.carbon.identity.application.common.model.Claim; diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java index a80704e4c4e0..8a58a33886f9 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java @@ -28,9 +28,9 @@ import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.action.management.ActionManagementService; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.model.*; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; import org.wso2.carbon.identity.common.testng.WithCarbonHome; From 29d61a2539c3841d1ef3a25db8573995e4b60804 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 4 Dec 2024 03:08:25 +0530 Subject: [PATCH 31/34] Minor improvement --- .../action/management/dao/TestActionDTOModelResolver.java | 1 + 1 file changed, 1 insertion(+) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java index c6a943034c5e..2b5424d40672 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java @@ -106,5 +106,6 @@ public ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDT @Override public void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) { + // No need to resolve anything for delete operation since this is a test implementation. } } From 30d9ad4c8b9f8c2fc99462fe361a53075320ff30 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 4 Dec 2024 13:28:24 +0530 Subject: [PATCH 32/34] Add fallback to IDN_ACTION_ENDPOINT table --- .../constant/ActionMgtSQLConstants.java | 16 +++++ .../dao/impl/ActionManagementDAOImpl.java | 64 +++++++++++++------ 2 files changed, 61 insertions(+), 19 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java index 8f6ae2c77200..6fecc776c47d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java @@ -27,6 +27,9 @@ private ActionMgtSQLConstants() { } + public static final String IDN_ACTION_PROPERTIES_TABLE = "IDN_ACTION_PROPERTIES"; + public static final String IDN_ACTION_ENDPOINT_TABLE = "IDN_ACTION_ENDPOINT"; + /** * Column Names. */ @@ -78,6 +81,19 @@ public static class Query { "PROPERTY_VALUE = :PROPERTY_VALUE; WHERE ACTION_UUID = :ACTION_UUID; AND " + "TENANT_ID = :TENANT_ID; AND PROPERTY_NAME = :PROPERTY_NAME;"; + // TODO: Remove this temporary queries once the IDN_ACTION_PROPERTIES table is created. + public static final String ADD_ACTION_ENDPOINT = "INSERT INTO IDN_ACTION_ENDPOINT (ACTION_UUID, " + + "PROPERTY_NAME, PROPERTY_VALUE, TENANT_ID) VALUES (:ACTION_UUID;, :PROPERTY_NAME;, :PROPERTY_VALUE;, " + + ":TENANT_ID;)"; + public static final String GET_ACTION_ENDPOINT_INFO_BY_ID = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM " + + "IDN_ACTION_ENDPOINT WHERE ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; + public static final String DELETE_ACTION_ENDPOINT_PROPERTY = "DELETE FROM IDN_ACTION_ENDPOINT WHERE " + + "PROPERTY_NAME = :PROPERTY_NAME; AND ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; + public static final String UPDATE_ACTION_ENDPOINT_PROPERTY = "UPDATE IDN_ACTION_ENDPOINT SET " + + "PROPERTY_VALUE = :PROPERTY_VALUE; WHERE ACTION_UUID = :ACTION_UUID; AND " + + "TENANT_ID = :TENANT_ID; AND PROPERTY_NAME = :PROPERTY_NAME;"; + + private Query() { } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index a4a0816aa217..2a53f6b1e810 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -475,7 +475,9 @@ private void addActionPropertiesToDB(String actionId, Map action NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_PROPERTIES, + String query = isPropertiesTableExists() ? ActionMgtSQLConstants.Query.ADD_ACTION_PROPERTIES + : ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT; + template.executeBatchInsert(query, statement -> { for (Map.Entry property : actionProperties.entrySet()) { statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); @@ -504,7 +506,9 @@ private Map getActionPropertiesFromDB(String actionId, Integer t NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); Map actionEndpointProperties = new HashMap<>(); try { - jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_PROPERTIES_INFO_BY_ID, + String query = isPropertiesTableExists() ? ActionMgtSQLConstants.Query.GET_ACTION_PROPERTIES_INFO_BY_ID + : ActionMgtSQLConstants.Query.GET_ACTION_ENDPOINT_INFO_BY_ID; + jdbcTemplate.executeQuery(query, (resultSet, rowNumber) -> { actionEndpointProperties.put( resultSet.getString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME), @@ -517,7 +521,7 @@ private Map getActionPropertiesFromDB(String actionId, Integer t }); return actionEndpointProperties; - } catch (DataAccessException e) { + } catch (DataAccessException | SQLException e) { throw new ActionMgtServerException("Error while retrieving Action Properties from the system.", e); } } @@ -534,19 +538,22 @@ private void updateActionPropertiesInDB(String actionId, Map upd Integer tenantId) throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - jdbcTemplate.withTransaction(template -> - template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_PROPERTY, - statement -> { - for (Map.Entry property : updatingProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE, - property.getValue()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, - property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - statement.addBatch(); - } - }, null)); + jdbcTemplate.withTransaction(template -> { + String query = isPropertiesTableExists() ? ActionMgtSQLConstants.Query.UPDATE_ACTION_PROPERTY + : ActionMgtSQLConstants.Query.UPDATE_ACTION_ENDPOINT_PROPERTY; + return template.executeBatchInsert(query, + statement -> { + for (Map.Entry property : updatingProperties.entrySet()) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE, + property.getValue()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, + property.getKey()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.addBatch(); + } + }, null); + }); } /** @@ -561,8 +568,10 @@ private void deleteActionPropertiesInDB(String actionId, List deletingPr throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - jdbcTemplate.withTransaction(template -> - template.executeBatchInsert(ActionMgtSQLConstants.Query.DELETE_ACTION_PROPERTY, + jdbcTemplate.withTransaction(template -> { + String query = isPropertiesTableExists() ? ActionMgtSQLConstants.Query.DELETE_ACTION_PROPERTY + : ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTY; + return template.executeBatchInsert(query, statement -> { for (String property : deletingProperties) { statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, @@ -571,7 +580,8 @@ private void deleteActionPropertiesInDB(String actionId, List deletingPr statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); statement.addBatch(); } - }, null)); + }, null); + }); } /** @@ -602,4 +612,20 @@ private ActionDTO changeActionStatus(String actionType, String actionId, String throw new ActionMgtServerException("Error while updating Action Status to " + status, e); } } + + /** + * Check whether the IDN_ACTION_PROPERTIES table exists in the database. + * TODO: Remove this temporary method once the table is created. + * + * @return True if the table exists, False otherwise. + * @throws SQLException If an error occurs while checking the table existence. + */ + private boolean isPropertiesTableExists() throws SQLException { + + try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); + ResultSet resultSet = connection.getMetaData().getTables(null, null, + ActionMgtSQLConstants.IDN_ACTION_PROPERTIES_TABLE, null)) { + return resultSet.next(); + } + } } From 3f2a42d8b95613bf6ab79c5161dcb835577820a0 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 4 Dec 2024 15:05:19 +0530 Subject: [PATCH 33/34] Revert db scripts --- .../src/test/resources/dbscripts/h2.sql | 2 +- .../resources/dbscripts/db2.sql | 2 +- .../resources/dbscripts/h2.sql | 2 +- .../resources/dbscripts/mssql.sql | 2 +- .../resources/dbscripts/mysql-cluster.sql | 2 +- .../resources/dbscripts/mysql.sql | 2 +- .../resources/dbscripts/oracle.sql | 2 +- .../resources/dbscripts/oracle_rac.sql | 2 +- .../resources/dbscripts/postgresql.sql | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql index 9bf8470be8e8..776921371a60 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql @@ -8,7 +8,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql index 065ca3719ae4..0bb70a35e5db 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql @@ -2267,7 +2267,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); / -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql index 5e8b74e153c4..bfe52846ff1d 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql @@ -1487,7 +1487,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql index adafc091efae..231e0ff73ddc 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql @@ -1638,7 +1638,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql index bd88f410cfbd..50ea8ebf6164 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql @@ -1679,7 +1679,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql index b2eb12391d97..5c331ab54f25 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql @@ -1515,7 +1515,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql index 7fa6d49d06e0..6636a2717308 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql @@ -2324,7 +2324,7 @@ CREATE INDEX IDX_CON_FILE_RES_ID ON IDN_CONFIG_FILE (RESOURCE_ID) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql index b7d2a6901480..2d9c97707a7d 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql @@ -2229,7 +2229,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql index e79f5d721dfa..a62b056d12f9 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql @@ -1762,7 +1762,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_PROPERTIES_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); From b30a89b4c92b0252ca7d6a835702c248bc5b5290 Mon Sep 17 00:00:00 2001 From: Ashan Thamara Palihakkara <75057725+ashanthamara@users.noreply.github.com> Date: Wed, 4 Dec 2024 15:08:18 +0530 Subject: [PATCH 34/34] Revert db scripts --- .../resources/dbscripts/db2.sql | 4 ++-- .../resources/dbscripts/h2.sql | 4 ++-- .../resources/dbscripts/mssql.sql | 6 +++--- .../resources/dbscripts/mysql-cluster.sql | 4 ++-- .../resources/dbscripts/mysql.sql | 4 ++-- .../resources/dbscripts/oracle.sql | 4 ++-- .../resources/dbscripts/oracle_rac.sql | 4 ++-- .../resources/dbscripts/postgresql.sql | 6 +++--- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql index 0bb70a35e5db..c8934674be58 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/db2.sql @@ -2083,7 +2083,7 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ) / -CREATE TABLE IDN_ACTION_PROPERTIES ( +CREATE TABLE IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -2267,7 +2267,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql index bfe52846ff1d..b8bed8110432 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/h2.sql @@ -1362,7 +1362,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1487,7 +1487,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql index 231e0ff73ddc..ae2824ced0bc 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mssql.sql @@ -1510,8 +1510,8 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ); -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_ACTION_PROPERTIES]') AND TYPE in (N'U')) -CREATE TABLE IDN_ACTION_PROPERTIES ( +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_ACTION_ENDPOINT]') AND TYPE in (N'U')) +CREATE TABLE IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1638,7 +1638,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql index 50ea8ebf6164..d9a4e310daab 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql-cluster.sql @@ -1525,7 +1525,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) )ENGINE NDB; -CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1679,7 +1679,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql index 5c331ab54f25..60bf37f8ca0f 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/mysql.sql @@ -1393,7 +1393,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) )DEFAULT CHARACTER SET latin1 ENGINE INNODB; -CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1515,7 +1515,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID); diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql index 6636a2717308..b1daec5a8412 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle.sql @@ -2146,7 +2146,7 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ) / -CREATE TABLE IDN_ACTION_PROPERTIES ( +CREATE TABLE IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -2324,7 +2324,7 @@ CREATE INDEX IDX_CON_FILE_RES_ID ON IDN_CONFIG_FILE (RESOURCE_ID) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID) / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql index 2d9c97707a7d..430f4458488f 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/oracle_rac.sql @@ -2079,7 +2079,7 @@ CREATE TABLE IDN_ACTION ( PRIMARY KEY (UUID) ) / -CREATE TABLE IDN_ACTION_PROPERTIES ( +CREATE TABLE IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -2229,7 +2229,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME) -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID) / -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID) +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID) / -- CERTIFICATE -- diff --git a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql index a62b056d12f9..cfd6cabf6105 100644 --- a/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql +++ b/features/identity-core/org.wso2.carbon.identity.core.server.feature/resources/dbscripts/postgresql.sql @@ -1630,8 +1630,8 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -DROP TABLE IF EXISTS IDN_ACTION_PROPERTIES; -CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( +DROP TABLE IF EXISTS IDN_ACTION_ENDPOINT; +CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, @@ -1762,7 +1762,7 @@ CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); -- ACTIONS -- CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); -CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_PROPERTIES (ACTION_UUID, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); -- CERTIFICATE -- CREATE INDEX IDX_IDN_CERTIFICATE_ID_TID ON IDN_CERTIFICATE (ID, TENANT_ID);