Search in sources :

Example 16 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleId.

@Test
public void testGetRoleId() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validRoleName = "engineer";
    final String validRoleSearchQuery = "displayName Eq " + validRoleName;
    final String expectedRoleId = "ac093278-9343-466c-8a71-af47921a575b";
    String invalidRoleName = "invalid_role";
    final String invalidRoleSearchQuery = "displayName Eq " + invalidRoleName;
    String roleReturningNullResponse = "invalid_user_giving_null_response";
    final String roleReturningNullResponseSearchQuery = "displayName Eq " + roleReturningNullResponse;
    // happy path
    String responseBody = "{\"totalResults\":1,\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"Resources\":" + "[{\"displayName\":\"PRIMARY/engineer\",\"meta\":{\"created\":\"2017-06-02T10:14:42\"," + "\"location\":\"https://localhost:9443/wso2/scim/Groups/ac093278-9343-466c-8a71-af47921a575b\"," + "\"lastModified\":\"2017-06-02T10:14:42\"},\"id\":\"ac093278-9343-466c-8a71-af47921a575b\"}]}";
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(responseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchGroups(validRoleSearchQuery)).thenReturn(createdResponse);
    try {
        String roleId = idpImpl.getRoleId(validRoleName);
        Assert.assertEquals(roleId, expectedRoleId);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // Assuming the role cannot be found - when returning a not 200 response
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"Group not found in the user store.\"}]}";
    Response createdResponseNoSuchRole = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchGroups(invalidRoleSearchQuery)).thenReturn(createdResponseNoSuchRole);
    try {
        idpImpl.getRoleId(invalidRoleName);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of role " + invalidRoleName + ". Error : Group not found in the user store.");
    }
    // error path
    // Assuming the response is null
    Mockito.when(scimServiceStub.searchGroups(roleReturningNullResponseSearchQuery)).thenReturn(null);
    try {
        idpImpl.getRoleId(roleReturningNullResponse);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of role " + roleReturningNullResponse + ". Error : Response is null.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 17 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testIsValidRole.

@Test
public void testIsValidRole() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    final String validRole = "engineer";
    final String validRoleSearchQuery = "displayName Eq " + validRole;
    Response okResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).build();
    Mockito.when(scimServiceStub.searchGroups(validRoleSearchQuery)).thenReturn(okResponse);
    Assert.assertTrue(idpImpl.isValidRole(validRole));
    final String invalidRole = "invalid-role";
    final String invalidRoleSearchQuery = "displayName Eq " + invalidRole;
    Response notFoundResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).build();
    Mockito.when(scimServiceStub.searchGroups(invalidRoleSearchQuery)).thenReturn(notFoundResponse);
    Assert.assertFalse(idpImpl.isValidRole(invalidRole));
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) HashMap(java.util.HashMap) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) Test(org.testng.annotations.Test)

Example 18 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleIdsOfUser.

@Test
public void testGetRoleIdsOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleIds = new ArrayList<>();
    roleIds.add(roleId1);
    roleIds.add(roleId2);
    roleIds.add(roleId3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleIdsOfUser(validUserId);
    Assert.assertEquals(roleIds.size(), roles.size());
    roles.forEach(roleId -> Assert.assertTrue(roleIds.contains(roleId)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role Ids of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 19 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class APIUtil method checkIfUserInRole.

/**
 * Check whether the user has the given role
 *
 * @param username Logged-in username
 * @param roleName role that needs to be checked
 * @throws UserStoreException
 */
public static boolean checkIfUserInRole(String username, String roleName) throws UserStoreException {
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
    int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
    RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
    UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
    org.wso2.carbon.user.core.UserStoreManager manager = realm.getUserStoreManager();
    AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager;
    return abstractManager.isUserInRole(tenantAwareUserName, roleName);
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 20 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method loadloadTenantAPIRXT.

public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // calculate resource path
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            resourcePath = authorizationManager.computePathOnMount(resourcePath);
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
            if (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File)

Aggregations

Test (org.testng.annotations.Test)85 ArrayList (java.util.ArrayList)74 UserStoreException (org.wso2.carbon.user.api.UserStoreException)56 HashMap (java.util.HashMap)52 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)42 Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)34 Role (org.wso2.charon3.core.objects.Role)33 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)31 CharonException (org.wso2.charon3.core.exceptions.CharonException)29 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)26 PreparedStatement (java.sql.PreparedStatement)25 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)24 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)23 HashSet (java.util.HashSet)20 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)20 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)19 IdentityRoleManagementClientException (org.wso2.carbon.identity.role.mgt.core.IdentityRoleManagementClientException)19 Matchers.anyString (org.mockito.Matchers.anyString)18