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);
}
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");
}
}
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;
}
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");
}
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");
}
Aggregations