Search in sources :

Example 46 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIConsumerImpl method getDeniedTiers.

/**
 * Returns a list of tiers denied
 * @param apiProviderTenantId tenant id of API provider
 * @return Set<Tier>
 */
@Override
public Set<String> getDeniedTiers(int apiProviderTenantId) throws APIManagementException {
    Set<String> deniedTiers = new HashSet<String>();
    String[] currentUserRoles;
    Set<TierPermissionDTO> tierPermissions = apiMgtDAO.getThrottleTierPermissions(apiProviderTenantId);
    if (apiProviderTenantId == 0) {
        apiProviderTenantId = tenantId;
    }
    if (apiProviderTenantId != 0) {
        if (APIUtil.isOnPremResolver()) {
            if (tenantId != apiProviderTenantId) {
                // therefore any POLICY that have a permission attached marked as deny policy.
                for (TierPermissionDTO tierPermission : tierPermissions) {
                    deniedTiers.add(tierPermission.getTierName());
                }
                return deniedTiers;
            }
        }
        /* Get the roles of the Current User */
        String userName = (userNameWithoutChange != null) ? userNameWithoutChange : username;
        currentUserRoles = APIUtil.getListOfRoles(userName);
        for (TierPermissionDTO tierPermission : tierPermissions) {
            String type = tierPermission.getPermissionType();
            List<String> currentRolesList = new ArrayList<String>(Arrays.asList(currentUserRoles));
            String[] rolesList = tierPermission.getRoles();
            List<String> roles = new ArrayList<>();
            if (rolesList != null) {
                roles = new ArrayList<>(Arrays.asList(rolesList));
            }
            currentRolesList.retainAll(roles);
            if (APIConstants.TIER_PERMISSION_ALLOW.equals(type)) {
                /* Current User is not allowed for this Tier*/
                if (currentRolesList.isEmpty()) {
                    deniedTiers.add(tierPermission.getTierName());
                }
            } else {
                /* Current User is denied for this Tier*/
                if (currentRolesList.size() > 0) {
                    deniedTiers.add(tierPermission.getTierName());
                }
            }
        }
    }
    return deniedTiers;
}
Also used : TierPermissionDTO(org.wso2.carbon.apimgt.impl.dto.TierPermissionDTO) ArrayList(java.util.ArrayList) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 47 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIKeyMgtRemoteUserStoreMgtService method getUserRoles.

/**
 * Get the role list of a user. Works for any tenant domain.
 * @param username username with tenant domain
 * @return list of roles
 * @throws APIManagementException
 */
public String[] getUserRoles(String username) throws APIManagementException {
    String[] userRoles = null;
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    UserStoreManager userStoreManager;
    try {
        userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username));
    } catch (UserStoreException e) {
        APIUtil.handleException("Error occurred retrieving roles of user " + username, e);
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
    }
    return userRoles;
}
Also used : UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 48 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class CommonConfigDeployer method createdConfigurationContext.

