Search in sources :

Example 61 with VerbInfoDTO

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

the class BasicAuthAuthenticator method authenticate.

/**
 * Authenticates the given request to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param synCtx The message to be authenticated
 * @return an AuthenticationResponse object which contains the authentication status
 */
@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) {
    if (log.isDebugEnabled()) {
        log.info("Basic Authentication initialized");
    }
    openAPI = (OpenAPI) synCtx.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT);
    if (openAPI == null && !APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        log.error("OpenAPI definition is missing in the gateway. Basic authentication cannot be performed.");
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF, "Basic authentication cannot be performed.");
    }
    // Extract basic authorization header while removing it from the authorization header
    String basicAuthHeader = extractBasicAuthHeader(synCtx);
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    // Check for resource level authentication
    String authenticationScheme;
    List<VerbInfoDTO> verbInfoList;
    if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        HashMap<String, Boolean> operationAuthSchemeMappingList = (HashMap<String, Boolean>) synCtx.getProperty(APIConstants.OPERATION_AUTH_SCHEME_MAPPING);
        HashMap<String, String> operationThrottlingMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.OPERATION_THROTTLING_MAPPING);
        String[] operationList = matchingResource.split(",");
        verbInfoList = new ArrayList<>(1);
        authenticationScheme = APIConstants.AUTH_NO_AUTHENTICATION;
        for (String operation : operationList) {
            boolean operationAuthSchemeEnabled = operationAuthSchemeMappingList.get(operation);
            VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
            if (operationAuthSchemeEnabled) {
                verbInfoDTO.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
                authenticationScheme = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
            } else {
                verbInfoDTO.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
            }
            verbInfoDTO.setThrottling(operationThrottlingMappingList.get(operation));
            verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + operation + ":" + httpMethod);
            verbInfoList.add(verbInfoDTO);
        }
    } else {
        authenticationScheme = OpenAPIUtils.getResourceAuthenticationScheme(openAPI, synCtx);
        verbInfoList = new ArrayList<>(1);
        VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
        verbInfoDTO.setAuthType(authenticationScheme);
        verbInfoDTO.setThrottling(OpenAPIUtils.getResourceThrottlingTier(openAPI, synCtx));
        verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + matchingResource + ":" + httpMethod);
        verbInfoList.add(verbInfoDTO);
    }
    String[] credentials;
    try {
        credentials = extractBasicAuthCredentials(basicAuthHeader);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    String username = getEndUserName(credentials[0]);
    String password = credentials[1];
    // If end user tenant domain does not match the API publisher's tenant domain, return error
    if (!MultitenantUtils.getTenantDomain(username).equals(synCtx.getProperty(PUBLISHER_TENANT_DOMAIN))) {
        log.error("Basic Authentication failure: tenant domain mismatch for user :" + username);
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
    }
    BasicAuthValidationInfoDTO basicAuthValidationInfoObj;
    try {
        if (basicAuthCredentialValidator == null) {
            basicAuthCredentialValidator = new BasicAuthCredentialValidator();
        }
        basicAuthValidationInfoObj = basicAuthCredentialValidator.validate(username, password);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    if (!basicAuthValidationInfoObj.isAuthenticated()) {
        log.error("Basic Authentication failure: Username and Password mismatch");
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    } else {
        // username password matches
        if (log.isDebugEnabled()) {
            log.debug("Basic Authentication: Username and Password authenticated");
        }
        // scope validation
        boolean scopesValid = false;
        try {
            scopesValid = basicAuthCredentialValidator.validateScopes(username, openAPI, synCtx, basicAuthValidationInfoObj);
        } catch (APISecurityException ex) {
            return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
        }
        String domainQualifiedUserName = basicAuthValidationInfoObj.getDomainQualifiedUsername();
        if (scopesValid) {
            if (APISecurityUtils.getAuthenticationContext(synCtx) == null) {
                // Create a dummy AuthenticationContext object with hard coded values for
                // Tier and KeyType. This is because we cannot determine the Tier nor Key
                // Type without subscription information..
                AuthenticationContext authContext = new AuthenticationContext();
                authContext.setAuthenticated(true);
                authContext.setTier(APIConstants.UNAUTHENTICATED_TIER);
                authContext.setStopOnQuotaReach(// Since we don't have details on unauthenticated tier we setting stop on quota reach true
                true);
                synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
                // In basic authentication scenario, we will use the username for throttling.
                authContext.setApiKey(domainQualifiedUserName);
                authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
                authContext.setUsername(domainQualifiedUserName);
                authContext.setCallerToken(null);
                authContext.setApplicationName(APIConstants.BASIC_AUTH_APPLICATION_NAME);
                // Set username as application ID in basic auth scenario
                authContext.setApplicationId(domainQualifiedUserName);
                // Set username as application ID in basic auth scenario
                authContext.setApplicationUUID(domainQualifiedUserName);
                // Set application owner in basic auth scenario
                authContext.setSubscriber(APIConstants.BASIC_AUTH_APPLICATION_OWNER);
                authContext.setConsumerKey(null);
                authContext.setApiTier(apiLevelPolicy);
                APISecurityUtils.setAuthenticationContext(synCtx, authContext, null);
            }
            log.debug("Basic Authentication: Scope validation passed");
            return new AuthenticationResponse(true, isMandatory, false, 0, null);
        }
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) HashMap(java.util.HashMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) BasicAuthValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.BasicAuthValidationInfoDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 62 with VerbInfoDTO

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

the class ThrottleHandler method doRoleBasedAccessThrottlingWithCEP.

/**
 * This method is responsible for throttle incoming messages. This method will perform Application, Subscription
 * and Resource level throttling.
 *
 * @param synCtx Synapse message context that contains message details.
 * @param cc     Configuration context which holds current configuration context.
 * @return
 */
private boolean doRoleBasedAccessThrottlingWithCEP(MessageContext synCtx, ConfigurationContext cc, AuthenticationContext authenticationContext) {
    // Throttle Keys
    // applicationLevelThrottleKey key is combination of {applicationId}:{authorizedUser}
    String applicationLevelThrottleKey;
    // subscriptionLevelThrottleKey key for an api subscription is combination of {applicationId}:{apiContext}:{apiVersion}
    // subscriptionLevelThrottleKey key for an api subscription is combination of {applicationId}:{productName}:{productProvider}
    // Todo: add product version to key when versioning is supported
    String subscriptionLevelThrottleKey;
    // The key is combination of {apiContext}/ {apiVersion}{resourceUri}:{httpMethod} if policy is user level then authorized user will append at end
    String resourceLevelThrottleKey = "";
    // apiLevelThrottleKey key is combination of {apiContext}:{apiVersion}
    String apiLevelThrottleKey;
    // Throttle Tiers
    String applicationLevelTier;
    String subscriptionLevelTier;
    String resourceLevelTier = "";
    String apiLevelTier;
    // Other Relevant parameters
    AuthenticationContext authContext = authenticationContext;
    String authorizedUser;
    // Throttled decisions
    boolean isThrottled = false;
    boolean isResourceLevelThrottled = false;
    boolean isOperationLevelThrottled = false;
    boolean isApplicationLevelThrottled;
    boolean isSubscriptionLevelThrottled;
    boolean isSubscriptionLevelSpikeThrottled = false;
    boolean isApiLevelThrottled = false;
    boolean isBlockedRequest = false;
    boolean apiLevelThrottledTriggered = false;
    boolean policyLevelUserTriggered = false;
    String ipLevelBlockingKey;
    String appLevelBlockingKey = "";
    String subscriptionLevelBlockingKey = "";
    boolean stopOnQuotaReach = true;
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    apiContext = apiContext != null ? apiContext : "";
    apiVersion = apiVersion != null ? apiVersion : "";
    String clientIp = GatewayUtils.getClientIp(synCtx);
    String subscriberTenantDomain = "";
    String apiTenantDomain = getTenantDomain();
    ConditionGroupDTO[] conditionGroupDTOs;
    String applicationId = authContext.getApplicationId();
    // If Authz context is not null only we can proceed with throttling
    if (authContext != null) {
        authorizedUser = authContext.getUsername();
        // Check if the tenant domain is appended with authorizedUser and append if it is not there
        if (!StringUtils.contains(authorizedUser, apiTenantDomain)) {
            authorizedUser = authContext.getUsername() + "@" + apiTenantDomain;
        }
        // Do blocking if there are blocking conditions present
        if (getThrottleDataHolder().isBlockingConditionsPresent()) {
            appLevelBlockingKey = authContext.getSubscriber() + ":" + authContext.getApplicationName();
            subscriptionLevelBlockingKey = apiContext + ":" + apiVersion + ":" + authContext.getSubscriber() + "-" + authContext.getApplicationName() + ":" + authContext.getKeyType();
            Timer timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), BLOCKED_TEST));
            Timer.Context context = timer.start();
            isBlockedRequest = getThrottleDataHolder().isRequestBlocked(apiContext, appLevelBlockingKey, authorizedUser, clientIp, apiTenantDomain, subscriptionLevelBlockingKey);
            context.stop();
        }
        if (isBlockedRequest) {
            String msg = "Request blocked as it violates defined blocking conditions, for API: " + apiContext + " ,application:" + appLevelBlockingKey + " ,user:" + authorizedUser;
            if (log.isDebugEnabled()) {
                log.debug(msg);
            }
            synCtx.setProperty(APIThrottleConstants.BLOCKED_REASON, msg);
            synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.REQUEST_BLOCKED);
            isThrottled = true;
        } else {
            subscriberTenantDomain = authContext.getSubscriberTenantDomain();
            applicationLevelThrottleKey = applicationId + ":" + authorizedUser;
            apiLevelThrottleKey = apiContext + ":" + apiVersion;
            stopOnQuotaReach = authContext.isStopOnQuotaReach();
            applicationLevelTier = authContext.getApplicationTier();
            subscriptionLevelTier = authContext.getTier();
            apiLevelTier = authContext.getApiTier();
            VerbInfoDTO throttledResource = new VerbInfoDTO();
            // If request is not blocked then only we perform throttling.
            List<VerbInfoDTO> verbInfoDTOList = (List<VerbInfoDTO>) synCtx.getProperty(APIConstants.VERB_INFO_DTO);
            // If API level tier is not present only we should move to resource level tiers.
            if (verbInfoDTOList == null) {
                log.warn("Error while getting throttling information for resource and http verb");
                return false;
            }
            for (VerbInfoDTO verbInfoDTO : verbInfoDTOList) {
                boolean isUnlimittedTier = false;
                resourceLevelThrottleKey = verbInfoDTO.getRequestKey();
                resourceLevelTier = verbInfoDTO.getThrottling();
                if (APIConstants.UNLIMITED_TIER.equalsIgnoreCase(resourceLevelTier)) {
                    isUnlimittedTier = true;
                }
                // If API level throttle policy is present then it will apply and no resource level policy will apply for it
                if (!StringUtils.isEmpty(apiLevelTier) && !APIConstants.UNLIMITED_TIER.equalsIgnoreCase(apiLevelTier)) {
                    resourceLevelThrottleKey = apiLevelThrottleKey;
                    apiLevelThrottledTriggered = true;
                }
                // If verbInfo is present then only we will do resource level throttling
                if (isUnlimittedTier && !apiLevelThrottledTriggered) {
                    // If unlimited tier throttling will not apply at resource level and pass it
                    if (log.isDebugEnabled()) {
                        log.debug("Resource level throttling set as unlimited and request will pass " + "resource level");
                    }
                } else {
                    if (APIConstants.API_POLICY_USER_LEVEL.equalsIgnoreCase(verbInfoDTO.getApplicableLevel())) {
                        resourceLevelThrottleKey = resourceLevelThrottleKey + "_" + authorizedUser;
                        policyLevelUserTriggered = true;
                    }
                    // If tier is not unlimited only throttling will apply.
                    List<String> resourceLevelThrottleConditions = new ArrayList<>();
                    resourceLevelThrottleConditions = verbInfoDTO.getThrottlingConditions();
                    conditionGroupDTOs = verbInfoDTO.getConditionGroups();
                    Timer timer1 = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), RESOURCE_THROTTLE));
                    Timer.Context context1 = timer1.start();
                    if (getThrottleDataHolder().isAPIThrottled(resourceLevelThrottleKey)) {
                        if (getThrottleDataHolder().isConditionsAvailable(resourceLevelThrottleKey)) {
                            Map<String, List<ConditionDto>> conditionDtoMap = getThrottleDataHolder().getConditionDtoMap(resourceLevelThrottleKey);
                            if (log.isDebugEnabled()) {
                                log.debug("Conditions available" + conditionDtoMap.size());
                            }
                            String throttledCondition = getThrottleConditionEvaluator().getThrottledInCondition(synCtx, authContext, conditionDtoMap);
                            if (StringUtils.isNotEmpty(throttledCondition)) {
                                if (log.isDebugEnabled()) {
                                    log.debug("Throttled with Condition :" + throttledCondition);
                                }
                                String combinedResourceLevelThrottleKey = resourceLevelThrottleKey + "_" + throttledCondition;
                                if (log.isDebugEnabled()) {
                                    log.debug("Checking condition : " + combinedResourceLevelThrottleKey);
                                }
                                if (getThrottleDataHolder().isThrottled(combinedResourceLevelThrottleKey)) {
                                    if (!apiLevelThrottledTriggered) {
                                        isResourceLevelThrottled = isThrottled = true;
                                    } else {
                                        isApiLevelThrottled = isThrottled = true;
                                    }
                                    long timestamp = getThrottleDataHolder().getThrottleNextAccessTimestamp(combinedResourceLevelThrottleKey);
                                    synCtx.setProperty(APIThrottleConstants.THROTTLED_NEXT_ACCESS_TIMESTAMP, timestamp);
                                }
                            }
                        } else {
                            if (conditionGroupDTOs != null && conditionGroupDTOs.length > 0) {
                                if (log.isDebugEnabled()) {
                                    log.debug("Evaluating Conditional Groups for " + apiLevelThrottleKey);
                                }
                                // Then we will apply resource level throttling
                                List<ConditionGroupDTO> applicableConditions = getThrottleConditionEvaluator().getApplicableConditions(synCtx, authContext, conditionGroupDTOs);
                                for (ConditionGroupDTO conditionGroup : applicableConditions) {
                                    String combinedResourceLevelThrottleKey = resourceLevelThrottleKey + conditionGroup.getConditionGroupId();
                                    if (log.isDebugEnabled()) {
                                        log.debug("Checking condition : " + combinedResourceLevelThrottleKey);
                                    }
                                    if (getThrottleDataHolder().isThrottled(combinedResourceLevelThrottleKey)) {
                                        if (!apiLevelThrottledTriggered) {
                                            isResourceLevelThrottled = isThrottled = true;
                                        } else {
                                            isApiLevelThrottled = isThrottled = true;
                                        }
                                        long timestamp = getThrottleDataHolder().getThrottleNextAccessTimestamp(combinedResourceLevelThrottleKey);
                                        synCtx.setProperty(APIThrottleConstants.THROTTLED_NEXT_ACCESS_TIMESTAMP, timestamp);
                                        break;
                                    }
                                }
                            } else {
                                log.warn("Unable to find throttling information for resource and http verb. Throttling " + "will not be applied");
                            }
                        }
                    }
                    context1.stop();
                    if (isThrottled) {
                        throttledResource = verbInfoDTO;
                        break;
                    }
                }
            }
            if (!isApiLevelThrottled) {
                Timer timer2 = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), RESOURCE_THROTTLE));
                Timer.Context context2 = timer2.start();
                // if resource level not throttled then move to subscription level
                if (!isResourceLevelThrottled) {
                    // Subscription Level Throttling
                    subscriptionLevelThrottleKey = getSubscriptionLevelThrottleKey(subscriptionLevelTier, authContext, apiContext, apiVersion);
                    isSubscriptionLevelThrottled = getThrottleDataHolder().isThrottled(subscriptionLevelThrottleKey);
                    if (!isSubscriptionLevelThrottled && authContext.getSpikeArrestLimit() > 0) {
                        isSubscriptionLevelSpikeThrottled = isSubscriptionLevelSpike(synCtx, subscriptionLevelThrottleKey);
                    }
                    // Stop on quata reach
                    if (!isSubscriptionLevelThrottled && !isSubscriptionLevelSpikeThrottled) {
                        // Application Level Throttling
                        isApplicationLevelThrottled = getThrottleDataHolder().isThrottled(applicationLevelThrottleKey);
                        // if application level not throttled means it does not throttled at any level.
                        if (!isApplicationLevelThrottled) {
                            for (VerbInfoDTO verbInfo : verbInfoDTOList) {
                                resourceLevelThrottleKey = verbInfo.getRequestKey();
                                resourceLevelTier = verbInfo.getThrottling();
                                boolean keyTemplatesAvailable = getThrottleDataHolder().isKeyTemplatesPresent();
                                if (!keyTemplatesAvailable || !validateCustomPolicy(authorizedUser, applicationLevelThrottleKey, resourceLevelThrottleKey, apiLevelThrottleKey, subscriptionLevelThrottleKey, apiContext, apiVersion, subscriberTenantDomain, apiTenantDomain, applicationId, clientIp, getThrottleDataHolder().getKeyTemplateMap(), synCtx)) {
                                    // publish event to Global Policy Server
                                    if (isHardLimitThrottled(synCtx, authContext, apiContext, apiVersion)) {
                                        isThrottled = true;
                                    } else {
                                        ServiceReferenceHolder.getInstance().getThrottleDataPublisher().publishNonThrottledEvent(applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, subscriberTenantDomain, apiTenantDomain, applicationId, synCtx, authContext);
                                    }
                                } else {
                                    log.debug("Request throttled at custom throttling");
                                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.CUSTOM_POLICY_LIMIT_EXCEED);
                                    isThrottled = true;
                                }
                            }
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("Request throttled at application level for throttle key" + applicationLevelThrottleKey);
                            }
                            synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                            long timestamp = getThrottleDataHolder().getThrottleNextAccessTimestamp(applicationLevelThrottleKey);
                            synCtx.setProperty(APIThrottleConstants.THROTTLED_NEXT_ACCESS_TIMESTAMP, timestamp);
                            isThrottled = isApplicationLevelThrottled = true;
                        }
                    } else {
                        if (!stopOnQuotaReach) {
                            // limit has reached.
                            if (synCtx.getProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY) == null) {
                                synCtx.setProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY, Boolean.TRUE);
                            }
                            isThrottled = false;
                            if (log.isDebugEnabled()) {
                                log.debug("Request throttled at subscription level for throttle key" + subscriptionLevelThrottleKey + ". But subscription policy " + subscriptionLevelTier + " allows to continue to serve requests");
                            }
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("Request throttled at subscription level for throttle key" + subscriptionLevelThrottleKey);
                            }
                            if (!isSubscriptionLevelSpikeThrottled) {
                                long timestamp = getThrottleDataHolder().getThrottleNextAccessTimestamp(subscriptionLevelThrottleKey);
                                synCtx.setProperty(APIThrottleConstants.THROTTLED_NEXT_ACCESS_TIMESTAMP, timestamp);
                                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.SUBSCRIPTION_LIMIT_EXCEEDED);
                            }
                            isThrottled = true;
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Request throttled at resource level for throttle key" + throttledResource.getRequestKey());
                    }
                    // is throttled and resource level throttling
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                }
                context2.stop();
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Request throttled at api level for throttle key" + apiLevelThrottleKey);
                    if (policyLevelUserTriggered) {
                        log.debug("Request has throttled out in the user level for the throttle key" + apiLevelThrottleKey);
                    }
                }
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
            }
        }
    }
    // if we need to publish throttled level or some other information we can do it here. Just before return.
    return isThrottled;
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ArrayList(java.util.ArrayList) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) Timer(org.wso2.carbon.metrics.manager.Timer) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) List(java.util.List) ArrayList(java.util.ArrayList)

