Search in sources :

Example 31 with Roles

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

the class APIProviderImpl method updateApiArtifact.

private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        Resource apiResource = registry.get(artifact.getPath());
        String oldAccessControlRoles = api.getAccessControlRoles();
        if (apiResource != null) {
            oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
        }
        GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
        org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
        if (oldTags != null) {
            for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
                registry.removeTag(artifactPath, tag.getTagName());
            }
        }
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
            // If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
            // will skip registry update. Only if this API created with WSDL end point type we need to update
            // wsdls for each update.
            // check for wsdl endpoint
            org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
            boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
            String wsdlURL;
            if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
                wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
                if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
                    String path = APIUtil.createWSDL(registry, api);
                    if (path != null) {
                        // reset the wsdl path to permlink
                        updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
                    }
                }
            }
        }
        artifactManager.updateGenericArtifact(updateApiArtifact);
        // write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
        // to gain performance
        String apiStatus = api.getStatus().toUpperCase();
        saveAPIStatus(artifactPath, apiStatus);
        String[] visibleRoles = new String[0];
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        // propagate api status change and access control roles change to document artifact
        String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
            APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
        }
        if (updatePermissions) {
            APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
            String visibleRolesList = api.getVisibleRoles();
            if (visibleRolesList != null) {
                visibleRoles = visibleRolesList.split(",");
            }
            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        }
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = api.getApiCategories();
        artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
        if (attachedApiCategories != null) {
            for (APICategory category : attachedApiCategories) {
                artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
        apiUUID = updateApiArtifact.getId();
        if (updatePermissions) {
            APIManagerConfiguration config = getAPIManagerConfiguration();
            boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
            String docRootPath = APIUtil.getAPIDocPath(api.getId());
            if (isSetDocLevelPermissions) {
                // Retain the docs
                List<Documentation> docs = getAllDocumentation(api.getId());
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                        } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                            String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                        }
                    }
                }
            } else {
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
            }
        } else {
            // In order to support content search feature - we need to update resource permissions of document resources
            // if their visibility is set to API level.
            List<Documentation> docs = getAllDocumentation(api.getId());
            if (docs != null) {
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                    }
                }
            }
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error from this level will mask the original exception
            log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
        }
        handleException("Error while performing registry transaction operation", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error occurred while rolling back the transaction.", ex);
        }
    }
    return apiUUID;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) 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) JSONObject(org.json.simple.JSONObject) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 32 with Roles

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

the class APIConsumerImpl method getAllowedScopesForUserApplication.

private static List<Scope> getAllowedScopesForUserApplication(String username, Set<Scope> reqScopeSet) {
    String[] userRoles = null;
    org.wso2.carbon.user.api.UserStoreManager userStoreManager = null;
    String preservedCaseSensitiveValue = System.getProperty(PRESERVED_CASE_SENSITIVE_VARIABLE);
    boolean preservedCaseSensitive = JavaUtils.isTrueExplicitly(preservedCaseSensitiveValue);
    List<Scope> authorizedScopes = new ArrayList<Scope>();
    try {
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(MultitenantUtils.getTenantDomain(username));
        userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username));
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        // Log and return since we do not want to stop issuing the token in
        // case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
    }
    List<String> userRoleList;
    if (userRoles != null) {
        if (preservedCaseSensitive) {
            userRoleList = Arrays.asList(userRoles);
        } else {
            userRoleList = new ArrayList<String>();
            for (String userRole : userRoles) {
                userRoleList.add(userRole.toLowerCase());
            }
        }
    } else {
        userRoleList = Collections.emptyList();
    }
    // Iterate the requested scopes list.
    for (Scope scope : reqScopeSet) {
        // Get the set of roles associated with the requested scope.
        String roles = scope.getRoles();
        // If the scope has been defined in the context of the App and if roles have been defined for the scope
        if (roles != null && roles.length() != 0) {
            List<String> roleList = new ArrayList<String>();
            for (String scopeRole : roles.split(",")) {
                if (preservedCaseSensitive) {
                    roleList.add(scopeRole.trim());
                } else {
                    roleList.add(scopeRole.trim().toLowerCase());
                }
            }
            // Check if user has at least one of the roles associated with the scope
            roleList.retainAll(userRoleList);
            if (!roleList.isEmpty()) {
                authorizedScopes.add(scope);
            }
        }
    }
    return authorizedScopes;
}
Also used : UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ArrayList(java.util.ArrayList) Scope(org.wso2.carbon.apimgt.api.model.Scope) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 33 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles 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 34 with Roles

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

the class APIUtil method setResourcePermissions.

/**
 * This function is to set resource permissions based on its visibility
 *
 * @param visibility   API/Product visibility
 * @param roles        Authorized roles
 * @param artifactPath API/Product resource path
 * @param registry     Registry
 * @throws APIManagementException Throwing exception
 */
