Skip to content

Add integration tests for application creation, role creation and API Authorization in sub organization #23424

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

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this required?
If need to be merged, add license header

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>identity-integration-tests</artifactId>
<groupId>org.wso2.is</groupId>
<version>7.1.0-m2-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jacoco-report-generator</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.jacoco:org.jacoco.core</include>
<include>org.jacoco:org.jacoco.report</include>
<include>org.codehaus.plexus:plexus-utils</include>
<include>org.ow2.asm:asm</include>
<include>org.ow2.asm:asm-tree</include>
<include>org.ow2.asm:asm-commons</include>
</includes>
</artifactSet>
<transformers>
<transformer>
<mainClass>org.wso2.carbon.identity.jacoco.ReportGenerator</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.identity.inbound.auth.sts</groupId>
<artifactId>org.wso2.carbon.identity.sts.passive.stub</artifactId>
<version>5.11.9</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.automationutils</groupId>
<artifactId>org.wso2.carbon.integration.common.extensions</artifactId>
<version>4.5.4</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<maven-shade-plugin.version>3.2.4</maven-shade-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.jacoco.version>0.8.12</org.jacoco.version>
<plexus-utils.version>4.0.1</plexus-utils.version>
</properties>
</project>
4 changes: 2 additions & 2 deletions modules/integration/tests-integration/tests-backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -589,8 +589,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1177,6 +1177,43 @@ public void authorizeSystemAPIs(String applicationId, List<String> apiIdentifier
});
}

/**
* Authorize list of SYSTEM APIs to an application registered in sub organization.
*
* @param applicationId Application id.
* @param apiIdentifiers API identifiers to authorize.
* @throws Exception Error occured while authorizing APIs.
*/
public void authorizeSystemAPIsToSubOrganizationApp(String applicationId, List<String> apiIdentifiers,
String switchedM2MToken) {

apiIdentifiers.stream().forEach(apiIdentifier -> {
try {
List<APIResourceListItem> filteredAPIResource =
restClient.getAPIResourcesWithFilteringFromSubOrganization("identifier+eq+" + apiIdentifier,
switchedM2MToken);
if (filteredAPIResource == null || filteredAPIResource.isEmpty()) {
return;
}
String apiId = filteredAPIResource.get(0).getId();
// Get API scopes.
List<ScopeGetModel> apiResourceScopes = restClient.getAPIResourceScopesInSubOrganization(apiId,
switchedM2MToken);
AuthorizedAPICreationModel authorizedAPICreationModel = new AuthorizedAPICreationModel();
authorizedAPICreationModel.setId(apiId);
authorizedAPICreationModel.setPolicyIdentifier("RBAC");
apiResourceScopes.forEach(scope -> {
authorizedAPICreationModel.addScopesItem(scope.getName());
});
restClient.addAPIAuthorizationToSubOrgApplication(applicationId, authorizedAPICreationModel,
switchedM2MToken);
} catch (Exception e) {
throw new RuntimeException("Error while authorizing system API " + apiIdentifier + " to application "
+ applicationId, e);
}
});
}