Example 63 with VerbInfoDTO

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

the class HandshakeProcessor method setResourcesMapToContext.

/**
 * Set the resource map with VerbInfoDTOs to the context using URL mappings from the InboundMessageContext.
 *
 * @param inboundMessageContext InboundMessageContext
 */
private void setResourcesMapToContext(InboundMessageContext inboundMessageContext) {
    List<URLMapping> urlMappings = inboundMessageContext.getElectedAPI().getResources();
    Map<String, ResourceInfoDTO> resourcesMap = inboundMessageContext.getResourcesMap();
    ResourceInfoDTO resourceInfoDTO;
    VerbInfoDTO verbInfoDTO;
    for (URLMapping urlMapping : urlMappings) {
        resourceInfoDTO = resourcesMap.get(urlMapping.getUrlPattern());
        if (resourceInfoDTO == null) {
            resourceInfoDTO = new ResourceInfoDTO();
            resourceInfoDTO.setUrlPattern(urlMapping.getUrlPattern());
            resourceInfoDTO.setHttpVerbs(new LinkedHashSet<>());
            resourcesMap.put(urlMapping.getUrlPattern(), resourceInfoDTO);
        }
        verbInfoDTO = new VerbInfoDTO();
        verbInfoDTO.setHttpVerb(urlMapping.getHttpMethod());
        verbInfoDTO.setAuthType(urlMapping.getAuthScheme());
        verbInfoDTO.setThrottling(urlMapping.getThrottlingPolicy());
        resourceInfoDTO.getHttpVerbs().add(verbInfoDTO);
    }
}
Also used : URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) ResourceInfoDTO(org.wso2.carbon.apimgt.impl.dto.ResourceInfoDTO)

