Search in sources :

Example 6 with GraphQLSchemaDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPIGraphQLSchema.

/**
 * Get GraphQL Schema of given API
 *
 * @param apiId          apiId
 * @param accept
 * @param ifNoneMatch    If--Match header value
 * @param messageContext message context
 * @return Response with GraphQL Schema
 */
@Override
public Response getAPIGraphQLSchema(String apiId, String accept, String ifNoneMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // this will fail if user does not have access to the API or the API does not exist
        APIIdentifier apiIdentifier;
        if (ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId) != null) {
            apiIdentifier = APIMappingUtil.getAPIInfoFromUUID(apiId, organization).getId();
        } else {
            apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        }
        String schemaContent = apiProvider.getGraphqlSchema(apiIdentifier);
        GraphQLSchemaDTO dto = new GraphQLSchemaDTO();
        dto.setSchemaDefinition(schemaContent);
        dto.setName(apiIdentifier.getProviderName() + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR + apiIdentifier.getApiName() + apiIdentifier.getVersion() + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION);
        return Response.ok().entity(dto).build();
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving schema of API: " + apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving schema of API: " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) GraphQLSchemaDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 7 with GraphQLSchemaDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO in project carbon-apimgt by wso2.

the class PublisherCommonUtils method validateGraphQLSchema.

/**
 * Validate GraphQL Schema.
 *
 * @param filename file name of the schema
 * @param schema   GraphQL schema
 */
public static GraphQLValidationResponseDTO validateGraphQLSchema(String filename, String schema) throws APIManagementException {
    String errorMessage;
    GraphQLValidationResponseDTO validationResponse = new GraphQLValidationResponseDTO();
    boolean isValid = false;
    try {
        if (filename.endsWith(".graphql") || filename.endsWith(".txt") || filename.endsWith(".sdl")) {
            if (schema.isEmpty()) {
                throw new APIManagementException("GraphQL Schema cannot be empty or null to validate it", ExceptionCodes.GRAPHQL_SCHEMA_CANNOT_BE_NULL);
            }
            SchemaParser schemaParser = new SchemaParser();
            TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
            GraphQLSchema graphQLSchema = UnExecutableSchemaGenerator.makeUnExecutableSchema(typeRegistry);
            SchemaValidator schemaValidation = new SchemaValidator();
            Set<SchemaValidationError> validationErrors = schemaValidation.validateSchema(graphQLSchema);
            if (validationErrors.toArray().length > 0) {
                errorMessage = "InValid Schema";
                validationResponse.isValid(Boolean.FALSE);
                validationResponse.errorMessage(errorMessage);
            } else {
                validationResponse.setIsValid(Boolean.TRUE);
                GraphQLValidationResponseGraphQLInfoDTO graphQLInfo = new GraphQLValidationResponseGraphQLInfoDTO();
                GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
                List<URITemplate> operationList = graphql.extractGraphQLOperationList(typeRegistry, null);
                List<APIOperationsDTO> operationArray = APIMappingUtil.fromURITemplateListToOprationList(operationList);
                graphQLInfo.setOperations(operationArray);
                GraphQLSchemaDTO schemaObj = new GraphQLSchemaDTO();
                schemaObj.setSchemaDefinition(schema);
                graphQLInfo.setGraphQLSchema(schemaObj);
                validationResponse.setGraphQLInfo(graphQLInfo);
            }
        } else {
            throw new APIManagementException("Unsupported extension type of file: " + filename, ExceptionCodes.UNSUPPORTED_GRAPHQL_FILE_EXTENSION);
        }
        isValid = validationResponse.isIsValid();
        errorMessage = validationResponse.getErrorMessage();
    } catch (SchemaProblem e) {
        errorMessage = e.getMessage();
    }
    if (!isValid) {
        validationResponse.setIsValid(isValid);
        validationResponse.setErrorMessage(errorMessage);
    }
    return validationResponse;
}
Also used : TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaValidator(graphql.schema.validation.SchemaValidator) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) GraphQLValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseDTO) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) SchemaValidationError(graphql.schema.validation.SchemaValidationError) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GraphQLValidationResponseGraphQLInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseGraphQLInfoDTO) SchemaProblem(graphql.schema.idl.errors.SchemaProblem) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) GraphQLSchemaDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO)

Example 8 with GraphQLSchemaDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO 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 9 with GraphQLSchemaDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO 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)

Example 10 with GraphQLSchemaDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO in project carbon-apimgt by wso2.

the class GraphQLAPIHandlerTest method setup.

@Before
public void setup() throws IOException {
    messageContext = Mockito.mock(Axis2MessageContext.class);
    axis2MessageContext = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    omElement = Mockito.mock(OMElement.class);
    dataHolder = Mockito.mock(DataHolder.class);
    SOAPEnvelope soapEnvelope = Mockito.mock(SOAPEnvelope.class);
    SOAPBody soapBody = Mockito.mock(SOAPBody.class);
    PowerMockito.mockStatic(DataHolder.class);
    OMElement body = Mockito.mock(OMElement.class);
    Map propertyList = Mockito.mock(Map.class);
    Mockito.when(messageContext.getAxis2MessageContext()).thenReturn(axis2MessageContext);
    Mockito.when(axis2MessageContext.getIncomingTransportName()).thenReturn("ws");
    Mockito.when(messageContext.getProperty(APIConstants.GRAPHQL_SUBSCRIPTION_REQUEST)).thenReturn(true);
    Mockito.when(axis2MessageContext.getIncomingTransportName()).thenReturn("wss");
    Mockito.when(axis2MessageContext.getEnvelope()).thenReturn(soapEnvelope);
    Mockito.when(soapEnvelope.getBody()).thenReturn(soapBody);
    Mockito.when(soapBody.getFirstElement()).thenReturn(body);
    Mockito.when(body.getFirstChildWithName(QName.valueOf("query"))).thenReturn(omElement);
    Mockito.when(messageContext.getProperties()).thenReturn(propertyList);
    Mockito.when(messageContext.getProperty(REST_SUB_REQUEST_PATH)).thenReturn("/");
    Mockito.when(propertyList.get(REST_SUB_REQUEST_PATH)).thenReturn("/");
    Mockito.when(propertyList.get(REST_SUB_REQUEST_PATH).toString().split("/?query=")).thenReturn(new String[0]);
    Mockito.when(DataHolder.getInstance()).thenReturn(dataHolder);
    // Get schema and parse
    schemaDTOMap = new HashMap<>();
    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);
    schemaDTOMap.put("12345", schemaDTO);
    Mockito.when(dataHolder.getApiToGraphQLSchemaDTOMap()).thenReturn(schemaDTOMap);
}
Also used : TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) OMElement(org.apache.axiom.om.OMElement) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) SOAPBody(org.apache.axiom.soap.SOAPBody) DataHolder(org.wso2.carbon.apimgt.gateway.internal.DataHolder) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) GraphQLSchemaDTO(org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO) HashMap(java.util.HashMap) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Before(org.junit.Before)

Aggregations

GraphQLSchema (graphql.schema.GraphQLSchema)9 SchemaParser (graphql.schema.idl.SchemaParser)9 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)9 GraphQLSchemaDTO (org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO)8 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)6 InboundProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO)6 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)5 JSONObject (org.json.simple.JSONObject)4 JSONParser (org.json.simple.parser.JSONParser)4 GraphQLProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO)3 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 GraphQLSchemaDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO)2 SchemaProblem (graphql.schema.idl.errors.SchemaProblem)1 SchemaValidationError (graphql.schema.validation.SchemaValidationError)1 SchemaValidator (graphql.schema.validation.SchemaValidator)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1