Search in sources :

Example 26 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIProviderImpl method getAPILifeCycleData.

@Override
public /*
    * This method returns the lifecycle data for an API including current state,next states.
    *
    * @param apiId APIIdentifier
    * @return Map<String,Object> a map with lifecycle data
    */
Map<String, Object> getAPILifeCycleData(APIIdentifier apiId) throws APIManagementException {
    String path = APIUtil.getAPIPath(apiId);
    Map<String, Object> lcData = new HashMap<String, Object>();
    String providerTenantMode = apiId.getProviderName();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        Resource apiSourceArtifact = registry.get(path);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when getting lifecycle data for API " + apiId;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiSourceArtifact.getUUID());
        // Get all the actions corresponding to current state of the api artifact
        String[] actions = artifact.getAllLifecycleActions(APIConstants.API_LIFE_CYCLE);
        // Put next states into map
        lcData.put(APIConstants.LC_NEXT_STATES, actions);
        String lifeCycleState = artifact.getLifecycleState();
        lcData.put(APIConstants.LC_STATUS, lifeCycleState);
        LifecycleBean bean;
        bean = LifecycleBeanPopulator.getLifecycleBean(path, (UserRegistry) registry, configRegistry);
        if (bean != null) {
            ArrayList<CheckListItem> checkListItems = new ArrayList<CheckListItem>();
            ArrayList<String> permissionList = new ArrayList<String>();
            // Get lc properties
            Property[] lifecycleProps = bean.getLifecycleProperties();
            // Get roles of the current session holder
            String[] roleNames = bean.getRolesOfUser();
            for (Property property : lifecycleProps) {
                String propName = property.getKey();
                String[] propValues = property.getValues();
                // Check for permission properties if any exists
                if (propValues != null && propValues.length != 0) {
                    if (propName.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propName.endsWith(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX) && propName.contains(APIConstants.API_LIFE_CYCLE)) {
                        for (String role : roleNames) {
                            for (String propValue : propValues) {
                                String key = propName.replace(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX, "").replace(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX, "");
                                if (propValue.equals(role)) {
                                    permissionList.add(key);
                                } else if (propValue.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propValue.endsWith(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX)) {
                                    permissionList.add(key);
                                }
                            }
                        }
                    }
                }
            }
            // Check for lifecycle checklist item properties defined
            for (Property property : lifecycleProps) {
                String propName = property.getKey();
                String[] propValues = property.getValues();
                if (propValues != null && propValues.length != 0) {
                    CheckListItem checkListItem = new CheckListItem();
                    checkListItem.setVisible("false");
                    if (propName.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propName.endsWith(APIConstants.LC_PROPERTY_ITEM_SUFFIX) && propName.contains(APIConstants.API_LIFE_CYCLE)) {
                        if (propValues.length > 2) {
                            for (String param : propValues) {
                                if (param.startsWith(APIConstants.LC_STATUS)) {
                                    checkListItem.setLifeCycleStatus(param.substring(7));
                                } else if (param.startsWith(APIConstants.LC_CHECK_ITEM_NAME)) {
                                    checkListItem.setName(param.substring(5));
                                } else if (param.startsWith(APIConstants.LC_CHECK_ITEM_VALUE)) {
                                    checkListItem.setValue(param.substring(6));
                                } else if (param.startsWith(APIConstants.LC_CHECK_ITEM_ORDER)) {
                                    checkListItem.setOrder(param.substring(6));
                                }
                            }
                        }
                        String key = propName.replace(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX, "").replace(APIConstants.LC_PROPERTY_ITEM_SUFFIX, "");
                        if (permissionList.contains(key)) {
                            // Set visible to true if the checklist item permits
                            checkListItem.setVisible("true");
                        }
                    }
                    if (checkListItem.matchLifeCycleStatus(lifeCycleState)) {
                        checkListItems.add(checkListItem);
                    }
                }
            }
            lcData.put("items", checkListItems);
        }
    } catch (Exception e) {
        handleException(e.getMessage(), e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return lcData;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CheckListItem(org.wso2.carbon.governance.custom.lifecycles.checklist.util.CheckListItem) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) OMException(org.apache.axiom.om.OMException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) LifecycleBean(org.wso2.carbon.governance.custom.lifecycles.checklist.beans.LifecycleBean) JSONObject(org.json.simple.JSONObject) Property(org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property)

Example 27 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIProviderImpl method checkAccessControlPermission.

/* To check authorization of the API against current logged in user. If the user is not authorized an exception
     * will be thrown.
     *
     * @param identifier API identifier
     * @throws APIManagementException APIManagementException
     */
protected void checkAccessControlPermission(Identifier identifier) throws APIManagementException {
    if (identifier == null || !isAccessControlRestrictionEnabled) {
        if (!isAccessControlRestrictionEnabled && log.isDebugEnabled()) {
            log.debug("Publisher access control restriction is not enabled. Hence the API " + identifier + " can be editable and viewable by all the API publishers and creators.");
        }
        return;
    }
    String resourcePath = StringUtils.EMPTY;
    String identifierType = StringUtils.EMPTY;
    if (identifier instanceof APIIdentifier) {
        resourcePath = APIUtil.getAPIPath((APIIdentifier) identifier);
        identifierType = APIConstants.API_IDENTIFIER_TYPE;
    } else if (identifier instanceof APIProductIdentifier) {
        resourcePath = APIUtil.getAPIProductPath((APIProductIdentifier) identifier);
        identifierType = APIConstants.API_PRODUCT_IDENTIFIER_TYPE;
    }
    try {
        Registry sysRegistry = getRegistryService().getGovernanceSystemRegistry();
        // Need user name with tenant domain to get correct domain name from
        // MultitenantUtils.getTenantDomain(username)
        String userNameWithTenantDomain = (userNameWithoutChange != null) ? userNameWithoutChange : username;
        if (!sysRegistry.resourceExists(resourcePath)) {
            if (log.isDebugEnabled()) {
                log.debug("Resource does not exist in the path : " + resourcePath + " this can happen if this is in the " + "middle of the new " + identifierType + " creation, hence not checking the access control");
            }
            return;
        }
        Resource resource = sysRegistry.get(resourcePath);
        if (resource == null) {
            return;
        }
        String accessControlProperty = resource.getProperty(APIConstants.ACCESS_CONTROL);
        if (accessControlProperty == null || accessControlProperty.trim().isEmpty() || accessControlProperty.equalsIgnoreCase(APIConstants.NO_ACCESS_CONTROL)) {
            if (log.isDebugEnabled()) {
                log.debug(identifierType + " in the path  " + resourcePath + " does not have any access control restriction");
            }
            return;
        }
        if (APIUtil.hasPermission(userNameWithTenantDomain, APIConstants.Permissions.APIM_ADMIN)) {
            return;
        }
        String publisherAccessControlRoles = resource.getProperty(APIConstants.DISPLAY_PUBLISHER_ROLES);
        if (publisherAccessControlRoles != null && !publisherAccessControlRoles.trim().isEmpty()) {
            String[] accessControlRoleList = publisherAccessControlRoles.replaceAll("\\s+", "").split(",");
            if (log.isDebugEnabled()) {
                log.debug(identifierType + " has restricted access to creators and publishers with the roles : " + Arrays.toString(accessControlRoleList));
            }
            String[] userRoleList = APIUtil.getListOfRoles(userNameWithTenantDomain);
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " has roles " + Arrays.toString(userRoleList));
            }
            for (String role : accessControlRoleList) {
                if (!role.equalsIgnoreCase(APIConstants.NULL_USER_ROLE_LIST) && APIUtil.compareRoleList(userRoleList, role)) {
                    return;
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(identifierType + " " + identifier + " cannot be accessed by user '" + username + "'. It " + "has a publisher access control restriction");
            }
            throw new APIManagementException(APIConstants.UN_AUTHORIZED_ERROR_MESSAGE + " view or modify the " + identifierType + " " + identifier);
        }
    } catch (RegistryException e) {
        throw new APIManagementException("Registry Exception while trying to check the access control restriction of " + identifierType + " " + identifier.getName(), e);
    }
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 28 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIThrottleHandlerTest method testMsgThrottleOutWhenApplicationLevelQuotaExceeded.

@Test
public void testMsgThrottleOutWhenApplicationLevelQuotaExceeded() throws XMLStreamException, ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
    authenticationContext.setApplicationTier("Silver");
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 0, 60000, "true"), THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 0, 60000, "true"), THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
    Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn(callerConfiguration);
    // Set application level access state to be ACCESS_DENIED
    Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) Test(org.junit.Test)

