Search in sources :

Example 51 with Tier

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

the class DefaultKeyValidationHandlerTest method testValidateScopes.

@Test
public void testValidateScopes() throws APIKeyMgtException {
    API api = new API();
    api.setApiId(1);
    api.setApiProvider(USER_NAME);
    api.setApiName(API_NAME);
    api.setApiVersion(API_VERSION);
    api.setContext(API_CONTEXT);
    URLMapping urlMapping = new URLMapping();
    urlMapping.addScope(SCOPES);
    urlMapping.setHttpMethod(HTTP_VERB);
    urlMapping.setUrlPattern(RESOURCE);
    api.addResource(urlMapping);
    Map<String, API> apiMap = new HashMap<>();
    String key = API_CONTEXT + ":" + API_VERSION;
    apiMap.put(key, api);
    APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
    dto.setSubscriber(SUBSCRIBER);
    dto.setApplicationName(APPLICATION_NAME);
    dto.setApplicationId(APPLICATION_ID);
    dto.setApplicationTier(TIER);
    Set<String> scopeSet = new HashSet<>();
    scopeSet.add(SCOPES);
    dto.setScopes(scopeSet);
    dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
    // TokenValidationContext for non default API
    TokenValidationContext param1 = new TokenValidationContext();
    param1.setValidationInfoDTO(dto);
    param1.setContext(API_CONTEXT);
    param1.setVersion(API_VERSION);
    param1.setAccessToken(ACCESS_TOKEN);
    param1.setMatchingResource(RESOURCE);
    param1.setHttpVerb(HTTP_VERB);
    // TokenValidationContext for default API version
    TokenValidationContext param2 = new TokenValidationContext();
    param2.setValidationInfoDTO(dto);
    param2.setContext(API_CONTEXT);
    param2.setVersion(DEFAULT_API_VERSION);
    param2.setAccessToken(ACCESS_TOKEN);
    param2.setMatchingResource(RESOURCE);
    param2.setHttpVerb(HTTP_VERB);
    Mockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
    Mockito.when(subscriptionDataHolder.getTenantSubscriptionStore(eq(TENANT_DOMAIN))).thenReturn(tenantSubscriptionStore);
    Mockito.when(tenantSubscriptionStore.getApiByContextAndVersion(eq(API_CONTEXT), eq(API_VERSION))).thenReturn(api);
    DefaultKeyValidationHandler defaultKeyValidationHandler = new DefaultKeyValidationHandler();
    boolean isScopeValidated = defaultKeyValidationHandler.validateScopes(param1);
    boolean isScopeValidated_default = defaultKeyValidationHandler.validateScopes(param2);
    Assert.assertTrue("Scope validation fails for API " + API_NAME, isScopeValidated);
    Assert.assertTrue("Scope validation fails for default API " + API_NAME, isScopeValidated_default);
}
Also used : URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 52 with Tier

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

the class JWTGenerator method populateStandardClaims.

