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

Adds testcase to check CORS for token endpoints #13241

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 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 @@ -26,6 +26,7 @@
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
Expand Down Expand Up @@ -95,6 +96,22 @@ public static org.wso2.carbon.automation.test.utils.http.client.HttpResponse doP
return constructResponse(response);
}

/**
* do HTTP OPTIONS operation for the given URL
*
* @param url request URL
* @param headers headers to be send
* @return org.wso2.carbon.automation.test.utils.http.client.HttpResponse
* @throws IOException if connection issue occurred
*/
public static org.wso2.carbon.automation.test.utils.http.client.HttpResponse doOptions(String url,
Map<String, String> headers) throws IOException {

CloseableHttpClient httpClient = getHttpsClient();
HttpResponse response = sendOptionsMessage(httpClient, url, headers);
return constructResponse(response);
}

/**
* To do HTTPS GET operation for the given URL with mutual SSL.
*
Expand Down Expand Up @@ -317,6 +334,27 @@ private static HttpResponse sendPUTMessage(CloseableHttpClient httpClient, Strin
return httpClient.execute(put);
}

/**
* OPTIONS function implementation
*
* @param httpClient http client to use
* @param url request URL
* @param headers headers to be send
* @param body payload to be send
* @return org.apache.http.HttpResponse
* @throws IOException if connection issue occurred
*/
private static HttpResponse sendOptionsMessage(CloseableHttpClient httpClient, String url,
Map<String, String> headers) throws IOException {
HttpOptions options = new HttpOptions(url);
if (headers != null) {
for (Map.Entry<String, String> head : headers.entrySet()) {
options.addHeader(head.getKey(), head.getValue());
}
}
return httpClient.execute(options);
}

