Search in sources :

Example 96 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class APIMappingUtil method handleAWSCredentials.

/**
 * Set AWS Secret Key based on preserveCredentials state
 *
 * @param awsEndpointConfig   Endpoint configuration of the API
 * @param preserveCredentials Condition to preserve credentials
 * @return Updated endpoint config
 */
private static JSONObject handleAWSCredentials(JSONObject awsEndpointConfig, boolean preserveCredentials) {
    if (StringUtils.isNotEmpty((String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY))) {
        if (!preserveCredentials) {
            awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, APIConstants.AWS_SECRET_KEY);
            return awsEndpointConfig;
        } else {
            String secretKey = (String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            // Decrypting the key since CTL project goes between environments which have different encryption keys.
            try {
                CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                String decryptedSecret = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
                awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, decryptedSecret);
                return awsEndpointConfig;
            } catch (CryptoException | UnsupportedEncodingException e) {
                log.error("Error while decrypting the Amazon key", e);
            }
        }
    }
    return awsEndpointConfig;
}
Also used : CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CryptoException(org.wso2.carbon.core.util.CryptoException)

Example 97 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class SearchResultMappingUtil method setPaginationParams.

/**
 * Sets pagination urls for a SearchResultListDTO object given pagination parameters and url parameters.
 *
 * @param resultListDTO a SearchResultListDTO object
 * @param query         search condition
 * @param limit         max number of objects returned
 * @param offset        starting index
 * @param size          max offset
 */
public static void setPaginationParams(SearchResultListDTO resultListDTO, String query, int offset, int limit, int size) {
    // acquiring pagination parameters and setting pagination urls
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
    String paginatedPrevious = "";
    String paginatedNext = "";
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
    }
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setNext(paginatedNext);
    paginationDTO.setPrevious(paginatedPrevious);
    paginationDTO.setOffset(offset);
    paginationDTO.setLimit(limit);
    paginationDTO.setTotal(size);
    resultListDTO.setPagination(paginationDTO);
}
Also used : PaginationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO)

Example 98 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class PolicyMappingUtil method mapCondition.

/**
 * Map a org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition to a
 * org.wso2.carbon.apimgt.api.model.policy.Condition
 *
 * @param conditionDTO org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition
 * @return org.wso2.carbon.apimgt.api.model.policy.Condition object
 */
public static Condition mapCondition(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition conditionDTO) {
    switch(conditionDTO.getConditionType()) {
        case PolicyConstants.IP_RANGE_TYPE:
            IPCondition ipRangeCondition = new IPCondition(PolicyConstants.IP_RANGE_TYPE);
            ipRangeCondition.setInvertCondition(conditionDTO.isInverted());
            ipRangeCondition.setStartingIP(conditionDTO.getName());
            ipRangeCondition.setEndingIP(conditionDTO.getValue());
            return ipRangeCondition;
        case PolicyConstants.IP_SPECIFIC_TYPE:
            IPCondition ipSpecificCondition = new IPCondition(PolicyConstants.IP_SPECIFIC_TYPE);
            ipSpecificCondition.setInvertCondition(conditionDTO.isInverted());
            ipSpecificCondition.setSpecificIP(conditionDTO.getValue());
            return ipSpecificCondition;
        case PolicyConstants.HEADER_TYPE:
            HeaderCondition headerCondition = new HeaderCondition();
            headerCondition.setInvertCondition(conditionDTO.isInverted());
            headerCondition.setHeader(conditionDTO.getName());
            headerCondition.setValue(conditionDTO.getValue());
            return headerCondition;
        case PolicyConstants.JWT_CLAIMS_TYPE:
            JWTClaimsCondition jwtClaimsCondition = new JWTClaimsCondition();
            jwtClaimsCondition.setInvertCondition(conditionDTO.isInverted());
            jwtClaimsCondition.setClaimUrl(conditionDTO.getName());
            jwtClaimsCondition.setAttribute(conditionDTO.getValue());
            return jwtClaimsCondition;
        case PolicyConstants.QUERY_PARAMETER_TYPE:
            QueryParameterCondition queryParameterCondition = new QueryParameterCondition();
            queryParameterCondition.setInvertCondition(conditionDTO.isInverted());
            queryParameterCondition.setParameter(conditionDTO.getName());
            queryParameterCondition.setValue(conditionDTO.getValue());
            return queryParameterCondition;
        default:
            return null;
    }
}
Also used : IPCondition(org.wso2.carbon.apimgt.api.model.policy.IPCondition) JWTClaimsCondition(org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition) HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)