public String getRoleV2ResourceId(String roleName, String audienceType, String OrganizationId) throws Exception {

List<String> roles = restClient.getRoles(roleName, audienceType, OrganizationId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package org.wso2.identity.integration.test.rest.api.server.application.management.v1;
Copy link
Contributor

Choose a reason for hiding this comment

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

missing license header. Fix other places as well


import com.nimbusds.oauth2.sdk.AccessTokenResponse;
import com.nimbusds.oauth2.sdk.AuthorizationGrant;
import com.nimbusds.oauth2.sdk.ClientCredentialsGrant;
import com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant;
import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.TokenRequest;
import com.nimbusds.oauth2.sdk.TokenResponse;
import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
import com.nimbusds.oauth2.sdk.auth.Secret;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.oauth2.sdk.id.ClientID;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AssociatedRolesConfig;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.InboundProtocolListItem;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.InboundProtocols;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration;
import org.wso2.identity.integration.test.rest.api.server.organization.management.v1.OrganizationManagementBaseTest;
import org.wso2.identity.integration.test.rest.api.server.roles.v2.model.Audience;
import org.wso2.identity.integration.test.rest.api.server.roles.v2.model.Permission;
import org.wso2.identity.integration.test.rest.api.server.roles.v2.model.RoleV2;
import org.wso2.identity.integration.test.restclients.OAuth2RestClient;
import org.wso2.identity.integration.test.restclients.OrgMgtRestClient;
import org.wso2.identity.integration.test.utils.OAuth2Constant;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class OrganizationOAuth2ApplicationManagementSuccessTest extends OrganizationManagementBaseTest {
Copy link
Contributor

Choose a reason for hiding this comment

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

missing class comment


private static final String AUTHORIZED_APIS_JSON = "org-based-authorized-apis.json";
private static final String SUB_ORG_NAME = "subOrg";

private OrgMgtRestClient orgMgtRestClient;
private OAuth2RestClient oAuth2RestClient;
private String subOrgId;
private String switchedM2MToken;
private String subOrgAppToken;

@Factory(dataProvider = "restAPIUserConfigProvider")
public OrganizationOAuth2ApplicationManagementSuccessTest(TestUserMode userMode) throws Exception {

super.init(userMode);
this.context = isServer;
this.authenticatingUserName = context.getContextTenant().getTenantAdmin().getUserName();
this.authenticatingCredential = context.getContextTenant().getTenantAdmin().getPassword();
this.tenant = context.getContextTenant().getDomain();
}

@BeforeClass(alwaysRun = true)
public void initClass() throws Exception {

super.testInit("v1", swaggerDefinition, tenant);
oAuth2RestClient = new OAuth2RestClient(serverURL, tenantInfo);

orgMgtRestClient = new OrgMgtRestClient(isServer, tenantInfo, serverURL,
new JSONObject(readResource(AUTHORIZED_APIS_JSON, this.getClass())));
subOrgId = orgMgtRestClient.addOrganization(SUB_ORG_NAME);
switchedM2MToken = orgMgtRestClient.switchM2MToken(subOrgId);
orgMgtRestClient.addOrganizationUser("sub-org-user", "SubOrgUser@123");
Copy link
Contributor

Choose a reason for hiding this comment

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

from where will this user get deleted?

}

@AfterClass(alwaysRun = true)
public void atEnd() throws Exception {

orgMgtRestClient.deleteOrganization(subOrgId);
orgMgtRestClient.closeHttpClient();
oAuth2RestClient.closeHttpClient();
}

@Test
public void testCreateOAuth2ApplicationInOrganization() throws Exception {

String body = readResource("create-basic-oauth2-application.json", this.getClass());

oAuth2RestClient.createApplicationInSubOrganization(body, switchedM2MToken);
Copy link
Contributor

Choose a reason for hiding this comment

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

from where does this application get deleted?

System.out.println("Sub Organization Application ID : " + oAuth2RestClient.getAppIdUsingAppNameInOrganization("My SAMPLE APP", switchedM2MToken));
String subOrganizationAppId = oAuth2RestClient.getAppIdUsingAppNameInOrganization("My SAMPLE APP",
switchedM2MToken);

// Authorizing the APIs to the sub organization application
authorizeSystemAPIsToSubOrganizationApp(oAuth2RestClient, subOrganizationAppId,
new ArrayList<>(Arrays.asList("/o/scim2/Roles", "/o/oauth2/introspect")), switchedM2MToken);

// Creating an application role for the sub organization application
RoleV2 role;
String displayName;
List<String> schemas = Collections.emptyList();
List<Permission> permissions = new ArrayList<>();
permissions.add(new Permission("internal_org_role_mgt_create"));
permissions.add(new Permission("internal_org_role_mgt_view"));
displayName = "Application Role";
Audience roleAudience = new Audience("APPLICATION", subOrganizationAppId);
role = new RoleV2(roleAudience, displayName, permissions, schemas);
oAuth2RestClient.createV2RolesInSubOrganization(role, switchedM2MToken);
ApplicationResponseModel subOrgAppModel = oAuth2RestClient.getSubOrgApplication(subOrganizationAppId,
switchedM2MToken);

// Validate application details
Assert.assertEquals(subOrgAppModel.getName(), "My SAMPLE APP");

// Validate application role audience and roles
AssociatedRolesConfig associatedRolesConfig = subOrgAppModel.getAssociatedRoles();
Assert.assertEquals(associatedRolesConfig.getAllowedAudience().toString(), "APPLICATION");
Assert.assertEquals(associatedRolesConfig.getRoles().get(0).getName(), "Application Role");

// Validate application inbound protocols
List<InboundProtocolListItem> inboundProtocols = subOrgAppModel.getInboundProtocols();
Assert.assertEquals(inboundProtocols.size(), 1);
}

@Test(dependsOnMethods = "testCreateOAuth2ApplicationInOrganization")
public void testIssueAccessTokenFromSubOrgApplicationFromCCGrant() throws Exception {

String subOrganizationAppId = oAuth2RestClient.getAppIdUsingAppNameInOrganization("My SAMPLE APP",
switchedM2MToken);
OpenIDConnectConfiguration oidcConfig = oAuth2RestClient.getOIDCInboundDetailsForSubOrgApplications(
subOrganizationAppId, switchedM2MToken);
String subOrgAppClientId = oidcConfig.getClientId();
String clientSecret = oidcConfig.getClientSecret();

// Issue access token from sub organization application
AccessTokenResponse accessTokenResponse = getSubOrgApplicationToken("client_credentials", subOrgAppClientId, clientSecret, subOrgId);
subOrgAppToken = accessTokenResponse.getTokens().getAccessToken().getValue();
Assert.assertNotNull(subOrgAppToken);
String scopes = accessTokenResponse.getTokens().getAccessToken().getScope().toString();
String[] scopeArray = scopes.split(" ");
Assert.assertEquals(scopeArray.length, 6);
Assert.assertTrue(Arrays.asList(scopeArray).contains("internal_org_role_mgt_create"));
Assert.assertTrue(Arrays.asList(scopeArray).contains("internal_org_role_mgt_view"));
Assert.assertTrue(Arrays.asList(scopeArray).contains("internal_org_role_mgt_update"));
Assert.assertTrue(Arrays.asList(scopeArray).contains("internal_org_role_mgt_delete"));
}

public void testAccessResourcesFromTokensIssuedFromSubOrgApplication() throws Exception {

// Access resources from tokens issued from sub organization application
oAuth2RestClient.getRoles(subOrgAppToken);
}

private AccessTokenResponse getSubOrgApplicationToken(String grantType, String clientId, String clientSecretStr, String orgId) throws Exception {

URI tokenEndpoint = new URI("https://localhost:9853/t/carbon.super/o/" + orgId + "/oauth2/token");

ClientID clientID = new ClientID(clientId);
Secret clientSecret = new Secret(clientSecretStr);
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);

AuthorizationGrant authorizationGrant;
switch (grantType) {
case OAuth2Constant.OAUTH2_GRANT_TYPE_CLIENT_CREDENTIALS:
authorizationGrant = new ClientCredentialsGrant();
break;
case OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER:
authorizationGrant = new ResourceOwnerPasswordCredentialsGrant(null, null);
break;
default:
throw new Exception("Unsupported grant type");
}
Scope scope = new Scope("SYSTEM");

TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, authorizationGrant, scope);
HTTPResponse tokenHTTPResp = request.toHTTPRequest().send();
TokenResponse tokenResponse = TokenResponse.parse(tokenHTTPResp);
return tokenResponse.toSuccessResponse();
}

@DataProvider(name = "restAPIUserConfigProvider")
public static Object[][] restAPIUserConfigProvider() {

return new Object[][]{
{TestUserMode.SUPER_TENANT_ADMIN}
// {TestUserMode.TENANT_ADMIN}
Copy link
Contributor

Choose a reason for hiding this comment

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

why is it commented for tenanted mode?

};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.wso2.identity.integration.test.rest.api.server.api.resource.v1.model.APIResourceListItem;
import org.wso2.identity.integration.test.rest.api.server.api.resource.v1.model.ScopeGetModel;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AdvancedApplicationConfiguration;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationModel;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationSharePOSTRequest;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AuthorizedAPICreationModel;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.InboundProtocols;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration;
import org.wso2.identity.integration.test.rest.api.server.common.RESTAPIServerTestBase;
Expand Down Expand Up @@ -173,12 +176,26 @@ protected String getAppClientId(String applicationId) throws Exception {
return oidcConfig.getClientId();
}

protected String getSubOrgAppClientId(String applicationId, String switchedToken) throws Exception {

OpenIDConnectConfiguration oidcConfig = oAuth2RestClient.getOIDCInboundDetailsForSubOrgApplications(
applicationId, switchedToken);
return oidcConfig.getClientId();
}

protected String getAppClientSecret(String applicationId) throws Exception {

OpenIDConnectConfiguration oidcConfig = oAuth2RestClient.getOIDCInboundDetails(applicationId);
return oidcConfig.getClientSecret();
}

protected String getSubOrgAppClientSecret(String applicationId, String switchedM2MToken) throws Exception {

OpenIDConnectConfiguration oidcConfig = oAuth2RestClient.getOIDCInboundDetailsForSubOrgApplications(
applicationId, switchedM2MToken);
return oidcConfig.getClientSecret();
}

protected String buildGetRequestURL(String endpointURL, String tenantDomain, List<NameValuePair> queryParams) {

String authorizeEndpoint = getTenantQualifiedURL(endpointURL, tenantDomain);
Expand Down Expand Up @@ -259,4 +276,41 @@ protected String createB2BUser(String switchedM2MToken) throws Exception {
Assert.assertNotNull(b2bUserID, "B2B user creation failed.");
return b2bUserID;
}

/**
* Authorize list of SYSTEM APIs to an application registered in sub organization.
*
* @param applicationId Application id.
* @param apiIdentifiers API identifiers to authorize.
* @throws Exception Error occured while authorizing APIs.
*/
public void authorizeSystemAPIsToSubOrganizationApp(OAuth2RestClient restClient, String applicationId, List<String> apiIdentifiers,
String switchedM2MToken) {

apiIdentifiers.stream().forEach(apiIdentifier -> {
try {
List<APIResourceListItem> filteredAPIResource =
restClient.getAPIResourcesWithFilteringFromSubOrganization("identifier+eq+" + apiIdentifier,
switchedM2MToken);
if (filteredAPIResource == null || filteredAPIResource.isEmpty()) {
return;
}
String apiId = filteredAPIResource.get(0).getId();
// Get API scopes.
List<ScopeGetModel> apiResourceScopes = restClient.getAPIResourceScopesInSubOrganization(apiId,
switchedM2MToken);
AuthorizedAPICreationModel authorizedAPICreationModel = new AuthorizedAPICreationModel();
authorizedAPICreationModel.setId(apiId);
authorizedAPICreationModel.setPolicyIdentifier("RBAC");
apiResourceScopes.forEach(scope -> {
authorizedAPICreationModel.addScopesItem(scope.getName());
});
restClient.addAPIAuthorizationToSubOrgApplication(applicationId, authorizedAPICreationModel,
switchedM2MToken);
} catch (Exception e) {
throw new RuntimeException("Error while authorizing system API " + apiIdentifier + " to application "
+ applicationId, e);
}
});
}
}
Loading