Search in sources :

Example 61 with Condition

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

the class AbstractAPIManagerTestCase method testGetTiersForTenant.

@Test
public void testGetTiersForTenant() throws APIManagementException {
    Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(-1234, -1, 1);
    Map<String, Tier> tierMap1 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap2 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap3 = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    Tier tier3 = new Tier("tier3");
    tierMap1.put("Gold", tier1);
    tierMap2.put("Gold", tier1);
    tierMap2.put("Silver", tier2);
    tierMap3.put("Gold", tier1);
    tierMap3.put("Silver", tier2);
    tierMap3.put("Platinum", tier3);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTiers()).thenReturn(tierMap1);
    PowerMockito.when(APIUtil.getTiers(Mockito.anyInt())).thenReturn(tierMap2);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap1);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 1);
    // verify next branch of if
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 1);
    // condition
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap2);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 2);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap3);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 3);
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) HashMap(java.util.HashMap) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 62 with Condition

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

the class APIProviderImpl method updatePolicy.

public void updatePolicy(Policy policy) throws APIManagementException {
    String oldKeyTemplate = null;
    String newKeyTemplate = null;
    if (policy instanceof APIPolicy) {
        APIPolicy apiPolicy = (APIPolicy) policy;
        apiPolicy.setUserLevel(PolicyConstants.ACROSS_ALL);
        // TODO this has done due to update policy method not deleting the second level entries when delete on cascade
        // TODO Need to fix appropriately
        List<Pipeline> pipelineList = apiPolicy.getPipelines();
        if (pipelineList != null && pipelineList.size() != 0) {
            Iterator<Pipeline> pipelineIterator = pipelineList.iterator();
            while (pipelineIterator.hasNext()) {
                Pipeline pipeline = pipelineIterator.next();
                if (!pipeline.isEnabled()) {
                    pipelineIterator.remove();
                } else {
                    if (pipeline.getConditions() != null && pipeline.getConditions().size() != 0) {
                        Iterator<Condition> conditionIterator = pipeline.getConditions().iterator();
                        while (conditionIterator.hasNext()) {
                            Condition condition = conditionIterator.next();
                            if (JavaUtils.isFalseExplicitly(condition.getConditionEnabled())) {
                                conditionIterator.remove();
                            }
                        }
                    } else {
                        pipelineIterator.remove();
                    }
                }
            }
        }
        APIPolicy existingPolicy = apiMgtDAO.getAPIPolicy(policy.getPolicyName(), policy.getTenantId());
        apiPolicy = apiMgtDAO.updateAPIPolicy(apiPolicy);
        // TODO rename level to  resource or appropriate name
        APIManagerConfiguration config = getAPIManagerConfiguration();
        if (log.isDebugEnabled()) {
            log.debug("Calling invalidation cache for API Policy for tenant ");
        }
        String policyContext = APIConstants.POLICY_CACHE_CONTEXT + "/t/" + apiPolicy.getTenantDomain() + "/";
        invalidateResourceCache(policyContext, null, Collections.EMPTY_SET);
        List<Integer> addedConditionGroupIds = new ArrayList<>();
        List<Integer> deletedConditionGroupIds = new ArrayList<>();
        for (Pipeline pipeline : existingPolicy.getPipelines()) {
            deletedConditionGroupIds.add(pipeline.getId());
        }
        for (Pipeline pipeline : apiPolicy.getPipelines()) {
            addedConditionGroupIds.add(pipeline.getId());
        }
        APIPolicyEvent apiPolicyEvent = new APIPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, apiPolicy.getTenantDomain(), apiPolicy.getPolicyId(), apiPolicy.getPolicyName(), apiPolicy.getDefaultQuotaPolicy().getType(), addedConditionGroupIds, deletedConditionGroupIds);
        APIUtil.sendNotification(apiPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof ApplicationPolicy) {
        ApplicationPolicy appPolicy = (ApplicationPolicy) policy;
        apiMgtDAO.updateApplicationPolicy(appPolicy);
        // policy id is not set. retrieving policy to get the id.
        ApplicationPolicy retrievedPolicy = apiMgtDAO.getApplicationPolicy(appPolicy.getPolicyName(), tenantId);
        ApplicationPolicyEvent applicationPolicyEvent = new ApplicationPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, appPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), appPolicy.getPolicyName(), appPolicy.getDefaultQuotaPolicy().getType());
        APIUtil.sendNotification(applicationPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof SubscriptionPolicy) {
        SubscriptionPolicy subPolicy = (SubscriptionPolicy) policy;
        apiMgtDAO.updateSubscriptionPolicy(subPolicy);
        String monetizationPlan = subPolicy.getMonetizationPlan();
        Map<String, String> monetizationPlanProperties = subPolicy.getMonetizationPlanProperties();
        // call the monetization extension point to create plans (if any)
        if (StringUtils.isNotBlank(monetizationPlan) && MapUtils.isNotEmpty(monetizationPlanProperties)) {
            updateMonetizationPlan(subPolicy);
        }
        // policy id is not set. retrieving policy to get the id.
        SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(subPolicy.getPolicyName(), tenantId);
        SubscriptionPolicyEvent subscriptionPolicyEvent = new SubscriptionPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, subPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), subPolicy.getPolicyName(), subPolicy.getDefaultQuotaPolicy().getType(), subPolicy.getRateLimitCount(), subPolicy.getRateLimitTimeUnit(), subPolicy.isStopOnQuotaReach(), subPolicy.getGraphQLMaxDepth(), subPolicy.getGraphQLMaxComplexity(), subPolicy.getSubscriberCount());
        APIUtil.sendNotification(subscriptionPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof GlobalPolicy) {
        GlobalPolicy globalPolicy = (GlobalPolicy) policy;
        // getting key templates before updating database
        GlobalPolicy oldGlobalPolicy = apiMgtDAO.getGlobalPolicy(policy.getPolicyName());
        oldKeyTemplate = oldGlobalPolicy.getKeyTemplate();
        newKeyTemplate = globalPolicy.getKeyTemplate();
        apiMgtDAO.updateGlobalPolicy(globalPolicy);
        GlobalPolicy retrievedPolicy = apiMgtDAO.getGlobalPolicy(globalPolicy.getPolicyName());
        GlobalPolicyEvent globalPolicyEvent = new GlobalPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, globalPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), globalPolicy.getPolicyName());
        APIUtil.sendNotification(globalPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else {
        String msg = "Policy type " + policy.getClass().getName() + " is not supported";
        log.error(msg);
        throw new UnsupportedPolicyTypeException(msg);
    }
    // publishing keytemplate after update
    if (oldKeyTemplate != null && newKeyTemplate != null) {
        publishKeyTemplateEvent(oldKeyTemplate, "remove");
        publishKeyTemplateEvent(newKeyTemplate, "add");
    }
}
Also used : Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) ArrayList(java.util.ArrayList) ApplicationPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationPolicyEvent) SubscriptionPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionPolicyEvent) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) GlobalPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.GlobalPolicyEvent)