/**
* Construct the org.wso2.carbon.automation.test.utils.http.client.HttpResponse
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.am.integration.tests.other;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.tests.api.lifecycle.APIManagerLifecycleBaseTest;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;

import java.io.File;

public class TokenEndpointCorsConfig extends APIManagerLifecycleBaseTest {
private ServerConfigurationManager serverConfigurationManager;
private AutomationContext superTenantKeyManagerContext;

@BeforeTest(alwaysRun = true)
public void setEnvironment() throws Exception {
superTenantKeyManagerContext = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_KEY_MANAGER_INSTANCE,
TestUserMode.SUPER_TENANT_ADMIN);
serverConfigurationManager = new ServerConfigurationManager(superTenantKeyManagerContext);

serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation()
+ File.separator + "configFiles" + File.separator + "cors" +
File.separator + "deployment.toml"));
}

@AfterTest(alwaysRun = true)
public void removeApplicationSharingConfig() throws Exception {
serverConfigurationManager.restoreToLastConfiguration(false);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.am.integration.tests.other;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.testng.Assert;
import org.testng.annotations.*;
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid import all

import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APICreationRequestBean;
import org.wso2.am.integration.test.utils.http.HTTPSClientUtils;
import org.wso2.am.integration.tests.api.lifecycle.APIManagerLifecycleBaseTest;
import org.wso2.am.integration.tests.api.lifecycle.AddEndPointSecurityPerTypeTestCase;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;

import java.net.URL;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;

public class TokenEndpointCorsTestCase extends APIManagerLifecycleBaseTest {

private static final Log log = LogFactory.getLog(AddEndPointSecurityPerTypeTestCase.class);
private final String API_NAME = "TokenEndpointCorsAPI";
private final String API_CONTEXT = "TokenEndpointCorsAPI";
private final String API_VERSION_1_0_0 = "1.0.0";
private final String APPLICATION_NAME = "AddEndPointSecurityPerTypeTestCase";
private String providerName;
private APICreationRequestBean apiCreationRequestBean;
private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
private String apiEndPointUrl;
private String apiID;
ArrayList<String> apiIds = new ArrayList<>();
String tokenEndpointURL;

@BeforeClass(alwaysRun = true)
public void initialize() throws Exception {
super.init();
apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
providerName = user.getUserName();
apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName,
new URL(apiEndPointUrl));
APIDTO apidto = createAndPublishAPI(apiCreationRequestBean, restAPIPublisher, false);
waitForAPIDeploymentSync(user.getUserName(), API_NAME, API_VERSION_1_0_0,
APIMIntegrationConstants.IS_API_EXISTS);
apiID = apidto.getId();
tokenEndpointURL = keyManagerHTTPSURL + "oauth2/token";
}


@Test(groups = {"wso2.am"}, description = "Test CORS for token endpoint")
public void testCORSforTokenEndpoint() throws Exception {

Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("Origin", "http://wso2.is");
HttpResponse response1 = HTTPSClientUtils.doOptions(tokenEndpointURL, requestHeader);
log.info(requestHeader.toString());
log.info(response1.getHeaders().toString());
log.info(response1.getResponseMessage());
Assert.assertEquals(response1.getHeaders().get("Access-Control-Allow-Origin"), "http://wso2.is");
Assert.assertEquals(response1.getResponseCode(), 200);

requestHeader.put("Origin", "http://wso3.is");
HttpResponse response2 = HTTPSClientUtils.doOptions(tokenEndpointURL, requestHeader);
log.info(requestHeader.toString());
log.info(response2.getHeaders().toString());
log.info(response2.getResponseMessage());
Assert.assertEquals(response2.getResponseCode(), 403);
}

@AfterClass(alwaysRun = true)
public void cleanUpArtifacts() throws Exception {
for (String apiId: apiIds) {
undeployAndDeleteAPIRevisionsUsingRest(apiId, restAPIPublisher);
restAPIPublisher.deleteAPI(apiId);
}
super.cleanUp();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
[server]
hostname = "localhost"
#offset=0
base_path = "${carbon.protocol}://${carbon.host}:${carbon.management.port}"
server_role = "default"
enable_shutdown_from_api = true
enable_restart_from_api = true

[super_admin]
username = "admin"
password = "admin"
create_admin_account = true

[user_store]
type = "database_unique_id"

[database.apim_db]
driver = "$env{API_MANAGER_DATABASE_DRIVER}"
url = "$env{API_MANAGER_DATABASE_URL}"
username = "$env{API_MANAGER_DATABASE_USERNAME}"
password = "$env{API_MANAGER_DATABASE_PASSWORD}"
validationQuery = "$env{API_MANAGER_DATABASE_VALIDATION_QUERY}"

[database.shared_db]
driver = "$env{SHARED_DATABASE_DRIVER}"
url = "$env{SHARED_DATABASE_URL}"
username = "$env{SHARED_DATABASE_USERNAME}"
password = "$env{SHARED_DATABASE_PASSWORD}"
validationQuery = "$env{SHARED_DATABASE_VALIDATION_QUERY}"

[keystore.tls]
file_name = "wso2carbon.jks"
type = "JKS"
password = "wso2carbon"
alias = "wso2carbon"
key_password = "wso2carbon"

[[apim.gateway.environment]]
name = "Default"
type = "hybrid"
provider = "wso2"
display_in_api_console = true
description = "This is a hybrid gateway that handles both production and sandbox token traffic."
show_as_token_endpoint_url = true
service_url = "https://localhost:${mgt.transport.https.port}/services/"
username = "admin"
password = "admin"
ws_endpoint = "ws://localhost:9099"
http_endpoint = "http://localhost:${http.nio.port}"
https_endpoint = "https://localhost:${https.nio.port}"

[[apim.gateway.environment]]
name = "devportalEnv"
display_name = "Developer portal Test Environment"
type = "hybrid"
display_in_api_console = false
description = "development api gateway broker"
provider = "solace"
service_url = "http://localhost:9960"
username = "testUser"
ws_endpoint = "ws://localhost:9960/"
wss_endpoint = "wss://localhost:9960/"
http_endpoint = "http://localhost:9960"
https_endpoint = "https://localhost:9960/"
password = "testPassword"
show_as_token_endpoint_url = false

[apim.gateway.environment.properties]
Organization = "TestWSO2"
DisplayName = "Developer portal Test Environment"
DevAccountName = "devPortTestEnv"

[apim.devportal]
enable_application_sharing = true
application_sharing_type = "default"

[apim.cors]
allow_origins = "*"
allow_methods = ["GET","PUT","POST","DELETE","PATCH","OPTIONS"]
allow_headers = ["authorization","Access-Control-Allow-Origin","Content-Type","SOAPAction"]
allow_credentials = false

[cors]
allow_generic_http_requests = true
allow_any_origin = false
allowed_origins = ["http://wso2.is"]
allow_subdomains = false
supported_methods = [ "GET", "POST", "HEAD", "OPTIONS" ]
support_any_header = true
supported_headers = []
exposed_headers = []
supports_credentials = true
max_age = 3600
tag_requests = false

[[event_handler]]
name="userPostSelfRegistration"
subscriptions=["POST_ADD_USER"]
[transport]
passthru_https.listener.ssl_profile_interval = 6000
passthru_https.sender.ssl_profile.interval = 6000

[apim.certificate_reloader]
period = "1m"

[database.local]
url = "jdbc:h2:./repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE"

[[event_listener]]
id = "token_revocation"
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
name = "org.wso2.is.notification.ApimOauthEventInterceptor"
order = 1
[event_listener.properties]
notification_endpoint = "https://localhost:${mgt.transport.https.port}/internal/data/v1/notify"
username = "${admin.username}"
password = "${admin.password}"
'header.X-WSO2-KEY-MANAGER' = "default"

[apim.sync_runtime_artifacts.gateway.skip_list]
apis = ["admin--git2231head_v1.0.0.xml","admin--PizzaShackAPI_v1.0.0.xml","admin--ScriptMediatorAPI_v1.0.xml",
"APIThrottleBackendAPI.xml","BackEndSecurity.xml","DigestAuth_API.xml","git2231.xml","HttpPATCHSupport_API.xml","JWKS-Backend.xml","JWTBackendAPI.xml","multiVSR_v1.0.0.xml","Response_API_1.xml","Response_API_2.xml","Response_Custom_API.xml","Response_Error_API.xml","Response_Loc_API.xml","SpecialCRN_v1.0.0.xml","status_code_204_API.xml","stockquote.xml","XML_API.xml","Version1.xml","Version2.xml","schemaValidationAPI.xml"]
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@
<class name="org.wso2.am.integration.tests.api.lifecycle.ChangeEndPointSecurityOfAPITestCase"/>
<class name="org.wso2.am.integration.tests.api.lifecycle.ChangeEndPointSecurityPerTypeTestCase"/>
<class name="org.wso2.am.integration.tests.api.lifecycle.AddEndPointSecurityPerTypeTestCase"/>
<class name="org.wso2.am.integration.tests.other.TokenEndpointCorsConfig"/>
<class name="org.wso2.am.integration.tests.other.TokenEndpointCorsTestCase"/>
</classes>
</test>

Expand Down