Search in sources :

Example 36 with VerbInfoDTO

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

the class GraphQLRequestProcessor method handleRequest.

/**
 * Handle inbound websocket requests for GraphQL subscriptions and perform authentication, authorization,
 * payload validation, query depth and complexity analysis and throttling.
 *
 * @param msgSize               Message size of graphQL subscription payload
 * @param msgText               The GraphQL subscription payload text
 * @param inboundMessageContext InboundMessageContext
 * @return InboundProcessorResponseDTO
 */
@Override
public InboundProcessorResponseDTO handleRequest(int msgSize, String msgText, InboundMessageContext inboundMessageContext) {
    InboundProcessorResponseDTO responseDTO;
    JSONObject graphQLMsg = new JSONObject(msgText);
    responseDTO = InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext);
    Parser parser = new Parser();
    // for gql subscription operation payloads
    if (!responseDTO.isError() && checkIfSubscribeMessage(graphQLMsg)) {
        String operationId = graphQLMsg.getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ID);
        if (validatePayloadFields(graphQLMsg)) {
            String graphQLSubscriptionPayload = ((JSONObject) graphQLMsg.get(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_PAYLOAD)).getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_QUERY);
            Document document = parser.parseDocument(graphQLSubscriptionPayload);
            // Extract the operation type and operations from the payload
            OperationDefinition operation = getOperationFromPayload(document);
            if (operation != null) {
                if (checkIfValidSubscribeOperation(operation)) {
                    responseDTO = validateQueryPayload(inboundMessageContext, document, operationId);
                    if (!responseDTO.isError()) {
                        // subscription operation name
                        String subscriptionOperation = GraphQLProcessorUtil.getOperationList(operation, inboundMessageContext.getGraphQLSchemaDTO().getTypeDefinitionRegistry());
                        // extract verb info dto with throttle policy for matching verb
                        VerbInfoDTO verbInfoDTO = InboundWebsocketProcessorUtil.findMatchingVerb(subscriptionOperation, inboundMessageContext);
                        String authType = verbInfoDTO.getAuthType();
                        // validate scopes based on subscription payload when security is enabled
                        if (!StringUtils.capitalize(APIConstants.AUTH_TYPE_NONE.toLowerCase()).equals(authType)) {
                            responseDTO = InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, subscriptionOperation, operationId);
                        }
                        if (!responseDTO.isError()) {
                            SubscriptionAnalyzer subscriptionAnalyzer = new SubscriptionAnalyzer(inboundMessageContext.getGraphQLSchemaDTO().getGraphQLSchema());
                            // analyze query depth and complexity
                            responseDTO = validateQueryDepthAndComplexity(subscriptionAnalyzer, inboundMessageContext, graphQLSubscriptionPayload, operationId);
                            if (!responseDTO.isError()) {
                                // throttle for matching resource
                                responseDTO = InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize, verbInfoDTO, inboundMessageContext, operationId);
                                // add verb info dto for the successful invoking subscription operation request
                                inboundMessageContext.addVerbInfoForGraphQLMsgId(graphQLMsg.getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ID), new GraphQLOperationDTO(verbInfoDTO, subscriptionOperation));
                            }
                        }
                    }
                } else {
                    responseDTO = InboundWebsocketProcessorUtil.getBadRequestGraphQLFrameErrorDTO("Invalid operation. Only allowed Subscription type operations", operationId);
                }
            } else {
                responseDTO = InboundWebsocketProcessorUtil.getBadRequestGraphQLFrameErrorDTO("Operation definition cannot be empty", operationId);
            }
        } else {
            responseDTO = InboundWebsocketProcessorUtil.getBadRequestGraphQLFrameErrorDTO("Invalid operation payload", operationId);
        }
    }
    return responseDTO;
}
Also used : GraphQLOperationDTO(org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO) JSONObject(org.json.JSONObject) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) Document(graphql.language.Document) OperationDefinition(graphql.language.OperationDefinition) SubscriptionAnalyzer(org.wso2.carbon.apimgt.gateway.handlers.graphQL.analyzer.SubscriptionAnalyzer) Parser(graphql.parser.Parser)