Example 63 with Condition

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

the class AbstractKeyValidationHandler method validate.

private APIKeyValidationInfoDTO validate(APIKeyValidationInfoDTO infoDTO, String apiTenantDomain, int tenantId, SubscriptionDataStore datastore, API api, ApplicationKeyMapping key, Application app, Subscription sub, String keyManager) {
    String subscriptionStatus = sub.getSubscriptionState();
    String type = key.getKeyType();
    if (APIConstants.SubscriptionStatus.BLOCKED.equals(subscriptionStatus)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
        infoDTO.setAuthorized(false);
        return infoDTO;
    } else if (APIConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus) || APIConstants.SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
        infoDTO.setAuthorized(false);
        return infoDTO;
    } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subscriptionStatus) && !APIConstants.API_KEY_TYPE_SANDBOX.equals(type)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
        infoDTO.setType(type);
        infoDTO.setAuthorized(false);
        return infoDTO;
    }
    infoDTO.setTier(sub.getPolicyId());
    infoDTO.setSubscriber(app.getSubName());
    infoDTO.setApplicationId(app.getId().toString());
    infoDTO.setApiName(api.getApiName());
    infoDTO.setApiVersion(api.getApiVersion());
    infoDTO.setApiPublisher(api.getApiProvider());
    infoDTO.setApplicationName(app.getName());
    infoDTO.setApplicationTier(app.getPolicy());
    infoDTO.setApplicationUUID(app.getUUID());
    infoDTO.setAppAttributes(app.getAttributes());
    infoDTO.setType(type);
    // Advanced Level Throttling Related Properties
    String apiTier = api.getApiTier();
    String subscriberTenant = MultitenantUtils.getTenantDomain(app.getSubName());
    ApplicationPolicy appPolicy = datastore.getApplicationPolicyByName(app.getPolicy(), APIUtil.getTenantIdFromTenantDomain(app.getOrganization()));
    if (appPolicy == null) {
        try {
            appPolicy = new SubscriptionDataLoaderImpl().getApplicationPolicy(app.getPolicy(), app.getOrganization());
            datastore.addOrUpdateApplicationPolicy(appPolicy);
        } catch (DataLoadingException e) {
            log.error("Error while loading ApplicationPolicy");
        }
    }
    SubscriptionPolicy subPolicy = datastore.getSubscriptionPolicyByName(sub.getPolicyId(), tenantId);
    if (subPolicy == null) {
        try {
            subPolicy = new SubscriptionDataLoaderImpl().getSubscriptionPolicy(sub.getPolicyId(), apiTenantDomain);
            datastore.addOrUpdateSubscriptionPolicy(subPolicy);
        } catch (DataLoadingException e) {
            log.error("Error while loading SubscriptionPolicy");
        }
    }
    ApiPolicy apiPolicy = datastore.getApiPolicyByName(api.getApiTier(), tenantId);
    boolean isContentAware = false;
    if (appPolicy.isContentAware() || subPolicy.isContentAware() || (apiPolicy != null && apiPolicy.isContentAware())) {
        isContentAware = true;
    }
    infoDTO.setContentAware(isContentAware);
    // TODO this must implement as a part of throttling implementation.
    int spikeArrest = 0;
    String apiLevelThrottlingKey = "api_level_throttling_key";
    if (subPolicy.getRateLimitCount() > 0) {
        spikeArrest = subPolicy.getRateLimitCount();
    }
    String spikeArrestUnit = null;
    if (subPolicy.getRateLimitTimeUnit() != null) {
        spikeArrestUnit = subPolicy.getRateLimitTimeUnit();
    }
    boolean stopOnQuotaReach = subPolicy.isStopOnQuotaReach();
    int graphQLMaxDepth = 0;
    if (subPolicy.getGraphQLMaxDepth() > 0) {
        graphQLMaxDepth = subPolicy.getGraphQLMaxDepth();
    }
    int graphQLMaxComplexity = 0;
    if (subPolicy.getGraphQLMaxComplexity() > 0) {
        graphQLMaxComplexity = subPolicy.getGraphQLMaxComplexity();
    }
    List<String> list = new ArrayList<String>();
    list.add(apiLevelThrottlingKey);
    infoDTO.setSpikeArrestLimit(spikeArrest);
    infoDTO.setSpikeArrestUnit(spikeArrestUnit);
    infoDTO.setStopOnQuotaReach(stopOnQuotaReach);
    infoDTO.setSubscriberTenantDomain(subscriberTenant);
    infoDTO.setGraphQLMaxDepth(graphQLMaxDepth);
    infoDTO.setGraphQLMaxComplexity(graphQLMaxComplexity);
    if (apiTier != null && apiTier.trim().length() > 0) {
        infoDTO.setApiTier(apiTier);
    }
    // We also need to set throttling data list associated with given API. This need to have
    // policy id and
    // condition id list for all throttling tiers associated with this API.
    infoDTO.setThrottlingDataList(list);
    infoDTO.setAuthorized(true);
    return infoDTO;
}
Also used : SubscriptionDataLoaderImpl(org.wso2.carbon.apimgt.keymgt.model.impl.SubscriptionDataLoaderImpl) DataLoadingException(org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException) SubscriptionPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationPolicy) ApiPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy) ArrayList(java.util.ArrayList)

