Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add integrations tests to check malformed API contexts #13234

Merged
merged 3 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,9 @@ 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_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("Unlimited");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we use APIMIntegrationConstants.API_TIER.UNLIMITED?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed from a31b2d2


JSONObject additionalPropertiesObj = new JSONObject();
additionalPropertiesObj.put("name", "GraphQLAPIWithInvalidContext");
additionalPropertiesObj.put("context", "invalidContext{version}");
additionalPropertiesObj.put("version", API_VERSION_1_0_0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's move the name, context, version words to constants.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed from a31b2d2


JSONObject url = new JSONObject();
url.put("url", END_POINT_URL);
JSONObject endpointConfig = new JSONObject();
endpointConfig.put("endpoint_type", "http");
endpointConfig.put("sandbox_endpoints", url);
endpointConfig.put("production_endpoints", url);
additionalPropertiesObj.put("endpointConfig", endpointConfig);
additionalPropertiesObj.put("policies", policies);
additionalPropertiesObj.put("operations", operations);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can move the property names to constants, as there are multiple usages in the class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed from a31b2d2


// 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("Gold");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we use APIMIntegrationConstants.API_TIER.GOLD?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed from a31b2d2


HttpResponse response = restAPIPublisher.addAPIWithMalformedContext(apiCreationRequestBean);
Assert.assertNotNull(response, "Response cannot be null");
Assert.assertEquals(response.getResponseCode(), 400, "Response Code miss matched when creating the API");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use Response.Status.NOT_FOUND.getStatusCode() for 400

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed from a31b2d2

}

@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 @@ -101,6 +101,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 +468,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(), 400, "Response Code miss matched when creating the API");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use Response.Status.NOT_FOUND.getStatusCode() for 400

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed from a31b2d2

}

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