Example 29 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIThrottleHandlerTest method testMsgThrottleOutWhenHardLevelQuotaExceededForProductionEndpoint.

@Test
public void testMsgThrottleOutWhenHardLevelQuotaExceededForProductionEndpoint() throws XMLStreamException, ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
    authenticationContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, new VerbInfoDTO());
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000, "true"), THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000, "true"), THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    apiThrottleHandler.setProductionMaxCount(PRODUCTION_MAX_COUNT);
    Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
    Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn(callerConfiguration);
    Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) Test(org.junit.Test)

Example 30 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIUtil method getFilteredUserRoles.

public static String[] getFilteredUserRoles(String username) throws APIManagementException {
    String[] userRoles = APIUtil.getListOfRoles(username);
    String skipRolesByRegex = APIUtil.getSkipRolesByRegex();
    if (StringUtils.isNotEmpty(skipRolesByRegex)) {
        List<String> filteredUserRoles = new ArrayList<>(Arrays.asList(userRoles));
        String[] regexList = skipRolesByRegex.split(",");
        for (int i = 0; i < regexList.length; i++) {
            Pattern p = Pattern.compile(regexList[i]);
            Iterator<String> itr = filteredUserRoles.iterator();
            while (itr.hasNext()) {
                String role = itr.next();
                Matcher m = p.matcher(role);
                if (m.matches()) {
                    itr.remove();
                }
            }
        }
        userRoles = filteredUserRoles.toArray(new String[0]);
    }
    return userRoles;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

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