Example 64 with Condition

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

the class ThrottleConditionEvaluatorTest method testGetThrottledInConditionWithJWTCondition.

@Test
public void testGetThrottledInConditionWithJWTCondition() {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnableJwtConditions(true);
    String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3c28yLm9yZy9wcm9kdWN0cy9hbSIsImV4cCI6MTM0NTE4MzQ5MjE4MSwiaHR0cDov" + "L3dzbzIub3JnL2NsYWltcy9hYmMiOiJjZGUiLCJodHRwOi8vd3NvMi5vcmcvY2xhaW1zL2JjZCI6Inh5eiJ9.9zGU062DJ5mQ5hne" + "41h4IRpLbaY_b5thRxb3feebOcA";
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setCallerToken(jwt);
    ServiceReferenceHolder.getInstance().setThrottleProperties(throttleProperties);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    Map<String, List<ConditionDto>> conditionMap = new HashMap<>();
    conditionMap.put("condition1", Arrays.asList(new ConditionDto[] { getJWTCondition(false) }));
    conditionMap.put("default", Arrays.asList(new ConditionDto[] { getJWTCondition(false) }));
    String condition = throttleConditionEvaluator.getThrottledInCondition(messageContext, authenticationContext, conditionMap);
    Assert.assertEquals(condition, "condition1");
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) HashMap(java.util.HashMap) ConditionDto(org.wso2.carbon.apimgt.impl.dto.ConditionDto) List(java.util.List) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Test(org.junit.Test)

Example 65 with Condition

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

the class ThrottleConditionEvaluatorTest method testGetThrottledInConditionWithIPConditionWithDefaultWithInvert.

@Test
public void testGetThrottledInConditionWithIPConditionWithDefaultWithInvert() {
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    Map map = new TreeMap();
    map.put("X-Forwarded-For", "127.0.0.2");
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, map);
    Map<String, List<ConditionDto>> conditionMap = new HashMap<>();
    conditionMap.put("condition1", Arrays.asList(new ConditionDto[] { getIPCondition(true) }));
    conditionMap.put("default", Arrays.asList(new ConditionDto[] { getIPCondition(true) }));
    String condition = throttleConditionEvaluator.getThrottledInCondition(messageContext, null, conditionMap);
    Assert.assertEquals(condition, "condition1");
}
Also used : HashMap(java.util.HashMap) ConditionDto(org.wso2.carbon.apimgt.impl.dto.ConditionDto) List(java.util.List) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map) Test(org.junit.Test)

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