Example 37 with VerbInfoDTO

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

the class InboundWebsocketProcessorUtil method doThrottle.

/**
 * Checks if the request is throttled.
 *
 * @param msgSize               Websocket msg size
 * @param verbInfoDTO           VerbInfoDTO for invoking operation. Pass null for websocket API throttling.
 * @param inboundMessageContext InboundMessageContext
 * @return false if throttled
 */
public static InboundProcessorResponseDTO doThrottle(int msgSize, VerbInfoDTO verbInfoDTO, InboundMessageContext inboundMessageContext, InboundProcessorResponseDTO responseDTO) {
    APIKeyValidationInfoDTO infoDTO = inboundMessageContext.getInfoDTO();
    String applicationLevelTier = infoDTO.getApplicationTier();
    String apiLevelTier = infoDTO.getApiTier() == null && verbInfoDTO == null ? APIConstants.UNLIMITED_TIER : infoDTO.getApiTier();
    String subscriptionLevelTier = infoDTO.getTier();
    String resourceLevelTier;
    String authorizedUser;
    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(infoDTO.getSubscriberTenantDomain())) {
        authorizedUser = infoDTO.getSubscriber() + "@" + infoDTO.getSubscriberTenantDomain();
    } else {
        authorizedUser = infoDTO.getSubscriber();
    }
    String apiName = infoDTO.getApiName();
    String apiVersion = inboundMessageContext.getVersion();
    String appTenant = infoDTO.getSubscriberTenantDomain();
    String apiTenant = inboundMessageContext.getTenantDomain();
    String appId = infoDTO.getApplicationId();
    String applicationLevelThrottleKey = appId + ":" + authorizedUser;
    String apiLevelThrottleKey = inboundMessageContext.getApiContext() + ":" + apiVersion;
    String resourceLevelThrottleKey;
    // If API level throttle policy is present then it will apply and no resource level policy will apply for it
    if (StringUtils.isNotEmpty(apiLevelTier) && verbInfoDTO == null) {
        resourceLevelThrottleKey = apiLevelThrottleKey;
        resourceLevelTier = apiLevelTier;
    } else {
        resourceLevelThrottleKey = verbInfoDTO.getRequestKey();
        resourceLevelTier = verbInfoDTO.getThrottling();
    }
    String subscriptionLevelThrottleKey = appId + ":" + inboundMessageContext.getApiContext() + ":" + apiVersion;
    String messageId = UIDGenerator.generateURNString();
    String remoteIP = inboundMessageContext.getUserIP();
    if (log.isDebugEnabled()) {
        log.debug("Remote IP address : " + remoteIP);
    }
    if (remoteIP.indexOf(":") > 0) {
        remoteIP = remoteIP.substring(1, remoteIP.indexOf(":"));
    }
    JSONObject jsonObMap = new JSONObject();
    Utils.setRemoteIp(jsonObMap, remoteIP);
    jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, msgSize);
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
        boolean isThrottled = WebsocketUtil.isThrottled(resourceLevelThrottleKey, subscriptionLevelThrottleKey, applicationLevelThrottleKey);
        if (isThrottled) {
            responseDTO.setError(true);
            responseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR);
            responseDTO.setErrorMessage(WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR_MESSAGE);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    Object[] objects = new Object[] { messageId, applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, inboundMessageContext.getApiContext(), apiVersion, appTenant, apiTenant, appId, apiName, jsonObMap.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event("org.wso2.throttle.request.stream:1.0.0", System.currentTimeMillis(), null, null, objects);
    if (ServiceReferenceHolder.getInstance().getThrottleDataPublisher() == null) {
        log.error("Cannot publish events to traffic manager because ThrottleDataPublisher " + "has not been initialised");
    }
    ServiceReferenceHolder.getInstance().getThrottleDataPublisher().getDataPublisher().tryPublish(event);
    return responseDTO;
}
Also used : JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 38 with VerbInfoDTO

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