Example 99 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class PolicyUtil method deployPolicy.

/**
 * Deploy the given throttle policy in the Traffic Manager.
 *
 * @param policy      policy object
 * @param policyEvent policy event object which was triggered
 */
public static void deployPolicy(Policy policy, PolicyEvent policyEvent) {
    EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
    ThrottlePolicyTemplateBuilder policyTemplateBuilder = new ThrottlePolicyTemplateBuilder();
    Map<String, String> policiesToDeploy = new HashMap<>();
    List<String> policiesToUndeploy = new ArrayList<>();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
        String policyFile;
        String policyString;
        if (Policy.PolicyType.SUBSCRIPTION.equals(policy.getType()) && policy instanceof SubscriptionPolicy) {
            // Add Subscription policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_SUB, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForSubscriptionLevel((SubscriptionPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.APPLICATION.equals(policy.getType()) && policy instanceof ApplicationPolicy) {
            // Add Application policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_APP, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForAppLevel((ApplicationPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.API.equals(policy.getType()) && policy instanceof ApiPolicy) {
            // Add API policy
            policiesToDeploy = policyTemplateBuilder.getThrottlePolicyForAPILevel((ApiPolicy) policy);
            String defaultPolicy = policyTemplateBuilder.getThrottlePolicyForAPILevelDefault((ApiPolicy) policy);
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_RESOURCE, policy.getName());
            String defaultPolicyName = policyFile + APIConstants.THROTTLE_POLICY_DEFAULT;
            policiesToDeploy.put(defaultPolicyName, defaultPolicy);
            if (policyEvent instanceof APIPolicyEvent) {
                List<Integer> deletedConditionGroupIds = ((APIPolicyEvent) policyEvent).getDeletedConditionGroupIds();
                // Undeploy removed condition groups
                if (deletedConditionGroupIds != null) {
                    for (int conditionGroupId : deletedConditionGroupIds) {
                        policiesToUndeploy.add(policyFile + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroupId);
                    }
                }
            }
        } else if (Policy.PolicyType.GLOBAL.equals(policy.getType()) && policy instanceof GlobalPolicy) {
            // Add Global policy
            GlobalPolicy globalPolicy = (GlobalPolicy) policy;
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, PolicyConstants.POLICY_LEVEL_GLOBAL, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForGlobalLevel(globalPolicy);
            policiesToDeploy.put(policyFile, policyString);
        }
        // Undeploy removed policies
        undeployPolicies(policiesToUndeploy);
        for (Map.Entry<String, String> pair : policiesToDeploy.entrySet()) {
            String policyPlanName = pair.getKey();
            String flowString = pair.getValue();
            String executionPlan = null;
            try {
                executionPlan = eventProcessorService.getActiveExecutionPlan(policyPlanName);
            } catch (ExecutionPlanConfigurationException e) {
                // Deploy new policies
                eventProcessorService.deployExecutionPlan(flowString);
            }
            if (executionPlan != null) {
                // Update existing policies
                eventProcessorService.editActiveExecutionPlan(flowString, policyPlanName);
            }
        }
    } catch (APITemplateException e) {
        log.error("Error in creating execution plan", e);
    } catch (ExecutionPlanConfigurationException | ExecutionPlanDependencyValidationException e) {
        log.error("Error in deploying execution plan", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : HashMap(java.util.HashMap) GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) ArrayList(java.util.ArrayList) ApiPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy) ExecutionPlanConfigurationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanConfigurationException) EventProcessorService(org.wso2.carbon.event.processor.core.EventProcessorService) ExecutionPlanDependencyValidationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanDependencyValidationException) SubscriptionPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.SubscriptionPolicy) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) ApplicationPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 100 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class PolicyDAOImpl method isBlockConditionExist.