public void createdConfigurationContext(ConfigurationContext configurationContext) {
    final String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    final int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    try {
        // TODO adding only the policies to data wouldn't be sufficient. Need to figure out approach after tenant story has finalized
        // Add default set of policies to database
        ThrottleProperties.PolicyDeployer policyDeployer = configuration.getThrottleProperties().getPolicyDeployer();
        // Also this will avoid tenant login overhead as well
        if (policyDeployer.isEnabled()) {
            Thread t1 = new Thread(new Runnable() {

                public void run() {
                    try {
                        APIUtil.addDefaultTenantAdvancedThrottlePolicies(tenantDomain, tenantId);
                    } catch (APIManagementException e) {
                        log.error("Error while deploying throttle policies", e);
                    }
                }
            });
            t1.start();
        }
    } catch (Exception e) {
        log.error("Failed to load default policies to tenant" + tenantDomain, e);
    }
    try {
        // Check whether GatewayType is "Synapse" before attempting to load Custom-Sequences into registry
        String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
        if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
            APIUtil.writeDefinedSequencesToTenantRegistry(tenantId);
        }
    }// Need to continue the execution even if we encounter an error.
     catch (Exception e) {
        log.error("Failed to write defined sequences to tenant " + tenantDomain + "'s registry", e);
    }
    try {
        APIUtil.loadTenantExternalStoreConfig(tenantDomain);
    } catch (Exception e) {
        log.error("Failed to load external-stores.xml to tenant " + tenantDomain + "'s registry", e);
    }
    try {
        APIUtil.loadTenantGAConfig(tenantDomain);
    } catch (Exception e) {
        log.error("Failed to load ga-config.xml to tenant " + tenantDomain + "'s registry", e);
    }
    try {
        // load workflow-extension configuration to the registry
        APIUtil.loadTenantWorkFlowExtensions(tenantDomain);
    } catch (Exception e) {
        log.error("Failed to load workflow-extension.xml to tenant " + tenantDomain + "'s registry", e);
    }
    try {
        // load self signup configurations to the registry
        APIUtil.loadTenantSelfSignUpConfigurations(tenantDomain);
    } catch (Exception e) {
        log.error("Failed to load sign-up-config.xml to tenant " + tenantDomain + "'s registry", e);
    }
    try {
        APIUtil.loadAndSyncTenantConf(tenantDomain);
    } catch (APIManagementException e) {
        log.error("Failed to load " + APIConstants.API_TENANT_CONF + " for tenant " + tenantDomain, e);
    } catch (Exception e) {
        // The generic Exception is handled explicitly so execution does not stop during config deployment
        log.error("Exception when loading " + APIConstants.API_TENANT_CONF + " for tenant " + tenantDomain, e);
    }
    try {
        // Load common operation policies to tenant
        APIUtil.loadCommonOperationPolicies(tenantDomain);
    } catch (Exception e) {
        // The generic Exception is handled explicitly so execution does not stop during config deployment
        log.error("Exception when loading " + APIConstants.OPERATION_POLICIES + " for tenant " + tenantDomain, e);
    }
    try {
        APIUtil.createDefaultRoles(tenantId);
    } catch (APIManagementException e) {
        log.error("Failed create default roles for tenant " + tenantDomain, e);
    } catch (Exception e) {
        // The generic Exception is handled explicitly so execution does not stop during config deployment
        log.error("Exception when creating default roles for tenant " + tenantDomain, e);
    }
    try {
        CommonUtil.addDefaultLifecyclesIfNotAvailable(ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId), CommonUtil.getRootSystemRegistry(tenantId));
    } catch (RegistryException e) {
        log.error("Error while accessing registry", e);
    } catch (FileNotFoundException e) {
        log.error("Error while find lifecycle.xml", e);
    } catch (XMLStreamException e) {
        log.error("Error while parsing Lifecycle.xml", e);
    }
    KeyManagerConfigurationDataRetriever keyManagerConfigurationDataRetriever = new KeyManagerConfigurationDataRetriever(tenantDomain);
    keyManagerConfigurationDataRetriever.startLoadKeyManagerConfigurations();
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) KeyManagerConfigurationDataRetriever(org.wso2.carbon.apimgt.impl.loader.KeyManagerConfigurationDataRetriever) FileNotFoundException(java.io.FileNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FileNotFoundException(java.io.FileNotFoundException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)

Example 49 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowApprovedByAdmin.

@Test
public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setRoles(roleMap);
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
    PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod();
    PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
    Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true);
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true);
    // Set workflow status to be approved
    workflowDTO.setStatus(WorkflowStatus.APPROVED);
    workflowDTO.setTenantDomain(tenantDomain);
    // Set tenant admin credentials
    userRegistrationConfigDTO.setAdminUserName("admin");
    userRegistrationConfigDTO.setAdminPassword("admin");
    // Test failure to complete workflow execution, when error has been occurred while updating user with signup roles
    Mockito.doThrow(UserStoreException.class).when(userStoreManager).updateRoleListOfUser(Mockito.anyString(), Mockito.any(), new String[] { Mockito.anyString() });
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when sign up roles are not existing in user realm
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false);
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when error has been occurred while retrieving signup config
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException("Error occurred while retrieving signup configuration"));
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 50 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class BasicAuthenticationInterceptor method validateUserRolesWithRESTAPIScopes.