the class APIThrottleHandler method doRoleBasedAccessThrottling.

private boolean doRoleBasedAccessThrottling(MessageContext synCtx, ConfigurationContext cc) {
    boolean canAccess = true;
    ThrottleDataHolder dataHolder = (ThrottleDataHolder) cc.getPropertyNonReplicable(ThrottleConstants.THROTTLE_INFO_KEY);
    if (throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY) == null) {
        // skip role base throttling
        return true;
    }
    ConcurrentAccessController cac = null;
    if (isClusteringEnable) {
        // for clustered  env.,gets it from axis configuration context
        cac = (ConcurrentAccessController) cc.getProperty(key);
    }
    if (!synCtx.isResponse()) {
        // gets the remote caller role name
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        String accessToken;
        String consumerKey;
        String authorizedUser;
        String roleID;
        String applicationId;
        String applicationTier;
        if (authContext != null) {
            // Although the method says getApiKey, what is actually returned is the Bearer header (accessToken)
            accessToken = authContext.getApiKey();
            consumerKey = authContext.getConsumerKey();
            authorizedUser = authContext.getUsername();
            roleID = authContext.getTier();
            applicationTier = authContext.getApplicationTier();
            applicationId = authContext.getApplicationId();
            if (accessToken == null || roleID == null) {
                log.warn("No consumer key or role information found on the request - " + "Throttling not applied");
                return true;
            }
        } else {
            log.warn("No authentication context information found on the request - " + "Throttling not applied");
            return true;
        }
        // Domain name based throttling
        // check whether a configuration has been defined for this role name or not
        // loads the ThrottleContext
        ThrottleContext resourceContext = throttle.getThrottleContext(RESOURCE_THROTTLE_KEY);
        if (resourceContext == null) {
            log.warn("Unable to load throttle context");
            return true;
        }
        // Loads the ThrottleConfiguration
        ThrottleConfiguration config = resourceContext.getThrottleConfiguration();
        if (config != null) {
            String applicationRoleId = null;
            // If an application level tier has been specified and it is not 'Unlimited'
            if (applicationTier != null && !APIConstants.UNLIMITED_TIER.equals(applicationTier)) {
                // Get the configuration role of the application
                // applicationRoleId = config.getConfigurationKeyOfCaller(applicationTier);
                applicationRoleId = applicationTier;
            }
            AccessInformation info = null;
            // If application level throttling is applied
            if (applicationRoleId != null) {
                ThrottleContext applicationThrottleContext = getApplicationThrottleContext(synCtx, dataHolder, applicationId);
                if (isClusteringEnable) {
                    applicationThrottleContext.setConfigurationContext(cc);
                    applicationThrottleContext.setThrottleId(id);
                }
                // First throttle by application
                try {
                    info = applicationRoleBasedAccessController.canAccess(applicationThrottleContext, applicationId, applicationRoleId);
                    if (log.isDebugEnabled()) {
                        log.debug("Throttle by Application " + applicationId);
                        log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
                    }
                } catch (ThrottleException e) {
                    log.warn("Exception occurred while performing role " + "based throttling", e);
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                    return false;
                }
                // check for the permission for access
                if (info != null && !info.isAccessAllowed()) {
                    log.info("Exceeded the allocated quota in Application level.");
                    // if the access has denied by rate based throttling
                    if (cac != null) {
                        cac.incrementAndGet();
                        // set back if this is a clustered env
                        if (isClusteringEnable) {
                            cc.setProperty(key, cac);
                            resourceContext.setConfigurationContext(cc);
                            // replicate the current state of ConcurrentAccessController
                            try {
                                Replicator.replicate(cc, new String[] { key });
                            } catch (ClusteringFault clusteringFault) {
                                log.error("Error during replicating states", clusteringFault);
                            }
                        }
                    }
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                    return false;
                }
            }
            // ---------------End of application level throttling------------
            // ==============================Start of Resource level throttling======================================
            // get throttling information for given request with resource path and http verb
            // VerbInfoDTO verbInfoDTO = null;
            // verbInfoDTO = validator.getVerbInfoDTOFromAPIData(apiContext, apiVersion, requestPath, httpMethod);
            VerbInfoDTO verbInfoDTO = (VerbInfoDTO) synCtx.getProperty(APIConstants.VERB_INFO_DTO);
            String resourceLevelRoleId = null;
            // no data related to verb information data
            if (verbInfoDTO == null) {
                log.warn("Error while getting throttling information for resource and http verb");
                return false;
            } else {
                // Not only we can proceed
                String resourceAndHTTPVerbThrottlingTier = verbInfoDTO.getThrottling();
                // If there no any tier then we need to set it as unlimited
                if (resourceAndHTTPVerbThrottlingTier == null) {
                    log.warn("Unable to find throttling information for resource and http verb. Throttling will " + "not apply");
                } else {
                    resourceLevelRoleId = resourceAndHTTPVerbThrottlingTier;
                }
                // adding consumerKey and authz_user combination instead of access token to resourceAndHTTPVerbKey
                // This avoids sending more than the permitted number of requests in a unit time by
                // regenerating the access token
                String resourceAndHTTPVerbKey = verbInfoDTO.getRequestKey() + '-' + consumerKey + ':' + authorizedUser;
                // if request not null then only we proceed
                if (resourceLevelRoleId != null) {
                    try {
                        // if application level throttling has passed
                        if (!APIConstants.UNLIMITED_TIER.equals(resourceLevelRoleId) && (info == null || info.isAccessAllowed())) {
                            // If this is a clustered env.
                            if (isClusteringEnable) {
                                resourceContext.setConfigurationContext(cc);
                                resourceContext.setThrottleId(id + "resource");
                            }
                            info = roleBasedAccessController.canAccess(resourceContext, resourceAndHTTPVerbKey, resourceAndHTTPVerbThrottlingTier);
                        }
                    } catch (ThrottleException e) {
                        log.warn("Exception occurred while performing resource" + "based throttling", e);
                        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                        return false;
                    }
                    // check for the permission for access
                    if (info != null && !info.isAccessAllowed()) {
                        log.info("Exceeded the allocated quota in Resource level.");
                        // if the access has denied by rate based throttling
                        if (cac != null) {
                            cac.incrementAndGet();
                            // set back if this is a clustered env
                            if (isClusteringEnable) {
                                cc.setProperty(key, cac);
                                // replicate the current state of ConcurrentAccessController
                                try {
                                    Replicator.replicate(cc, new String[] { key });
                                } catch (ClusteringFault clusteringFault) {
                                    log.error("Error during replicating states", clusteringFault);
                                }
                            }
                        }
                        if (isContinueOnThrottleReached(resourceAndHTTPVerbThrottlingTier)) {
                            // 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);
                            }
                        } else {
                            synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                            return false;
                        }
                    }
                } else {
                    log.warn("Unable to find the throttle policy for role.");
                }
            }
            // ==============================End of Resource level throttling=======================================
            // ---------------Start of API level throttling------------------
            // Domain name based throttling
            // check whether a configuration has been defined for this role name or not
            // loads the ThrottleContext
            ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
            String apiKey;
            if (context == null) {
                log.warn("Unable to load throttle context");
                return true;
            }
            // If this is a clustered env.
            // check for configuration role of the caller
            config = context.getThrottleConfiguration();
            String consumerRoleID = config.getConfigurationKeyOfCaller(roleID);
            if (isClusteringEnable) {
                context.setConfigurationContext(cc);
                context.setThrottleId(id);
            }
            try {
                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 : "";
                // adding consumerKey and authz_user combination instead of access token to apiKey
                // This avoids sending more than the permitted number of requests in a unit time by
                // regenerating the access token
                apiKey = apiContext + ':' + apiVersion + ':' + consumerKey + ':' + authorizedUser;
                // if application level throttling has passed
                if (!APIConstants.UNLIMITED_TIER.equals(roleID) && (info == null || info.isAccessAllowed())) {
                    // Throttle by access token
                    info = roleBasedAccessController.canAccess(context, apiKey, consumerRoleID);
                }
            } catch (ThrottleException e) {
                log.warn("Exception occurred while performing role " + "based throttling", e);
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                return false;
            }
            // check for the permission for access
            if (info != null && !info.isAccessAllowed()) {
                log.info("Exceeded the allocated quota in API level.");
                // if the access has denied by rate based throttling
                if (cac != null) {
                    cac.incrementAndGet();
                    // set back if this is a clustered env
                    if (isClusteringEnable) {
                        cc.setProperty(key, cac);
                        // replicate the current state of ConcurrentAccessController
                        try {
                            Replicator.replicate(cc, new String[] { key });
                        } catch (ClusteringFault clusteringFault) {
                            log.error("Error during replicating states", clusteringFault);
                        }
                    }
                }
                if (isContinueOnThrottleReached(consumerRoleID)) {
                    // 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);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Request throttled at API level for throttle key" + apiKey + ". But role " + consumerRoleID + "allows to continue to serve requests");
                    }
                } else {
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                    return false;
                }
            }
        }
    }
    // ---------------End of API level throttling------------------
    // ---------------Start of Hard throttling------------------
    ThrottleContext hardThrottleContext = throttle.getThrottleContext(APIThrottleConstants.HARD_THROTTLING_CONFIGURATION);
    try {
        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 : "";
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        if (hardThrottleContext != null && authContext.getKeyType() != null) {
            String throttleKey = apiContext + ':' + apiVersion + ':' + authContext.getKeyType();
            AccessInformation info = null;
            if (isClusteringEnable) {
                hardThrottleContext.setConfigurationContext(cc);
            }
            if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(authContext.getKeyType())) {
                hardThrottleContext.setThrottleId(id + APIThrottleConstants.PRODUCTION_HARD_LIMIT);
                info = roleBasedAccessController.canAccess(hardThrottleContext, throttleKey, APIThrottleConstants.PRODUCTION_HARD_LIMIT);
            } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(authContext.getKeyType())) {
                hardThrottleContext.setThrottleId(id + APIThrottleConstants.SANDBOX_HARD_LIMIT);
                info = roleBasedAccessController.canAccess(hardThrottleContext, throttleKey, APIThrottleConstants.SANDBOX_HARD_LIMIT);
            }
            if (log.isDebugEnabled()) {
                log.debug("Throttle by hard limit " + throttleKey);
                log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
            }
            if (info != null && !info.isAccessAllowed()) {
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
                log.info("Hard Throttling limit exceeded.");
                return false;
            }
        }
    } catch (ThrottleException e) {
        log.warn("Exception occurred while performing role based throttling", e);
        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
        return false;
    }
    return canAccess;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ThrottleDataHolder(org.apache.synapse.commons.throttle.core.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) ClusteringFault(org.apache.axis2.clustering.ClusteringFault)