public static void setResourcePermissions(String username, String visibility, String[] roles, String artifactPath, Registry registry) throws APIManagementException {
    try {
        String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
        Resource registryResource = null;
        if (registry != null && registry.resourceExists(artifactPath)) {
            registryResource = registry.get(artifactPath);
        }
        StringBuilder publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
        if (registryResource != null) {
            String publisherRole = registryResource.getProperty(APIConstants.PUBLISHER_ROLES);
            if (publisherRole != null) {
                publisherAccessRoles = new StringBuilder(publisherRole);
            }
            if (StringUtils.isEmpty(publisherAccessRoles.toString())) {
                publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
            }
            if (APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(visibility) || APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
                // set publisher
                publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
            // access roles null since store visibility is global. We do not need to add any roles to
            // store_view_role property.
            } else {
                registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
            }
        }
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            // 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 (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
                boolean isRoleEveryOne = false;
                /*If no roles have defined, authorize for everyone role */
                if (roles != null) {
                    if (roles.length == 1 && "".equals(roles[0])) {
                        authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                        isRoleEveryOne = true;
                    } else {
                        for (String role : roles) {
                            if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
                                isRoleEveryOne = true;
                            }
                            authManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
                            publisherAccessRoles.append(",").append(role.trim().toLowerCase());
                        }
                    }
                }
                if (!isRoleEveryOne) {
                    authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                }
                authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
                /*If no roles have defined, deny access for everyone & anonymous role */
                if (roles == null) {
                    authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                    authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                } else {
                    for (String role : roles) {
                        authManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
                    }
                }
            } else {
                authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            }
        } else {
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
                boolean isRoleEveryOne = false;
                if (roles != null) {
                    for (String role : roles) {
                        if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
                            isRoleEveryOne = true;
                        }
                        authorizationManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
                        publisherAccessRoles.append(",").append(role.toLowerCase());
                    }
                }
                if (!isRoleEveryOne) {
                    authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                }
                authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
                /*If no roles have defined, deny access for everyone & anonymous role */
                if (roles == null) {
                    authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                    authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                } else {
                    for (String role : roles) {
                        authorizationManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Store view roles for " + artifactPath + " : " + publisherAccessRoles.toString());
                }
                authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            }
        }
        if (registryResource != null) {
            registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
            registry.put(artifactPath, registryResource);
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while adding role permissions to API", e);
    } catch (RegistryException e) {
        throw new APIManagementException("Registry exception while adding role permissions to API", e);
    }
}
Also used : Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 35 with Roles

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

the class BasicAuthCredentialValidator method validateScopes.

/**
 * Validates the roles of the given user against the roles of the scopes of the API resource.
 *
 * @param username     given username
 * @param openAPI      OpenAPI of the API
 * @param synCtx       The message to be authenticated
 * @param userRoleList The list of roles of the user
 * @return true if the validation passed
 * @throws APISecurityException If an authentication failure or some other error occurs
 */
@MethodStats
public boolean validateScopes(String username, OpenAPI openAPI, MessageContext synCtx, BasicAuthValidationInfoDTO basicAuthValidationInfoDTO) throws APISecurityException {
    String[] userRoleList = basicAuthValidationInfoDTO.getUserRoleList();
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String apiElectedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String httpMethod = (String) axis2MessageContext.getProperty(APIConstants.DigestAuthConstants.HTTP_METHOD);
    String resourceKey = apiContext + ":" + apiVersion + ":" + apiElectedResource + ":" + httpMethod;
    Map<String, Scope> scopeMap = apiKeyValidator.retrieveScopes(tenantDomain);
    String resourceCacheKey = resourceKey + ":" + username;
    if (gatewayKeyCacheEnabled && getGatewayBasicAuthResourceCache().get(resourceCacheKey) != null && basicAuthValidationInfoDTO.isCached()) {
        return true;
    }
    if (openAPI != null) {
        // retrieve the user roles related to the scope of the API resource
        List<String> resourceScopes = OpenAPIUtils.getScopesOfResource(openAPI, synCtx);
        if (resourceScopes != null && resourceScopes.size() > 0) {
            for (String resourceScope : resourceScopes) {
                Scope scope = scopeMap.get(resourceScope);
                if (scope != null) {
                    if (scope.getRoles().isEmpty()) {
                        log.debug("Scope " + resourceScope + " didn't have roles");
                        if (gatewayKeyCacheEnabled) {
                            getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
                        }
                        return true;
                    } else {
                        // any of the role of the user
                        if (validateInternalUserRoles(scope.getRoles(), userRoleList)) {
                            if (gatewayKeyCacheEnabled) {
                                getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
                            }
                            return true;
                        }
                        // check if the roles related to the API resource contains any of the role of the user
                        for (String role : userRoleList) {
                            if (scope.getRoles().contains(role)) {
                                if (gatewayKeyCacheEnabled) {
                                    getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
                                }
                                return true;
                            }
                        }
                    }
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Basic Authentication: No scopes for the API resource: ".concat(resourceKey));
            }
            return true;
        }
    } else if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        HashMap<String, String> operationScopeMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.SCOPE_OPERATION_MAPPING);
        String[] operationList = ((String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).split(",");
        for (String operation : operationList) {
            String operationScope = operationScopeMappingList.get(operation);
            if (operationScope != null) {
                if (scopeMap.containsKey(operationScope)) {
                    List<String> operationRoles = scopeMap.get(operationScope).getRoles();
                    boolean userHasOperationRole = false;
                    if (operationRoles.isEmpty()) {
                        userHasOperationRole = true;
                    } else {
                        for (String role : userRoleList) {
                            if (operationRoles.contains(role)) {
                                userHasOperationRole = true;
                                break;
                            }
                        }
                    }
                    if (!userHasOperationRole) {
                        throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
                    }
                } else {
                    throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
                }
            }
        }
        if (gatewayKeyCacheEnabled) {
            getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
        }
        return true;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Basic Authentication: No OpenAPI found in the gateway for the API: ".concat(apiContext).concat(":").concat(apiVersion));
        }
        return true;
    }
    if (log.isDebugEnabled()) {
        log.debug("Basic Authentication: Scope validation failed for the API resource: ".concat(apiElectedResource));
    }
    throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) Scope(org.wso2.carbon.apimgt.keymgt.model.entity.Scope) HashMap(java.util.HashMap) List(java.util.List) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

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