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 all 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 @@ -27,6 +27,7 @@
import java.util.List;
import org.wso2.am.integration.clients.admin.api.dto.ClaimMappingEntryDTO;
import org.wso2.am.integration.clients.admin.api.dto.KeyManagerCertificatesDTO;
import org.wso2.am.integration.clients.admin.api.dto.KeyManagerPermissionsDTO;
import org.wso2.am.integration.clients.admin.api.dto.TokenValidationDTO;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
Expand Down Expand Up @@ -158,6 +159,10 @@ public class KeyManagerDTO {
@SerializedName(SERIALIZED_NAME_ADDITIONAL_PROPERTIES)
private Object additionalProperties;

public static final String SERIALIZED_NAME_PERMISSIONS = "permissions";
@SerializedName(SERIALIZED_NAME_PERMISSIONS)
private KeyManagerPermissionsDTO permissions;

/**
* The type of the tokens to be used (exchanged or without exchanged). Accepted values are EXCHANGED and DIRECT.
*/
Expand Down Expand Up @@ -923,6 +928,29 @@ public void setAdditionalProperties(Object additionalProperties) {
}


public KeyManagerDTO permissions(KeyManagerPermissionsDTO permissions) {

this.permissions = permissions;
return this;
}

/**
* Get permissions
* @return permissions
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")

public KeyManagerPermissionsDTO getPermissions() {
return permissions;
}


public void setPermissions(KeyManagerPermissionsDTO permissions) {
this.permissions = permissions;
}


public KeyManagerDTO tokenType(TokenTypeEnum tokenType) {

this.tokenType = tokenType;
Expand Down Expand Up @@ -986,12 +1014,13 @@ public boolean equals(Object o) {
Objects.equals(this.tokenValidation, keyManager.tokenValidation) &&
Objects.equals(this.enabled, keyManager.enabled) &&
Objects.equals(this.additionalProperties, keyManager.additionalProperties) &&
Objects.equals(this.permissions, keyManager.permissions) &&
Objects.equals(this.tokenType, keyManager.tokenType);
}

@Override
public int hashCode() {
return Objects.hash(id, name, displayName, type, description, wellKnownEndpoint, introspectionEndpoint, clientRegistrationEndpoint, tokenEndpoint, displayTokenEndpoint, revokeEndpoint, displayRevokeEndpoint, userInfoEndpoint, authorizeEndpoint, certificates, issuer, alias, scopeManagementEndpoint, availableGrantTypes, enableTokenGeneration, enableTokenEncryption, enableTokenHashing, enableMapOAuthConsumerApps, enableOAuthAppCreation, enableSelfValidationJWT, claimMapping, consumerKeyClaim, scopesClaim, tokenValidation, enabled, additionalProperties, tokenType);
return Objects.hash(id, name, displayName, type, description, wellKnownEndpoint, introspectionEndpoint, clientRegistrationEndpoint, tokenEndpoint, displayTokenEndpoint, revokeEndpoint, displayRevokeEndpoint, userInfoEndpoint, authorizeEndpoint, certificates, issuer, alias, scopeManagementEndpoint, availableGrantTypes, enableTokenGeneration, enableTokenEncryption, enableTokenHashing, enableMapOAuthConsumerApps, enableOAuthAppCreation, enableSelfValidationJWT, claimMapping, consumerKeyClaim, scopesClaim, tokenValidation, enabled, additionalProperties, permissions, tokenType);
}


Expand Down Expand Up @@ -1030,6 +1059,7 @@ public String toString() {
sb.append(" tokenValidation: ").append(toIndentedString(tokenValidation)).append("\n");
sb.append(" enabled: ").append(toIndentedString(enabled)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append(" permissions: ").append(toIndentedString(permissions)).append("\n");
sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n");
sb.append("}");
return sb.toString();
Expand Down
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();
}

}
Loading
Loading