Search in sources :

Example 41 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class RestApiUtil method buildForbiddenException.

/**
 * Returns a new ForbiddenException
 *
 * @param resource Resource type
 * @param id identifier of the resource
 * @return a new ForbiddenException with the specified details as a response DTO
 */
public static ForbiddenException buildForbiddenException(String resource, String id) {
    String description;
    if (!StringUtils.isEmpty(id)) {
        description = "You don't have permission to access the " + resource + " with Id " + id;
    } else {
        description = "You don't have permission to access the " + resource;
    }
    ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, description);
    return new ForbiddenException(errorDTO);
}
Also used : ForbiddenException(org.wso2.carbon.apimgt.rest.api.util.exception.ForbiddenException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)

Example 42 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class SubscriberRegistrationInterceptor method handleMessage.

/**
 * Handles the incoming message after post authentication. Only used in Store REST API, to register a newly
 * signed up store user who hasn't logged in to Store for the first time either via REST API or Store UI.
 * This method will register the user as a subscriber
 * (register in AM_SUBSCRIBER table, add the default application for subscriber etc.).
 *
 * @param message cxf message
 */
@Override
@MethodStats
public void handleMessage(Message message) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    // by-passes the interceptor if user is an annonymous user
    if (username.equalsIgnoreCase(APIConstants.WSO2_ANONYMOUS_USER)) {
        return;
    }
    // checking if the subscriber exists in the subscriber cache
    Cache<String, Subscriber> subscriberCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.API_SUBSCRIBER_CACHE);
    if (subscriberCache.get(username) != null) {
        return;
    }
    // check the existence in the database
    String groupId = RestApiUtil.getLoggedInUserGroupId();
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    try {
        // takes a consumer object using the user set in thread local carbon context
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        Subscriber subscriber = apiConsumer.getSubscriber(username);
        if (subscriber == null) {
            synchronized ((username + LOCK_POSTFIX).intern()) {
                subscriber = apiConsumer.getSubscriber(username);
                if (subscriber == null) {
                    message.getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
                    if (!hasSubscribeScope(message)) {
                        // permission. It should be allowed.
                        if (logger.isDebugEnabled()) {
                            logger.debug("User " + username + " does not have subscribe scope " + "(" + APIM_SUBSCRIBE_SCOPE + ")");
                        }
                        return;
                    }
                    if (!APIConstants.SUPER_TENANT_DOMAIN.equalsIgnoreCase(tenantDomain)) {
                        loadTenantRegistry();
                    }
                    apiConsumer.addSubscriber(username, groupId);
                    // The subscriber object added here is not a complete subscriber object. It will only contain
                    // username
                    subscriberCache.put(username, new Subscriber(username));
                    if (logger.isDebugEnabled()) {
                        logger.debug("Subscriber " + username + " added to AM_SUBSCRIBER database");
                    }
                }
            }
        } else {
            subscriberCache.put(username, subscriber);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Unable to add the subscriber " + username, e, logger);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 43 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class AbstractOAuthAuthenticator method validateScopes.

/**
 * @param message   CXF message to be validate
 * @param tokenInfo Token information associated with incoming request
 * @return return true if we found matching scope in resource and token information
 * else false(means scope validation failed).
 */
@MethodStats
public boolean validateScopes(Message message, OAuthTokenInfo tokenInfo) {
    String basePath = (String) message.get(Message.BASE_PATH);
    // path is obtained from Message.REQUEST_URI instead of Message.PATH_INFO, as Message.PATH_INFO contains
    // decoded values of request parameters
    String path = (String) message.get(Message.REQUEST_URI);
    String verb = (String) message.get(Message.HTTP_REQUEST_METHOD);
    String resource = path.substring(basePath.length() - 1);
    String[] scopes = tokenInfo.getScopes();
    String version = (String) message.get(RestApiConstants.API_VERSION);
    // get all the URI templates of the REST API from the base path
    Set<URITemplate> uriTemplates = RestApiUtil.getURITemplatesForBasePath(basePath + version);
    if (uriTemplates.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No matching scopes found for request with path: " + basePath + ". Skipping scope validation.");
        }
        return true;
    }
    for (Object template : uriTemplates.toArray()) {
        org.wso2.uri.template.URITemplate templateToValidate = null;
        Map<String, String> var = new HashMap<String, String>();
        // check scopes with what we have
        String templateString = ((URITemplate) template).getUriTemplate();
        try {
            templateToValidate = new org.wso2.uri.template.URITemplate(templateString);
        } catch (URITemplateException e) {
            log.error("Error while creating URI Template object to validate request. Template pattern: " + templateString, e);
        }
        if (templateToValidate != null && templateToValidate.matches(resource, var) && scopes != null && verb != null && verb.equalsIgnoreCase(((URITemplate) template).getHTTPVerb())) {
            for (String scope : scopes) {
                Scope scp = ((URITemplate) template).getScope();
                if (scp != null) {
                    if (scope.equalsIgnoreCase(scp.getKey())) {
                        // we found scopes matches
                        if (log.isDebugEnabled()) {
                            log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scp.getKey() + " for resource path: " + path + " and verb " + verb);
                        }
                        return true;
                    }
                } else if (!((URITemplate) template).retrieveAllScopes().isEmpty()) {
                    List<Scope> scopesList = ((URITemplate) template).retrieveAllScopes();
                    for (Scope scpObj : scopesList) {
                        if (scope.equalsIgnoreCase(scpObj.getKey())) {
                            // we found scopes matches
                            if (log.isDebugEnabled()) {
                                log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scpObj.getKey() + " for resource path: " + path + " and verb " + verb);
                            }
                            return true;
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Scope not defined in swagger for matching resource " + resource + " and verb " + verb + " . So consider as anonymous permission and let request to continue.");
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : HashMap(java.util.HashMap) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) URITemplateException(org.wso2.uri.template.URITemplateException) Scope(org.wso2.carbon.apimgt.api.model.Scope) List(java.util.List) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 44 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class PublisherCommonUtils method prepareToCreateAPIByDTO.

/**
 * Prepares the API Model object to be created using the DTO object.
 *
 * @param body        APIDTO of the API
 * @param apiProvider API Provider
 * @param username    Username
 * @param organization  Organization Identifier
 * @return API object to be created
 * @throws APIManagementException Error while creating the API
 */
public static API prepareToCreateAPIByDTO(APIDTO body, APIProvider apiProvider, String username, String organization) throws APIManagementException {
    String context = body.getContext();
    // Make sure context starts with "/". ex: /pizza
    context = context.startsWith("/") ? context : ("/" + context);
    if (body.getAccessControlRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateUserRoles(body.getAccessControlRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (body.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(body.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, body.getName(), body.getVersion()));
        }
    }
    if (body.getContext() == null) {
        throw new APIManagementException("Parameter: \"context\" cannot be null", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    } else if (body.getContext().endsWith("/")) {
        throw new APIManagementException("Context cannot end with '/' character", ExceptionCodes.INVALID_CONTEXT);
    }
    if (apiProvider.isApiNameWithDifferentCaseExist(body.getName())) {
        throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists.", ExceptionCodes.from(ExceptionCodes.API_NAME_ALREADY_EXISTS, body.getName()));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
    }
    if (body.getVisibility() == APIDTO.VisibilityEnum.RESTRICTED && body.getVisibleRoles().isEmpty()) {
        throw new APIManagementException("Valid roles should be added under 'visibleRoles' to restrict " + "the visibility", ExceptionCodes.USER_ROLES_CANNOT_BE_NULL);
    }
    if (body.getVisibleRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateRoles(body.getVisibleRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    // Get all existing versions of  api been adding
    List<String> apiVersions = apiProvider.getApiVersionsMatchingApiNameAndOrganization(body.getName(), username, organization);
    if (apiVersions.size() > 0) {
        // If any previous version exists
        for (String version : apiVersions) {
            if (version.equalsIgnoreCase(body.getVersion())) {
                // If version already exists
                if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
                    throw new APIManagementException("Error occurred while " + "adding the API. A duplicate API already exists for " + context + " in the organization : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                } else {
                    throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists with different context" + context + " in the organization" + " : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                }
            }
        }
    } else {
        // If no any previous version exists
        if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
            throw new APIManagementException("Error occurred while adding the API. A duplicate API context already exists for " + context + " in the organization" + " : " + organization, ExceptionCodes.from(ExceptionCodes.API_CONTEXT_ALREADY_EXISTS, context));
        }
    }
    // Check if the user has admin permission before applying a different provider than the current user
    String provider = body.getProvider();
    if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
        if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
            }
            provider = username;
        } else {
            if (!APIUtil.isUserExist(provider)) {
                throw new APIManagementException("Specified provider " + provider + " not exist.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
            }
        }
    } else {
        // Set username in case provider is null or empty
        provider = username;
    }
    List<String> tiersFromDTO = body.getPolicies();
    // check whether the added API's tiers are all valid
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
    if (invalidTiers.size() > 0) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    APIPolicy apiPolicy = apiProvider.getAPIPolicy(username, body.getApiThrottlingPolicy());
    if (apiPolicy == null && body.getApiThrottlingPolicy() != null) {
        throw new APIManagementException("Specified policy " + body.getApiThrottlingPolicy() + " is invalid", ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
    }
    API apiToAdd = APIMappingUtil.fromDTOtoAPI(body, provider);
    // only allow CREATED as the stating state for the new api if not status is PROTOTYPED
    if (!APIConstants.PROTOTYPED.equals(apiToAdd.getStatus())) {
        apiToAdd.setStatus(APIConstants.CREATED);
    }
    if (!apiToAdd.isAdvertiseOnly() || StringUtils.isBlank(apiToAdd.getApiOwner())) {
        // we are setting the api owner as the logged in user until we support checking admin privileges and
        // assigning the owner as a different user
        apiToAdd.setApiOwner(provider);
    }
    if (body.getKeyManagers() instanceof List) {
        apiToAdd.setKeyManagers((List<String>) body.getKeyManagers());
    } else if (body.getKeyManagers() == null) {
        apiToAdd.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    } else {
        throw new APIManagementException("KeyManagers value need to be an array");
    }
    // Set default gatewayVendor
    if (body.getGatewayVendor() == null) {
        apiToAdd.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
    }
    apiToAdd.setOrganization(organization);
    return apiToAdd;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 45 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class ThrottlingPolicyMappingUtil method setTierPermissions.

/**
 * Fills the tier information on TierDTO
 *
 * @param throttlingPolicyDTO Object Containing throttling policy DTOs
 * @param throttlingPolicy    Throttling Policy object
 * @return ThrottlingPolicyDTO with permission info
 */
public static ThrottlingPolicyDTO setTierPermissions(ThrottlingPolicyDTO throttlingPolicyDTO, Tier throttlingPolicy) {
    ThrottlingPolicyPermissionInfoDTO tierPermission = new ThrottlingPolicyPermissionInfoDTO();
    // If no permission found for the tier, the default permission will be applied
    if (throttlingPolicy.getTierPermission() == null || throttlingPolicy.getTierPermission().getPermissionType() == null) {
        tierPermission.setType(ThrottlingPolicyPermissionInfoDTO.TypeEnum.valueOf("ALLOW"));
        List<String> roles = new ArrayList<>();
        roles.add("Internal/everyone");
        tierPermission.setRoles(roles);
    } else {
        String permissionType = throttlingPolicy.getTierPermission().getPermissionType();
        tierPermission.setType(ThrottlingPolicyPermissionInfoDTO.TypeEnum.valueOf(permissionType.toUpperCase()));
        tierPermission.setRoles(Arrays.asList(throttlingPolicy.getTierPermission().getRoles()));
    }
    throttlingPolicyDTO.setThrottlingPolicyPermissions(tierPermission);
    return throttlingPolicyDTO;
}
Also used : ArrayList(java.util.ArrayList) ThrottlingPolicyPermissionInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ThrottlingPolicyPermissionInfoDTO)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)29 HashSet (java.util.HashSet)18 HashMap (java.util.HashMap)17 ArrayList (java.util.ArrayList)16 Test (org.testng.annotations.Test)16 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)16 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 API (org.wso2.carbon.apimgt.core.models.API)15 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)15 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)13 Map (java.util.Map)12 Resource (org.wso2.carbon.registry.core.Resource)12 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)12 API (org.wso2.carbon.apimgt.api.model.API)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)9 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)9 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)8