@Override
public Map<String, String> populateStandardClaims(TokenValidationContext validationContext) throws APIManagementException {
    // generating expiring timestamp
    long currentTime = System.currentTimeMillis();
    long expireIn = currentTime + getTTL() * 1000;
    String dialect;
    ClaimsRetriever claimsRetriever = getClaimsRetriever();
    if (claimsRetriever != null) {
        dialect = claimsRetriever.getDialectURI(validationContext.getValidationInfoDTO().getEndUserName());
    } else {
        dialect = getDialectURI();
    }
    // dialect is either empty or '/' do not append a backslash. otherwise append a backslash '/'
    if (!"".equals(dialect) && !"/".equals(dialect)) {
        dialect = dialect + "/";
    }
    String subscriber = validationContext.getValidationInfoDTO().getSubscriber();
    String applicationName = validationContext.getValidationInfoDTO().getApplicationName();
    String applicationId = validationContext.getValidationInfoDTO().getApplicationId();
    String tier = validationContext.getValidationInfoDTO().getTier();
    String endUserName = validationContext.getValidationInfoDTO().getEndUserName();
    String keyType = validationContext.getValidationInfoDTO().getType();
    String userType = validationContext.getValidationInfoDTO().getUserType();
    String applicationTier = validationContext.getValidationInfoDTO().getApplicationTier();
    String enduserTenantId = String.valueOf(APIUtil.getTenantId(endUserName));
    String apiName = validationContext.getValidationInfoDTO().getApiName();
    Application application = getApplicationById(validationContext.getValidationInfoDTO().getSubscriberTenantDomain(), Integer.parseInt(applicationId));
    String uuid = null;
    Map<String, String> appAttributes = null;
    if (application != null) {
        appAttributes = application.getAttributes();
        uuid = application.getUUID();
    }
    Map<String, String> claims = new LinkedHashMap<String, String>(20);
    claims.put("iss", API_GATEWAY_ID);
    claims.put("exp", String.valueOf(expireIn));
    claims.put(dialect + "subscriber", subscriber);
    claims.put(dialect + "applicationid", applicationId);
    claims.put(dialect + "applicationname", applicationName);
    claims.put(dialect + "applicationtier", applicationTier);
    claims.put(dialect + "apiname", apiName);
    claims.put(dialect + "apicontext", validationContext.getContext());
    claims.put(dialect + "version", validationContext.getVersion());
    claims.put(dialect + "tier", tier);
    claims.put(dialect + "keytype", keyType);
    claims.put(dialect + "usertype", userType);
    claims.put(dialect + "enduser", APIUtil.getUserNameWithTenantSuffix(endUserName));
    claims.put(dialect + "enduserTenantId", enduserTenantId);
    claims.put(dialect + "applicationUUId", uuid);
    try {
        if (appAttributes != null && !appAttributes.isEmpty()) {
            String stringAppAttributes = new ObjectMapper().writeValueAsString(appAttributes);
            claims.put(dialect + "applicationAttributes", stringAppAttributes);
        }
    } catch (JsonProcessingException e) {
        log.error("Error in converting Map to String");
    }
    return claims;
}
Also used : ClaimsRetriever(org.wso2.carbon.apimgt.impl.token.ClaimsRetriever) Application(org.wso2.carbon.apimgt.keymgt.model.entity.Application) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LinkedHashMap(java.util.LinkedHashMap)

Example 53 with Tier

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

the class APIUtil method getPolicyByName.

public static Tier getPolicyByName(String policyLevel, String policyName, String organization) throws APIManagementException {
    int tenantId = APIUtil.getInternalOrganizationId(organization);
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    Policy policy;
    if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
        policy = apiMgtDAO.getSubscriptionPolicy(policyName, tenantId);
    } else if (PolicyConstants.POLICY_LEVEL_API.equalsIgnoreCase(policyLevel)) {
        policy = apiMgtDAO.getAPIPolicy(policyName, tenantId);
    } else if (PolicyConstants.POLICY_LEVEL_APP.equalsIgnoreCase(policyLevel)) {
        policy = apiMgtDAO.getApplicationPolicy(policyName, tenantId);
    } else {
        throw new APIManagementException("No such a policy type : " + policyLevel);
    }
    if (policy != null) {
        if (!APIConstants.UNLIMITED_TIER.equalsIgnoreCase(policy.getPolicyName())) {
            Tier tier = new Tier(policy.getPolicyName());
            tier.setDescription(policy.getDescription());
            tier.setDisplayName(policy.getDisplayName());
            Limit limit = policy.getDefaultQuotaPolicy().getLimit();
            tier.setTimeUnit(limit.getTimeUnit());
            tier.setUnitTime(limit.getUnitTime());
            tier.setQuotaPolicyType(policy.getDefaultQuotaPolicy().getType());
            // If the policy is a subscription policy
            if (policy instanceof SubscriptionPolicy) {
                SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) policy;
                tier.setRateLimitCount(subscriptionPolicy.getRateLimitCount());
                tier.setRateLimitTimeUnit(subscriptionPolicy.getRateLimitTimeUnit());
                setBillingPlanAndCustomAttributesToTier(subscriptionPolicy, tier);
                if (StringUtils.equals(subscriptionPolicy.getBillingPlan(), APIConstants.COMMERCIAL_TIER_PLAN)) {
                    tier.setMonetizationAttributes(subscriptionPolicy.getMonetizationPlanProperties());
                }
            }
            if (limit instanceof RequestCountLimit) {
                RequestCountLimit countLimit = (RequestCountLimit) limit;
                tier.setRequestsPerMin(countLimit.getRequestCount());
                tier.setRequestCount(countLimit.getRequestCount());
            } else if (limit instanceof BandwidthLimit) {
                BandwidthLimit bandwidthLimit = (BandwidthLimit) limit;
                tier.setRequestsPerMin(bandwidthLimit.getDataAmount());
                tier.setRequestCount(bandwidthLimit.getDataAmount());
                tier.setBandwidthDataUnit(bandwidthLimit.getDataUnit());
            } else {
                EventCountLimit eventCountLimit = (EventCountLimit) limit;
                tier.setRequestCount(eventCountLimit.getEventCount());
                tier.setRequestsPerMin(eventCountLimit.getEventCount());
            }
            if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
                tier.setTierPlan(((SubscriptionPolicy) policy).getBillingPlan());
            }
            return tier;
        } else {
            if (APIUtil.isEnabledUnlimitedTier()) {
                Tier tier = new Tier(policy.getPolicyName());
                tier.setDescription(policy.getDescription());
                tier.setDisplayName(policy.getDisplayName());
                tier.setRequestsPerMin(Integer.MAX_VALUE);
                tier.setRequestCount(Integer.MAX_VALUE);
                if (isUnlimitedTierPaid(getTenantDomainFromTenantId(tenantId))) {
                    tier.setTierPlan(APIConstants.COMMERCIAL_TIER_PLAN);
                } else {
                    tier.setTierPlan(APIConstants.BILLING_PLAN_FREE);
                }
                return tier;
            }
        }
    }
    return null;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) Limit(org.wso2.carbon.apimgt.api.model.policy.Limit) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)