/**
 * This method validates the user roles against the roles of the REST API scopes defined for the current resource.
 *
 * @param resourceScopeList Scope list of the current resource
 * @param restAPIScopes     RESTAPIScopes mapping for the current tenant
 * @param userRoles         Role list for the user
 * @param username          Username
 * @param path              Path Info
 * @param verb              HTTP Request Method
 * @param inMessage         cxf Message to set the matched user scopes for the resource
 * @return whether user role validation against REST API scope roles is success or not.
 */
private boolean validateUserRolesWithRESTAPIScopes(List<Scope> resourceScopeList, Map<String, String> restAPIScopes, String[] userRoles, String username, String path, String verb, Message inMessage) {
    // Holds the REST API scope list which the user will get successfully validated against with
    List<Scope> validatedUserScopes = new ArrayList<>();
    // iterate the non empty scope list of the URITemplate of the invoking resource
    for (Scope scope : resourceScopeList) {
        // get the configured roles list string of the requested resource
        String resourceRolesString = restAPIScopes.get(scope.getKey());
        if (StringUtils.isNotBlank(resourceRolesString)) {
            // split role list string read using comma separator
            List<String> resourceRoleList = Arrays.asList(resourceRolesString.split("\\s*,\\s*"));
            // check if the roles related to the API resource contains any of the role of the user
            for (String role : userRoles) {
                if (resourceRoleList.contains(role)) {
                    // Role validation is success. Add the current scope to the validated user scope list and
                    // skip role check iteration of current scope and move to next resource scope.
                    validatedUserScopes.add(scope);
                    if (log.isDebugEnabled()) {
                        log.debug("Basic Authentication: role validation successful for user: " + username + " with scope: " + scope.getKey() + " for resource path: " + path + " and verb " + verb);
                        log.debug("Added scope: " + scope.getKey() + " to validated user scope list");
                    }
                    break;
                }
            }
        } else {
            // No role for the requested resource scope. Add it to the validated user scope list.
            validatedUserScopes.add(scope);
            if (log.isDebugEnabled()) {
                log.debug("Role validation skipped. No REST API scope to role mapping defined for resource scope: " + scope.getKey() + " Treated as anonymous scope.");
            }
        }
    }
    List<String> scopes = new ArrayList<>();
    validatedUserScopes.forEach(scope -> scopes.add(scope.getKey()));
    // Add the validated user scope list to the cxf message
    inMessage.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, scopes.toArray(new String[0]));
    if (!validatedUserScopes.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Successfully validated REST API Scopes for the user " + username);
        }
        return true;
    }
    // none of the resource scopes were matched against the user role set
    log.error("Insufficient privileges. Role validation failed for user: " + username + " to access resource path: " + path + " and verb " + verb);
    return false;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) ArrayList(java.util.ArrayList)

Aggregations

ArrayList (java.util.ArrayList)72 HashMap (java.util.HashMap)60 Test (org.testng.annotations.Test)36 UserStoreException (org.wso2.carbon.user.api.UserStoreException)36 SQLException (java.sql.SQLException)27 HashSet (java.util.HashSet)26 Map (java.util.Map)25 Connection (java.sql.Connection)23 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)23 PreparedStatement (java.sql.PreparedStatement)21 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)20 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)18 JSONObject (org.json.simple.JSONObject)17 UserStoreException (org.wso2.carbon.user.core.UserStoreException)17 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)16 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)16 RealmService (org.wso2.carbon.user.core.service.RealmService)15 API (org.wso2.carbon.apimgt.core.models.API)14 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)14 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)14