Example 39 with VerbInfoDTO

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

the class GraphQLRequestProcessorTest method testHandleRequestScopeValidationSkipWhenSecurityDisabled.

@Test
public void testHandleRequestScopeValidationSkipWhenSecurityDisabled() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    int msgSize = 100;
    String msgText = "{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{}," + "\"operationName\":null,\"query\":\"subscription {\\n  " + "liftStatusChange {\\n    id\\n    name\\n }\\n}\\n\"}}";
    PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
    // Get schema and parse
    String graphqlDirPath = "graphQL" + File.separator;
    String relativePath = graphqlDirPath + "schema_with_additional_props.graphql";
    String schemaString = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath));
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry registry = schemaParser.parse(schemaString);
    GraphQLSchema schema = UnExecutableSchemaGenerator.makeUnExecutableSchema(registry);
    GraphQLSchemaDTO schemaDTO = new GraphQLSchemaDTO(schema, registry);
    inboundMessageContext.setGraphQLSchemaDTO(schemaDTO);
    // VerbInfoDTO with security disabled
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setHttpVerb("SUBSCRIPTION");
    verbInfoDTO.setThrottling("Unlimited");
    verbInfoDTO.setAuthType("None");
    PowerMockito.when(InboundWebsocketProcessorUtil.findMatchingVerb("liftStatusChange", inboundMessageContext)).thenReturn(verbInfoDTO);
    // Creating response for scope validation
    GraphQLProcessorResponseDTO graphQLProcessorResponseDTO = new GraphQLProcessorResponseDTO();
    graphQLProcessorResponseDTO.setError(true);
    graphQLProcessorResponseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR);
    graphQLProcessorResponseDTO.setErrorMessage("User is NOT authorized to access the Resource");
    graphQLProcessorResponseDTO.setCloseConnection(false);
    graphQLProcessorResponseDTO.setId("1");
    PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, "liftStatusChange", "1")).thenReturn(graphQLProcessorResponseDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize, verbInfoDTO, inboundMessageContext, "1")).thenReturn(responseDTO);
    GraphQLRequestProcessor graphQLRequestProcessor = new GraphQLRequestProcessor();
    InboundProcessorResponseDTO processorResponseDTO = graphQLRequestProcessor.handleRequest(msgSize, msgText, inboundMessageContext);
    Assert.assertFalse(processorResponseDTO.isError());
    Assert.assertNull(processorResponseDTO.getErrorMessage());
    Assert.assertNotEquals(processorResponseDTO.getErrorMessage(), "User is NOT authorized to access the Resource");
}
Also used : GraphQLProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) GraphQLSchemaDTO(org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 40 with VerbInfoDTO

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

the class GraphQLRequestProcessorTest method testHandleRequestSuccess.

@Test
public void testHandleRequestSuccess() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    int msgSize = 100;
    String msgText = "{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{}," + "\"operationName\":null,\"query\":\"subscription {\\n  " + "liftStatusChange {\\n    id\\n    name\\n    }\\n}\\n\"}}";
    PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
    // Get schema and parse
    String graphqlDirPath = "graphQL" + File.separator;
    String relativePath = graphqlDirPath + "schema_with_additional_props.graphql";
    String schemaString = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath));
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry registry = schemaParser.parse(schemaString);
    GraphQLSchema schema = UnExecutableSchemaGenerator.makeUnExecutableSchema(registry);
    GraphQLSchemaDTO schemaDTO = new GraphQLSchemaDTO(schema, registry);
    inboundMessageContext.setGraphQLSchemaDTO(schemaDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, "liftStatusChange", "1")).thenReturn(responseDTO);
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setHttpVerb("SUBSCRIPTION");
    verbInfoDTO.setThrottling("Unlimited");
    PowerMockito.when(InboundWebsocketProcessorUtil.findMatchingVerb("liftStatusChange", inboundMessageContext)).thenReturn(verbInfoDTO);
    APIKeyValidationInfoDTO infoDTO = new APIKeyValidationInfoDTO();
    infoDTO.setGraphQLMaxComplexity(4);
    infoDTO.setGraphQLMaxDepth(3);
    inboundMessageContext.setInfoDTO(infoDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize, verbInfoDTO, inboundMessageContext, "1")).thenReturn(responseDTO);
    GraphQLRequestProcessor graphQLRequestProcessor = new GraphQLRequestProcessor();
    InboundProcessorResponseDTO processorResponseDTO = graphQLRequestProcessor.handleRequest(msgSize, msgText, inboundMessageContext);
    Assert.assertFalse(processorResponseDTO.isError());
    Assert.assertNull(processorResponseDTO.getErrorMessage());
    Assert.assertEquals(inboundMessageContext.getVerbInfoForGraphQLMsgId("1").getOperation(), "liftStatusChange");
    Assert.assertEquals(inboundMessageContext.getVerbInfoForGraphQLMsgId("1").getVerbInfoDTO().getHttpVerb(), "SUBSCRIPTION");
    Assert.assertEquals(inboundMessageContext.getVerbInfoForGraphQLMsgId("1").getVerbInfoDTO().getThrottling(), "Unlimited");
}
Also used : VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) GraphQLSchemaDTO(org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

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