Search in sources :

Example 16 with APIKeyValidationInfoDTO

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

the class AbstractKeyValidationHandler method validateSubscription.

@Override
public boolean validateSubscription(TokenValidationContext validationContext) throws APIKeyMgtException {
    if (validationContext == null || validationContext.getValidationInfoDTO() == null) {
        return false;
    }
    if (validationContext.isCacheHit()) {
        return true;
    }
    APIKeyValidationInfoDTO dto = validationContext.getValidationInfoDTO();
    if (validationContext.getTokenInfo() != null) {
        if (validationContext.getTokenInfo().isApplicationToken()) {
            dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
        } else {
            dto.setUserType(APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN);
        }
        AccessTokenInfo tokenInfo = validationContext.getTokenInfo();
        // Application Token
        if (!hasTokenRequiredAuthLevel(validationContext.getRequiredAuthenticationLevel(), tokenInfo)) {
            dto.setAuthorized(false);
            dto.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE);
            return false;
        }
    }
    boolean state = false;
    try {
        if (log.isDebugEnabled()) {
            log.debug("Before validating subscriptions : " + dto);
            log.debug("Validation Info : { context : " + validationContext.getContext() + " , " + "version : " + validationContext.getVersion() + " , consumerKey : " + dto.getConsumerKey() + " }");
        }
        state = validateSubscriptionDetails(validationContext.getContext(), validationContext.getVersion(), dto.getConsumerKey(), dto.getKeyManager(), dto);
        if (log.isDebugEnabled()) {
            log.debug("After validating subscriptions : " + dto);
        }
    } catch (APIManagementException e) {
        log.error("Error Occurred while validating subscription.", e);
    }
    return state;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 17 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, int appId, boolean defaultVersionInvoked) {
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    API api = null;
    Subscription sub = null;
    Application app = 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) {
        app = datastore.getApplicationById(appId);
        api = datastore.getApiByContextAndVersion(context, version);
        if (api == null && APIConstants.DEFAULT_WEBSOCKET_VERSION.equals(version)) {
            // for websocket default version.
            api = datastore.getDefaultApiByContext(context);
        }
        if (api != null) {
            sub = datastore.getSubscriptionById(appId, 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 " + appId + " and apiId " + api.getApiId());
                }
            }
        } 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 && sub != null) {
        validate(infoDTO, apiTenantDomain, tenantId, datastore, api, app, sub);
    } 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)

Example 18 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, String consumerKey, String keyManager) {
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    try {
        if (log.isDebugEnabled()) {
            log.debug("Before validating subscriptions");
            log.debug("Validation Info : { context : " + apiContext + " , " + "version : " + apiVersion + " , consumerKey : " + consumerKey + " }");
        }
        validateSubscriptionDetails(apiContext, apiVersion, consumerKey, keyManager, 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 19 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, 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 20 with APIKeyValidationInfoDTO

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

the class DefaultKeyValidationHandler method validateScopes.

@Override
public boolean validateScopes(TokenValidationContext validationContext) throws APIKeyMgtException {
    if (validationContext.isCacheHit()) {
        return true;
    }
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = validationContext.getValidationInfoDTO();
    if (apiKeyValidationInfoDTO == null) {
        throw new APIKeyMgtException("Key Validation information not set");
    }
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    String httpVerb = validationContext.getHttpVerb();
    String[] scopes;
    Set<String> scopesSet = apiKeyValidationInfoDTO.getScopes();
    StringBuilder scopeList = new StringBuilder();
    if (scopesSet != null && !scopesSet.isEmpty()) {
        scopes = scopesSet.toArray(new String[scopesSet.size()]);
        if (log.isDebugEnabled() && scopes != null) {
            for (String scope : scopes) {
                scopeList.append(scope);
                scopeList.append(",");
            }
            scopeList.deleteCharAt(scopeList.length() - 1);
            log.debug("Scopes allowed for token : " + validationContext.getAccessToken() + " : " + scopeList.toString());
        }
    }
    String resourceList = validationContext.getMatchingResource();
    List<String> resourceArray;
    if ((APIConstants.GRAPHQL_QUERY.equalsIgnoreCase(validationContext.getHttpVerb())) || (APIConstants.GRAPHQL_MUTATION.equalsIgnoreCase(validationContext.getHttpVerb())) || (APIConstants.GRAPHQL_SUBSCRIPTION.equalsIgnoreCase(validationContext.getHttpVerb()))) {
        resourceArray = new ArrayList<>(Arrays.asList(resourceList.split(",")));
    } else {
        resourceArray = new ArrayList<>(Arrays.asList(resourceList));
    }
    String actualVersion = validationContext.getVersion();
    // Check if the api version has been prefixed with _default_
    if (actualVersion != null && actualVersion.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
        // Remove the prefix from the version.
        actualVersion = actualVersion.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
    }
    SubscriptionDataStore tenantSubscriptionStore = SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
    API api = tenantSubscriptionStore.getApiByContextAndVersion(validationContext.getContext(), actualVersion);
    boolean scopesValidated = false;
    if (api != null) {
        for (String resource : resourceArray) {
            List<URLMapping> resources = api.getResources();
            URLMapping urlMapping = null;
            for (URLMapping mapping : resources) {
                if (Objects.equals(mapping.getHttpMethod(), httpVerb) || "WS".equalsIgnoreCase(api.getApiType())) {
                    if (isResourcePathMatching(resource, mapping)) {
                        urlMapping = mapping;
                        break;
                    }
                }
            }
            if (urlMapping != null) {
                if (urlMapping.getScopes().size() == 0) {
                    scopesValidated = true;
                    continue;
                }
                List<String> mappingScopes = urlMapping.getScopes();
                boolean validate = false;
                for (String scope : mappingScopes) {
                    if (scopesSet.contains(scope)) {
                        scopesValidated = true;
                        validate = true;
                        break;
                    }
                }
                if (!validate && urlMapping.getScopes().size() > 0) {
                    scopesValidated = false;
                    break;
                }
            }
        }
    }
    if (!scopesValidated) {
        apiKeyValidationInfoDTO.setAuthorized(false);
        apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.INVALID_SCOPE);
    }
    return scopesValidated;
}
Also used : SubscriptionDataStore(org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore) APIKeyMgtException(org.wso2.carbon.apimgt.keymgt.APIKeyMgtException) URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

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