/**
 * Check if a blocking condition already exists.
 *
 * @param blockConditions BlockConditions object to be added
 * @return true/false depending on the success
 * @throws APIMgtDAOException If failed to check if block condition exist
 */
private boolean isBlockConditionExist(BlockConditions blockConditions) throws APIMgtDAOException {
    boolean status = false;
    if (blockConditions.getConditionType().equals(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE)) {
        String isExistQuery = "SELECT STARTING_IP, ENDING_IP FROM AM_IP_RANGE_CONDITION WHERE STARTING_IP =? " + "AND ENDING_IP =?";
        try (Connection connection = DAOUtil.getConnection();
            PreparedStatement checkIsExistPreparedStatement = connection.prepareStatement(isExistQuery)) {
            checkIsExistPreparedStatement.setString(1, blockConditions.getStartingIP());
            checkIsExistPreparedStatement.setString(2, blockConditions.getEndingIP());
            try (ResultSet checkIsResultSet = checkIsExistPreparedStatement.executeQuery()) {
                if (checkIsResultSet.next()) {
                    status = true;
                }
            }
        } catch (SQLException e) {
            String msg = DAOUtil.DAO_ERROR_PREFIX + "checking if the IP range blacklist condition exists with starting IP: " + blockConditions.getStartingIP() + ", ending IP: " + blockConditions.getEndingIP();
            throw new APIMgtDAOException(msg, e);
        }
    } else {
        String isExistQuery = "SELECT CONDITION_ID,TYPE,VALUE,ENABLED,UUID FROM AM_BLOCK_CONDITIONS WHERE TYPE =? " + "AND VALUE =?";
        try (Connection connection = DAOUtil.getConnection();
            PreparedStatement checkIsExistPreparedStatement = connection.prepareStatement(isExistQuery)) {
            connection.setAutoCommit(false);
            checkIsExistPreparedStatement.setString(1, blockConditions.getConditionType());
            checkIsExistPreparedStatement.setString(2, blockConditions.getConditionValue());
            try (ResultSet checkIsResultSet = checkIsExistPreparedStatement.executeQuery()) {
                if (checkIsResultSet.next()) {
                    status = true;
                }
            }
        } catch (SQLException e) {
            String msg = DAOUtil.DAO_ERROR_PREFIX + "checking if the Block Condition Exist with condition type: " + blockConditions.getConditionType() + ", condition value: " + blockConditions.getConditionValue();
            throw new APIMgtDAOException(msg, e);
        }
    }
    return status;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

HashMap (java.util.HashMap)39 Test (org.junit.Test)32 Test (org.testng.annotations.Test)31 ArrayList (java.util.ArrayList)30 List (java.util.List)26 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)26 ConditionDto (org.wso2.carbon.apimgt.impl.dto.ConditionDto)26 MessageContext (org.apache.synapse.MessageContext)25 PreparedStatement (java.sql.PreparedStatement)23 Map (java.util.Map)22 ResultSet (java.sql.ResultSet)20 BlockConditions (org.wso2.carbon.apimgt.core.models.BlockConditions)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)18 Connection (java.sql.Connection)16 SQLException (java.sql.SQLException)16 TreeMap (java.util.TreeMap)16 HeaderCondition (org.wso2.carbon.apimgt.api.model.policy.HeaderCondition)15 JWTClaimsCondition (org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition)15 QueryParameterCondition (org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)15 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)15