From cd99185eb191724a8fe26e9462d25ef336047ff0 Mon Sep 17 00:00:00 2001 From: Kannan Kirishikesan Date: Mon, 10 Jul 2023 12:18:14 +0530 Subject: [PATCH 1/4] Adds testcase to check support cors for token endpoints --- .../test/utils/http/HTTPSClientUtils.java | 38 ++++++++ .../tests/other/TokenEndpointCorsConfig.java | 52 ++++++++++ .../other/TokenEndpointCorsTestCase.java | 96 +++++++++++++++++++ .../src/test/resources/testng.xml | 2 + 4 files changed, 188 insertions(+) create mode 100644 modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsConfig.java create mode 100644 modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/http/HTTPSClientUtils.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/http/HTTPSClientUtils.java index 9cec76b553..9db1da80c9 100644 --- a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/http/HTTPSClientUtils.java +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/http/HTTPSClientUtils.java @@ -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; @@ -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 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. * @@ -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 headers) throws IOException { + HttpOptions options = new HttpOptions(url); + if (headers != null) { + for (Map.Entry head : headers.entrySet()) { + options.addHeader(head.getKey(), head.getValue()); + } + } + return httpClient.execute(options); + } + /** * Construct the org.wso2.carbon.automation.test.utils.http.client.HttpResponse * diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsConfig.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsConfig.java new file mode 100644 index 0000000000..ca2fd8a9c3 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsConfig.java @@ -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); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java new file mode 100644 index 0000000000..445f4ec350 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java @@ -0,0 +1,96 @@ +/* + * 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.*; +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.*; + +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 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 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(); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml index cb3a4edd6b..8c5912b526 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml @@ -386,6 +386,8 @@ + + From d4df87670428fc794b0bd3092e3773cc63c61eaf Mon Sep 17 00:00:00 2001 From: Kannan Kirishikesan Date: Mon, 10 Jul 2023 12:19:24 +0530 Subject: [PATCH 2/4] Adds deployment.toml for tokenendpointcorstestcase --- .../AM/configFiles/cors/deployment.toml | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100755 modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/AM/configFiles/cors/deployment.toml diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/AM/configFiles/cors/deployment.toml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/AM/configFiles/cors/deployment.toml new file mode 100755 index 0000000000..2ae93d19bc --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/AM/configFiles/cors/deployment.toml @@ -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"] \ No newline at end of file From 260967d45747df083acde8042ab7a96f0ab36340 Mon Sep 17 00:00:00 2001 From: Kannan Kirishikesan Date: Tue, 18 Jul 2023 10:05:50 +0530 Subject: [PATCH 3/4] Removes java.util.* and imports only relevant ones --- .../am/integration/tests/other/TokenEndpointCorsTestCase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java index 445f4ec350..85d5a8d961 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/TokenEndpointCorsTestCase.java @@ -32,7 +32,9 @@ import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import java.net.URL; -import java.util.*; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; public class TokenEndpointCorsTestCase extends APIManagerLifecycleBaseTest { From 247606f81f7164338ff26520d3a266257d6c673c Mon Sep 17 00:00:00 2001 From: Kannan Kirishikesan Date: Wed, 11 Oct 2023 11:58:48 +0530 Subject: [PATCH 4/4] Adding testcase for Key Manager Permissions --- .../clients/admin/api/dto/KeyManagerDTO.java | 32 ++++- .../restapi/admin/KeyManagersTestCase.java | 132 ++++++++++++++++++ 2 files changed, 163 insertions(+), 1 deletion(-) diff --git a/modules/integration/tests-common/clients/admin/src/gen/java/org/wso2/am/integration/clients/admin/api/dto/KeyManagerDTO.java b/modules/integration/tests-common/clients/admin/src/gen/java/org/wso2/am/integration/clients/admin/api/dto/KeyManagerDTO.java index fd76c2e521..d44ba21ece 100644 --- a/modules/integration/tests-common/clients/admin/src/gen/java/org/wso2/am/integration/clients/admin/api/dto/KeyManagerDTO.java +++ b/modules/integration/tests-common/clients/admin/src/gen/java/org/wso2/am/integration/clients/admin/api/dto/KeyManagerDTO.java @@ -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; /** @@ -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. */ @@ -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; @@ -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); } @@ -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(); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/KeyManagersTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/KeyManagersTestCase.java index 0d7426ae09..27e5a7766f 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/KeyManagersTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/KeyManagersTestCase.java @@ -29,20 +29,61 @@ import org.wso2.am.integration.clients.admin.ApiResponse; import org.wso2.am.integration.clients.admin.api.dto.KeyManagerCertificatesDTO; import org.wso2.am.integration.clients.admin.api.dto.KeyManagerDTO; +import org.wso2.am.integration.clients.admin.api.dto.KeyManagerPermissionsDTO; +import org.wso2.am.integration.clients.store.api.ApiException; +import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO; +import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO; +import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO; +import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionDTO; import org.wso2.am.integration.test.helpers.AdminApiTestHelper; import org.wso2.am.integration.test.impl.DtoFactory; +import org.wso2.am.integration.test.impl.RestAPIStoreImpl; import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest; +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.bean.APILifeCycleAction; +import org.wso2.am.integration.test.utils.bean.APIRequest; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.ArrayList; + +import static org.testng.Assert.assertEquals; public class KeyManagersTestCase extends APIMIntegrationBaseTest { private AdminApiTestHelper adminApiTestHelper; private KeyManagerDTO keyManagerDTO; + private final String API_VERSION_1_0_0 = "1.0.0"; + private final String USER_TEST = "test"; + private final String USER_TEST_PASSWORD = "test123"; + private String apiEndPointUrl; + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private APIIdentifier apiIdentifier; + private String API_NAME = "DummyApi"; + private String apiId; + private String appId; + private String applicationId; + private String API_SUBSCRIBER = "APISubscriberRole"; + private String apiCreatorStoreDomain; + private RestAPIStoreImpl restAPIStoreClient1; + private String[] API_SUBSCRIBER_PERMISSIONS = { + "/permission/admin/login", + "/permission/admin/manage/api/create", + "/permission/admin/manage/api/subscriber" + }; + String[] ROLE_LIST = { "Internal/publisher", "Internal/subscriber", "Internal/everyone"}; + private APICreationRequestBean apiCreationRequestBean; @Factory(dataProvider = "userModeDataProvider") public KeyManagersTestCase(TestUserMode userMode) { @@ -59,6 +100,10 @@ public static Object[][] userModeDataProvider() { public void setEnvironment() throws Exception { super.init(userMode); adminApiTestHelper = new AdminApiTestHelper(); + apiPublisher = new APIPublisherRestClient(getPublisherURLHttp()); + apiStore = new APIStoreRestClient(getStoreURLHttp()); + apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + "jaxrs_basic/services/customers/customerservice/"; + apiIdentifier = new APIIdentifier(USER_TEST, API_NAME, API_VERSION_1_0_0); } //1. Auth0 Key Manager @@ -1104,6 +1149,93 @@ public void testAddKeyManagerWithExistingKeyManagerName() throws ApiException { } } + @Test(groups = {"wso2.am"}, description = "Test key manager permissions with WSO2IS with permissions" + ,dependsOnMethods = "testDeleteKeyManagerWithAuth0") + public void testKeyManagerPermissions() throws Exception { + + userManagementClient.addUser(USER_TEST, USER_TEST_PASSWORD, ROLE_LIST, USER_TEST); + userManagementClient.addRole(API_SUBSCRIBER, new String[]{ USER_TEST }, API_SUBSCRIBER_PERMISSIONS); + String providerName = user.getUserName(); + + APIRequest apiRequest; + apiRequest = new APIRequest("KMPermissionTestAPI", "KMPermissionTest", new URL(apiEndPointUrl)); + apiRequest.setVersion(API_VERSION_1_0_0); + apiRequest.setProvider(providerName); + apiRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD); + + //add KMPermissionTestAPI api + HttpResponse serviceResponse = restAPIPublisher.addAPI(apiRequest); + apiId = serviceResponse.getData(); + + //publish KMPermissionTestAPI api + restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.PUBLISH.getAction(), null); + + String name = "Wso2ISKeyManagerWithPermission"; + String type = "WSO2-IS"; + String displayName = "Test Key Manager Permissions WSO2IS"; + String introspectionEndpoint = "https://localhost:9444/oauth2/introspect"; + String clientRegistrationEndpoint = "https://localhost:9444/keymanager-operations/dcr/register"; + String scopeManagementEndpoint = "https://wso2is.com:9444/api/identity/oauth2/v1.0/scopes"; + String tokenEndpoint = "https://wso2is.com:9444/oauth2/token"; + String revokeEndpoint = "https://wso2is.com:9444/oauth2/revoke"; + String consumerKeyClaim = "azp"; + String scopesClaim = "scope"; + List availableGrantTypes = Collections.emptyList(); + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("Username", "admin"); + jsonObject.addProperty("Password", "admin"); + jsonObject.addProperty("self_validate_jwt", true); + Object additionalProperties = new Gson().fromJson(jsonObject, Map.class); + List rolesList = new ArrayList<>(); + rolesList.add(API_SUBSCRIBER); + KeyManagerPermissionsDTO keyManagerPermissionsDTO = new KeyManagerPermissionsDTO(); + keyManagerPermissionsDTO.setPermissionType(KeyManagerPermissionsDTO.PermissionTypeEnum.DENY); + keyManagerPermissionsDTO.setRoles(rolesList); + keyManagerDTO = DtoFactory.createKeyManagerDTO(name, null, type, displayName, introspectionEndpoint, + null, clientRegistrationEndpoint, tokenEndpoint, revokeEndpoint, null, null, + scopeManagementEndpoint, consumerKeyClaim, scopesClaim, availableGrantTypes, additionalProperties, + null); + keyManagerDTO.setPermissions(keyManagerPermissionsDTO); + + //Add the WSO2 IS key manager + ApiResponse addedKeyManagers = restAPIAdmin.addKeyManager(keyManagerDTO); + Assert.assertEquals(addedKeyManagers.getStatusCode(), HttpStatus.SC_CREATED); + KeyManagerDTO addedKeyManagerDTO = addedKeyManagers.getData(); + String keyManagerId = addedKeyManagerDTO.getId(); + + //Assert the status code and key manager ID + Assert.assertNotNull(keyManagerId, "The Key Manager ID cannot be null or empty"); + keyManagerDTO.setId(keyManagerId); + //Verify the created key manager DTO + adminApiTestHelper.verifyKeyManagerDTO(keyManagerDTO, addedKeyManagerDTO); + restAPIStore = new RestAPIStoreImpl(USER_TEST, USER_TEST_PASSWORD, + this.storeContext.getContextTenant().getDomain(), this.storeURLHttps); + HttpResponse applicationResponse = restAPIStore.createApplication("KMPermissionApplication7", + "KMPermissionTestApp", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, + ApplicationDTO.TokenTypeEnum.OAUTH); + assertEquals(applicationResponse.getResponseCode(), org.apache.commons.httpclient.HttpStatus.SC_OK, "Response code is not as expected"); + appId = applicationResponse.getData(); + System.out.println(appId); + + SubscriptionDTO subscriptionDto = restAPIStore.subscribeToAPI(apiId, appId, APIMIntegrationConstants.API_TIER.GOLD); + System.out.println(subscriptionDto.toString()); + System.out.println("Subscribed"); + + org.wso2.am.integration.clients.store.api.ApiResponse generateKeyResponse; + ArrayList grantTypes = new ArrayList<>(); + grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL); + + try { + generateKeyResponse = restAPIStore.generateKeysWithApiResponse(appId, "3600", null, + ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, + grantTypes, null, keyManagerId); + } catch (ApiException e) { + System.out.println(e); + Assert.assertEquals(e.getCode(), HttpStatus.SC_FORBIDDEN); + } + restAPIAdmin.deleteKeyManager(keyManagerId); + } + @AfterClass(alwaysRun = true) public void destroy() throws Exception { super.cleanUp();