Example 64 with VerbInfoDTO

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

the class SseApiHandler method getThrottlingInfo.

private ThrottleInfo getThrottlingInfo(AuthenticationContext authenticationContext, MessageContext synCtx) {
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    List<VerbInfoDTO> verbInfoList = (List<VerbInfoDTO>) synCtx.getProperty(APIConstants.VERB_INFO_DTO);
    String resourceLevelThrottleKey = null;
    String resourceLevelTier = null;
    if (verbInfoList != null) {
        // for sse, there will be only one verb info list
        VerbInfoDTO verbInfoDTO = verbInfoList.get(0);
        resourceLevelThrottleKey = verbInfoDTO.getRequestKey();
        resourceLevelTier = verbInfoDTO.getThrottling();
    }
    String remoteIP = GatewayUtils.getIp(axis2MC);
    ThrottleInfo throttleInfo = new ThrottleInfo(authenticationContext, apiContext, apiVersion, resourceLevelThrottleKey, resourceLevelTier, remoteIP);
    axis2MC.setProperty(SSE_THROTTLE_DTO, throttleInfo);
    return throttleInfo;
}
Also used : ThrottleInfo(org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.throttling.ThrottleInfo) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) List(java.util.List) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 65 with VerbInfoDTO

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

the class APIKeyValidatorTestCase method testGetVerbInfoDTOFromAPIData.