Example 54 with Tier

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

the class APIUtil method getAPI.

public static API getAPI(GovernanceArtifact artifact) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
        api = new API(apiIdentifier);
        int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
        if (apiId == -1) {
            return null;
        }
        // set uuid
        api.setUUID(artifact.getId());
        api.setRating(getAverageRating(apiId));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
        // ignore
        }
        api.setCacheTimeout(cacheTimeout);
        String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
        api.setApiLevelPolicy(apiLevelTier);
        Set<Tier> availablePolicy = new HashSet<Tier>();
        String[] subscriptionPolicy = ApiMgtDAO.getInstance().getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, replaceEmailDomainBack(providerName));
        List<String> definedPolicyNames = Arrays.asList(subscriptionPolicy);
        String policies = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        if (policies != null && !"".equals(policies)) {
            String[] policyNames = policies.split("\\|\\|");
            for (String policyName : policyNames) {
                if (definedPolicyNames.contains(policyName) || APIConstants.UNLIMITED_TIER.equals(policyName)) {
                    Tier p = new Tier(policyName);
                    availablePolicy.add(p);
                } else {
                    log.warn("Unknown policy: " + policyName + " found on API: " + apiName);
                }
            }
        }
        api.addAvailableTiers(availablePolicy);
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        api.setMonetizationCategory(getAPIMonetizationCategory(availablePolicy, tenantDomainName));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        ArrayList<URITemplate> urlPatternsList;
        urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(api.getContext(), api.getId().getVersion());
        Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
        for (URITemplate uriTemplate : uriTemplates) {
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        }
        api.setUriTemplates(uriTemplates);
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // non empty URLs to API object
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API from artifact ";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 55 with Tier

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

the class APIUtil method getAPIMonetizationCategory.

private static String getAPIMonetizationCategory(Set<Tier> tiers, String tenantDomain) throws APIManagementException {
    boolean isPaidFound = false;
    boolean isFreeFound = false;
    for (Tier tier : tiers) {
        if (isTierPaid(tier.getName(), tenantDomain)) {
            isPaidFound = true;
        } else {
            isFreeFound = true;
            if (isPaidFound) {
                break;
            }
        }
    }
    if (!isPaidFound) {
        return APIConstants.API_CATEGORY_FREE;
    } else if (!isFreeFound) {
        return APIConstants.API_CATEGORY_PAID;
    } else {
        return APIConstants.API_CATEGORY_FREEMIUM;
    }
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier)

Aggregations

Tier (org.wso2.carbon.apimgt.api.model.Tier)108 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 ArrayList (java.util.ArrayList)42 Test (org.junit.Test)40 HashSet (java.util.HashSet)39 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)37 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 API (org.wso2.carbon.apimgt.api.model.API)33 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)32 HashMap (java.util.HashMap)28 Application (org.wso2.carbon.apimgt.api.model.Application)26 Test (org.testng.annotations.Test)22 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)22 Application (org.wso2.carbon.apimgt.core.models.Application)22 LinkedHashSet (java.util.LinkedHashSet)21 JSONObject (org.json.simple.JSONObject)20 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)20 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)20 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 BeforeTest (org.testng.annotations.BeforeTest)19