Skip to content

Commit

Permalink
Merge pull request #13234 from dulithsenanayake/context-validation
Browse files Browse the repository at this point in the history
Add integrations tests to check malformed API contexts
  • Loading branch information
npamudika authored Jan 31, 2024
2 parents d3b68b3 + a31b2d2 commit 61b1e1d
Show file tree
Hide file tree
Showing 7 changed files with 210 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
import org.wso2.am.integration.test.ClientAuthenticator;
import org.wso2.am.integration.test.Constants;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.*;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import java.io.File;
Expand Down Expand Up @@ -262,6 +263,20 @@ public HttpResponse addAPI(APIRequest apiRequest) throws ApiException {
return response;
}

public HttpResponse addAPIWithMalformedContext(APIRequest apiRequest) {

String osVersion = "v3";
setActivityID();
HttpResponse response = null;
try {
this.addAPI(apiRequest, osVersion);
} catch (ApiException e) {
response = new HttpResponse(APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR, e.getCode());
return response;
}
return null;
}

/**
* \
* This method is used to create an API.
Expand Down Expand Up @@ -366,6 +381,9 @@ public APIDTO addAPI(APIRequest apiRequest, String osVersion) throws ApiExceptio
if (e.getResponseBody().contains("already exists")) {
return null;
}
if (e.getResponseBody().contains(APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR)) {
throw new ApiException(e.getCode(), APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR);
}
throw new ApiException(e);
}
return apidto;
Expand Down Expand Up @@ -1229,6 +1247,21 @@ public void updateGraphqlSchemaDefinition(String apiId, String schemaDefinition)
Assert.assertEquals(HttpStatus.SC_OK, schemaDefinitionDTO.getStatusCode());
}

public HttpResponse importGraphqlSchemaDefinitionWithInvalidContext(File file, String properties) throws ApiException {
ApiResponse<APIDTO> apiDtoApiResponse = null;
HttpResponse response = null;
try {
apiDtoApiResponse = apIsApi.importGraphQLSchemaWithHttpInfo(null, "GRAPHQL",
file, properties);
Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode());
} catch (ApiException e) {
if (e.getResponseBody().contains(APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR)) {
response = new HttpResponse(APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR, e.getCode());
}
}
return response;
}

public WSDLValidationResponseDTO validateWsdlDefinition(String url, File wsdlDefinition) throws ApiException {
ApiResponse<WSDLValidationResponseDTO> response = validationApi
.validateWSDLDefinitionWithHttpInfo(url, wsdlDefinition);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ public class APIMIntegrationConstants {
public static final String API_RESPONSE_ELEMENT_NAME_APIS = "apis";
public static final String API_RESPONSE_ELEMENT_NAME_ID = "id";

public static final String API_NAME = "name";
public static final String API_CONTEXT = "context";
public static final String API_VERSION = "version";
public static final String ENDPOINT_TYPE = "endpoint_type";
public static final String SANDBOX_ENDPOINTS = "sandbox_endpoints";
public static final String PRODUCTION_ENDPOINTS = "production_endpoints";
public static final String ENDPOINT_CONFIG = "endpointConfig";
public static final String POLICIES = "policies";
public static final String OPERATIONS = "operations";
public static final String API_CONTEXT_MALFORMED_ERROR = "The API context is malformed";
public static final String API_PRODUCT_CONTEXT_MALFORMED_ERROR = "The API Product context is malformed";

public static final String OAUTH_DEFAULT_APPLICATION_NAME = "DefaultApplication";

public static final String IS_API_EXISTS = "\"isApiExists\":true";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;

import javax.ws.rs.core.Response;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
Expand Down Expand Up @@ -89,6 +90,8 @@ public class APIProductCreationTestCase extends APIManagerLifecycleBaseTest {
private ApiProductTestHelper apiProductTestHelper;
private String apiProductId2;
private String resourcePath;
private String apiID1;
private String apiID2;

@Factory(dataProvider = "userModeDataProvider")
public APIProductCreationTestCase(TestUserMode userMode) {
Expand Down Expand Up @@ -298,6 +301,35 @@ public void testAPIProductNewVersionCreationWithDefaultVersion() throws Exceptio
Assert.assertEquals(isDefaultVersion, true, "Copied API Product is not the default version");
}

@Test(groups = {"wso2.am"}, description = "Test creation of API Product with malformed context")
public void testCreateApiProductWithMalformedContext() throws Exception {
// Pre-Conditions : Create APIs
List<APIDTO> apisToBeUsed = new ArrayList<>();
APIDTO apiOne = apiTestHelper.createApiOne(getBackendEndServiceEndPointHttp("wildcard/resources"));
APIDTO apiTwo = apiTestHelper.createApiTwo(getBackendEndServiceEndPointHttp("wildcard/resources"));
apisToBeUsed.add(apiOne);
apisToBeUsed.add(apiTwo);
apiID1 = apiOne.getId();
apiID2 = apiTwo.getId();

// Step 1 : Create APIProduct
final String provider = user.getUserName();
final String name = UUID.randomUUID().toString();
final String context = "/" + UUID.randomUUID().toString() + "{version}" ;
final String version = "1.0.0";

List<String> policies = Arrays.asList(TIER_UNLIMITED, TIER_GOLD);

try{
apiProductTestHelper.createAPIProductInPublisher(provider, name, context, version,
apisToBeUsed, policies);
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), Response.Status.BAD_REQUEST.getStatusCode());
Assert.assertTrue(e.getResponseBody().contains(
APIMIntegrationConstants.API_PRODUCT_CONTEXT_MALFORMED_ERROR));
}
}

@Test(groups = {"wso2.am"}, description = "Test creation and invocation of API Product which depends " +
"on a visibility restricted API")
public void testCreateAndInvokeApiProductWithVisibilityRestrictedApi() throws Exception {
Expand Down Expand Up @@ -781,6 +813,8 @@ private File geTempFileWithContent(String swagger) throws Exception {
@AfterClass(alwaysRun = true)
public void cleanUpArtifacts() throws Exception {

restAPIPublisher.deleteAPI(apiID1);
restAPIPublisher.deleteAPI(apiID2);
super.cleanUp();
userManagementClient.deleteUser(RESTRICTED_SUBSCRIBER);
userManagementClient.deleteUser(STANDARD_SUBSCRIBER);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,44 @@ public void createAndPublishGraphQLAPIUsingSchemaWithInterfaces() throws Excepti
APIMIntegrationConstants.IS_API_EXISTS);
}

@Test(groups = { "wso2.am" }, description =
"Attempt GraphQL API creation using a malformed context")
public void testCreateAndPublishGraphQLAPIUsingSchemaWithMalformedContext() throws Exception {

String schemaDefinitionWithInterface = IOUtils.toString(
getClass().getClassLoader().getResourceAsStream("graphql" + File.separator
+ "schemaWithInterface.graphql"), "UTF-8");
File file = getTempFileWithContent(schemaDefinitionWithInterface);
GraphQLValidationResponseDTO responseApiDto = restAPIPublisher.validateGraphqlSchemaDefinition(file);
GraphQLValidationResponseGraphQLInfoDTO graphQLInfo = responseApiDto.getGraphQLInfo();
String arrayToJson = new ObjectMapper().writeValueAsString(graphQLInfo.getOperations());
JSONArray operations = new JSONArray(arrayToJson);
HttpResponse response = null;

ArrayList<String> policies = new ArrayList<String>();
policies.add(APIMIntegrationConstants.API_TIER.UNLIMITED);

JSONObject additionalPropertiesObj = new JSONObject();
additionalPropertiesObj.put(APIMIntegrationConstants.API_NAME, "GraphQLAPIWithInvalidContext");
additionalPropertiesObj.put(APIMIntegrationConstants.API_CONTEXT, "invalidContext{version}");
additionalPropertiesObj.put(APIMIntegrationConstants.API_VERSION, API_VERSION_1_0_0);

JSONObject url = new JSONObject();
url.put("url", END_POINT_URL);
JSONObject endpointConfig = new JSONObject();
endpointConfig.put(APIMIntegrationConstants.ENDPOINT_TYPE, "http");
endpointConfig.put(APIMIntegrationConstants.SANDBOX_ENDPOINTS, url);
endpointConfig.put(APIMIntegrationConstants.PRODUCTION_ENDPOINTS, url);
additionalPropertiesObj.put(APIMIntegrationConstants.ENDPOINT_CONFIG, endpointConfig);
additionalPropertiesObj.put(APIMIntegrationConstants.POLICIES, policies);
additionalPropertiesObj.put(APIMIntegrationConstants.OPERATIONS, operations);

// create Graphql API
response = restAPIPublisher.importGraphqlSchemaDefinitionWithInvalidContext(file, additionalPropertiesObj.toString());
Assert.assertNotNull(response, "Response cannot be null");
Assert.assertEquals(response.getResponseCode(), 400, "Response Code miss matched when creating the API");
}

@Test(groups = {"wso2.am"}, description = "test retrieve schemaDefinition at publisher")
public void testRetrieveSchemaDefinitionAtPublisher() throws Exception {
GraphQLSchemaDTO schema = restAPIPublisher.getGraphqlSchemaDefinition(graphqlAPIId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.ApiResponse;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO;
Expand Down Expand Up @@ -71,6 +72,7 @@ public class WSDLImportTestCase extends APIManagerLifecycleBaseTest {
private final Log log = LogFactory.getLog(WSDLImportTestCase.class);
private String WSDL_FILE_API_NAME = "WSDLImportAPIWithWSDLFile";
private String WSDL_FILE_API_CONTEXT = "wsdlimportwithwsdlfile";
private String WSDL_FILE_MALFORMED_API_CONTEXT = "wsdlimportwithwsdlfile{version}";
private String WSDL_ZIP_API_NAME = "WSDLImportAPIWithZipFile";
private String WSDL_ZIP_API_CONTEXT = "wsdlimportwithzipfile";
private String WSDL_URL_API_NAME = "WSDLImportAPIWithURL";
Expand Down Expand Up @@ -247,6 +249,49 @@ public void testWsdlDefinitionImport() throws Exception {
accessToken = applicationKeyDTO.getToken().getAccessToken();
}

@Test(groups = {"wso2.am"}, description = "Importing WSDL API definition and create API")
public void testWsdlDefinitionImportWithMalformedContext() throws Exception {
log.info("testWsdlDefinitionImport initiated");

// Set environment
ArrayList<String> environment = new ArrayList<>();
environment.add(Constants.GATEWAY_ENVIRONMENT);

// Set policies
ArrayList<String> policies = new ArrayList<>();
policies.add(APIMIntegrationConstants.API_TIER.UNLIMITED);

// Set endpointConfig
JSONObject url = new JSONObject();
url.put("url", apiEndPointURL);
JSONObject endpointConfig = new JSONObject();
endpointConfig.put("endpoint_type", "http");
endpointConfig.put("sandbox_endpoints", url);
endpointConfig.put("production_endpoints", url);

// Create additional properties object
JSONObject additionalPropertiesObj = new JSONObject();
additionalPropertiesObj.put("provider", user.getUserName());
additionalPropertiesObj.put("name", WSDL_FILE_API_NAME);
additionalPropertiesObj.put("context", WSDL_FILE_MALFORMED_API_CONTEXT);
additionalPropertiesObj.put("version", API_VERSION);
additionalPropertiesObj.put("policies", policies);
additionalPropertiesObj.put("endpointConfig", endpointConfig);

// Create API by importing the WSDL definition as .wsdl file
String wsdlDefinitionPath = FrameworkPathUtil.getSystemResourceLocation() + "wsdl"
+ File.separator + "Sample.wsdl";
File file = new File(wsdlDefinitionPath);

try{
APIDTO wsdlFileApidto = restAPIPublisher.importWSDLSchemaDefinition(file, null,
additionalPropertiesObj.toString(), "SOAP");
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), Response.Status.BAD_REQUEST.getStatusCode());
Assert.assertTrue(e.getResponseBody().contains(APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR));
}
}

@Test(groups = {"wso2.am"}, description = "Get WSDL API definition of the created API",
dependsOnMethods = "testWsdlDefinitionImport")
public void testGetWsdlDefinitions() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,30 @@ public void testCreateAnAPIThroughThePublisherRest() throws Exception {
assertTrue(response.getData().contains("lastUpdatedTimestamp"), "Last Updated Timestamp is not available");
}

@Test(groups = {
"wso2.am" }, description = "Create an API Through the Publisher Rest API with malformed context")
public void testCreateAnAPIWithMalformedContextThroughThePublisherRest()
throws Exception {

// Now APIs with malformed context should not be allowed to create
String apiContextTest = "apim18PublisherTestAPIMalformed`";
String apiDescription = "This is Test API Created by API Manager Integration Test";
String apiTag = "tag18-4, tag18-5, tag18-6";
String apiName = "APIM18PublisherTestMalformed";

APIRequest apiCreationRequestBean;
apiCreationRequestBean = new APIRequest(apiName, apiContextTest, new URL(apiProductionEndPointUrl));

apiCreationRequestBean.setVersion(apiVersion);
apiCreationRequestBean.setDescription(apiDescription);
apiCreationRequestBean.setTags(apiTag);
apiCreationRequestBean.setTier(APIMIntegrationConstants.API_TIER.GOLD);

HttpResponse response = restAPIPublisher.addAPIWithMalformedContext(apiCreationRequestBean);
Assert.assertNotNull(response, "Response cannot be null");
Assert.assertEquals(response.getResponseCode(), Response.Status.BAD_REQUEST.getStatusCode(), "Response Code miss matched when creating the API");
}

@Test(groups = {"wso2.am"}, description = "Remove an API Through the Publisher Rest API",
dependsOnMethods = "testCreateAnAPIThroughThePublisherRest")
public void testRemoveAnAPIThroughThePublisherRest() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import org.wso2.carbon.utils.xml.StringUtils;

import javax.ws.rs.core.Response;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
Expand Down Expand Up @@ -101,6 +102,7 @@ enum AUTH_IN {
QUERY
}
private final String apiName = "WebSocketAPI";
private final String apiNameWithMalformedContext = "WebSocketAPIWithMalformedContext";
private final String applicationName = "WebSocketApplication";
private final String applicationJWTName = "WebSocketJWTTypeApplication";
private final String testMessage = "Web Socket Test Message";
Expand Down Expand Up @@ -467,6 +469,28 @@ public void testWebSocketAPIInvalidTokenInvocation() throws Exception {
}
}

@Test(description = "Create WebSocket API with malformed context",
dependsOnMethods = "testWebSocketAPIRemoveEndpoint")
public void testCreateWebSocketAPIWithMalformedContext() throws Exception {

provider = user.getUserName();
String apiContext = "echo{version}";
String apiVersion = "1.0.0";

URI endpointUri = new URI("ws://" + webSocketServerHost + ":" + webSocketServerPort);

//Create the api creation request object
apiRequest = new APIRequest(apiNameWithMalformedContext, apiContext, endpointUri, endpointUri);
apiRequest.setVersion(apiVersion);
apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.ASYNC_UNLIMITED);
apiRequest.setProvider(provider);
apiRequest.setType("WS");
apiRequest.setApiTier(APIMIntegrationConstants.API_TIER.UNLIMITED);

HttpResponse response = restAPIPublisher.addAPIWithMalformedContext(apiRequest);
Assert.assertEquals(response.getResponseCode(), Response.Status.BAD_REQUEST.getStatusCode(), "Response Code miss matched when creating the API");
}

/**
* Wait for client to receive reply from the server
*
Expand Down

0 comments on commit 61b1e1d

Please sign in to comment.