/*
     * Test method for getVerbInfoDTOFromAPIData()
     * */
@Test
public void testGetVerbInfoDTOFromAPIData() throws Exception {
    String context = "/";
    String apiVersion = "1.0";
    String requestPath = "/menu";
    String httpMethod = "GET";
    VerbInfoDTO verbDTO = getDefaultVerbInfoDTO();
    verbDTO.setRequestKey("//1.0/:https");
    APIKeyValidator apiKeyValidator = createAPIKeyValidator(true, getDefaultURITemplates("/menu", "GET"), verbDTO);
    // If isAPIResourceValidationEnabled==true
    apiKeyValidator.setGatewayAPIResourceValidationEnabled(true);
    PowerMockito.mockStatic(Cache.class);
    Cache cache = Mockito.mock(Cache.class);
    PowerMockito.mockStatic(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIManagerConfigurationService.class);
    PowerMockito.mockStatic(CacheProvider.class);
    org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
    final APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    PowerMockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    CacheProvider cacheProvider = Mockito.mock(CacheProvider.class);
    PowerMockito.when(cacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);
    Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
    VerbInfoDTO verbInfoDTO1 = new VerbInfoDTO();
    verbInfoDTO1.setHttpVerb("get");
    Mockito.when(APIUtil.getAPIInfoDTOCacheKey("", "1.0")).thenReturn("abc");
    Mockito.when((VerbInfoDTO) CacheProvider.getResourceCache().get("abc")).thenReturn(verbInfoDTO1);
    MessageContext messageContext = Mockito.mock(MessageContext.class);
    VerbInfoDTO verbInfoDTOFromAPIData = apiKeyValidator.getVerbInfoDTOFromAPIData(messageContext, context, apiVersion, requestPath, httpMethod);
    Assert.assertEquals("", verbDTO, verbInfoDTOFromAPIData);
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) CacheProvider(org.wso2.carbon.apimgt.impl.caching.CacheProvider) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)51 Test (org.junit.Test)47 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)41 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)37 MessageContext (org.apache.synapse.MessageContext)34 ArrayList (java.util.ArrayList)33 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)15 ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)14 InboundProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO)13 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)12 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)12 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)11 TreeMap (java.util.TreeMap)8 GraphQLProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO)7 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)7 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)7 GraphQLOperationDTO (org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO)6 GraphQLSchema (graphql.schema.GraphQLSchema)5 SchemaParser (graphql.schema.idl.SchemaParser)5