Search in sources :

Example 56 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class APIKeyCacheTestCase method testAPIKeyCache.

@Test
public void testAPIKeyCache() {
    APIKeyCache apiKeyCache = new APIKeyCache(2, 2);
    APIKeyValidationInfoDTO apiKeyValidationInfoDTOValid = new APIKeyValidationInfoDTO();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTOInvalid = new APIKeyValidationInfoDTO();
    apiKeyCache.addValidKey("validKey", apiKeyValidationInfoDTOValid);
    apiKeyCache.addInvalidKey("invalidKey", apiKeyValidationInfoDTOInvalid);
    apiKeyCache.getInfo("validKey");
    apiKeyCache.getInfo("key");
    apiKeyCache.invalidateEntry("validKey");
    apiKeyCache.invalidateCache();
}
Also used : APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Test(org.junit.Test)

Example 57 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class WebsocketUtil method validateCache.

/**
 * validate access token via cache
 *
 * @param apiKey access token
 * @param cacheKey key of second level cache
 * @return APIKeyValidationInfoDTO
 */
public static APIKeyValidationInfoDTO validateCache(String apiKey, String cacheKey) {
    // Get the access token from the first level cache.
    String cachedToken = (String) getGatewayTokenCache().get(apiKey);
    // If the access token exists in the first level cache.
    if (cachedToken != null) {
        APIKeyValidationInfoDTO info = (APIKeyValidationInfoDTO) getGatewayKeyCache().get(cacheKey);
        if (info != null) {
            if (APIUtil.isAccessTokenExpired(info)) {
                info.setAuthorized(false);
                // in cache, if token is expired  remove cache entry.
                getGatewayKeyCache().remove(cacheKey);
                // Remove from the first level token cache as well.
                getGatewayTokenCache().remove(apiKey);
            }
            return info;
        }
    }
    return null;
}
Also used : APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 58 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validateSubscription.

@Override
public APIKeyValidationInfoDTO validateSubscription(String apiContext, String apiVersion, int appId) {
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    try {
        if (log.isDebugEnabled()) {
            log.debug("Before validating subscriptions");
            log.debug("Validation Info : { context : " + apiContext + " , " + "version : " + apiVersion + " , appId : " + appId + " }");
        }
        validateSubscriptionDetails(apiContext, apiVersion, appId, apiKeyValidationInfoDTO);
        if (log.isDebugEnabled()) {
            log.debug("After validating subscriptions");
        }
    } catch (APIManagementException e) {
        log.error("Error Occurred while validating subscription.", e);
    }
    return apiKeyValidationInfoDTO;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 59 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validateSubscriptionDetails.

private APIKeyValidationInfoDTO validateSubscriptionDetails(APIKeyValidationInfoDTO infoDTO, String context, String version, String consumerKey, String keyManager, boolean defaultVersionInvoked) {
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    API api = null;
    ApplicationKeyMapping key = null;
    Application app = null;
    Subscription sub = null;
    SubscriptionDataStore datastore = SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(apiTenantDomain);
    // TODO add a check to see whether datastore is initialized an load data using rest api if it is not loaded
    if (datastore != null) {
        api = datastore.getApiByContextAndVersion(context, version);
        if (api != null) {
            key = datastore.getKeyMappingByKeyAndKeyManager(consumerKey, keyManager);
            if (key != null) {
                app = datastore.getApplicationById(key.getApplicationId());
                if (app != null) {
                    sub = datastore.getSubscriptionById(app.getId(), api.getApiId());
                    if (sub != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("All information is retrieved from the inmemory data store.");
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Valid subscription not found for appId " + app.getId() + " and apiId " + api.getApiId());
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Application not found in the datastore for id " + key.getApplicationId());
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Application keymapping not found in the datastore for id consumerKey " + consumerKey);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("API not found in the datastore for " + context + ":" + version);
            }
        }
    } else {
        log.error("Subscription datastore is not initialized for tenant domain " + apiTenantDomain);
    }
    if (api != null && app != null && key != null && sub != null) {
        validate(infoDTO, apiTenantDomain, tenantId, datastore, api, key, app, sub, keyManager);
    } else if (!infoDTO.isAuthorized() && infoDTO.getValidationStatus() == 0) {
        // Scenario where validation failed and message is not set
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    } else {
        infoDTO.setAuthorized(false);
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    }
    return infoDTO;
}
Also used : API(org.wso2.carbon.apimgt.keymgt.model.entity.API) SubscriptionDataStore(org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore) Subscription(org.wso2.carbon.apimgt.keymgt.model.entity.Subscription) Application(org.wso2.carbon.apimgt.keymgt.model.entity.Application) ApplicationKeyMapping(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMapping)

Example 60 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validate.

private APIKeyValidationInfoDTO validate(APIKeyValidationInfoDTO infoDTO, String apiTenantDomain, int tenantId, SubscriptionDataStore datastore, API api, Application app, Subscription sub) {
    String subscriptionStatus = sub.getSubscriptionState();
    String type = app.getTokenType();
    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 subscriberUserId = sub.getSubscriptionId();
    String subscriberTenant = MultitenantUtils.getTenantDomain(app.getSubName());
    ApplicationPolicy appPolicy = datastore.getApplicationPolicyByName(app.getPolicy(), tenantId);
    if (appPolicy == null) {
        try {
            appPolicy = new SubscriptionDataLoaderImpl().getApplicationPolicy(app.getPolicy(), apiTenantDomain);
            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)

Aggregations

APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)54 Test (org.junit.Test)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)28 Cache (javax.cache.Cache)19 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)14 HashMap (java.util.HashMap)13 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)12 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)12 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)11 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)11 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)11 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)11 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)10 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)9 MessageContext (org.apache.synapse.MessageContext)9 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)9 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)9 SignedJWT (com.nimbusds.jwt.SignedJWT)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 APIKeyDataStore (org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore)7