Search in sources :

Example 91 with Permission

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

the class ThrottlingApiServiceImpl method setPolicyPermissionsToDTO.

/**
 * Set subscription throttle policy permission info into the DTO
 *
 * @param policyDTO subscription throttle policy DTO
 * @throws APIManagementException error while setting/retrieve the permissions to the DTO
 */
private void setPolicyPermissionsToDTO(SubscriptionThrottlePolicyDTO policyDTO) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    TierPermissionDTO addedPolicyPermission = (TierPermissionDTO) apiProvider.getThrottleTierPermission(policyDTO.getPolicyName());
    if (addedPolicyPermission != null) {
        SubscriptionThrottlePolicyPermissionDTO addedPolicyPermissionDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyPermissionToDTO(addedPolicyPermission);
        policyDTO.setPermissions(addedPolicyPermissionDTO);
    }
}
Also used : TierPermissionDTO(org.wso2.carbon.apimgt.impl.dto.TierPermissionDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 92 with Permission

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

the class ThrottlingApiServiceImpl method throttlingPoliciesSubscriptionPost.

/**
 * Add a Subscription Level Throttle Policy
 *
 * @param body        DTO of new policy to be created
 * @param contentType Content-Type header
 * @return Created policy along with the location of it with Location header
 */
@Override
public Response throttlingPoliciesSubscriptionPost(String contentType, SubscriptionThrottlePolicyDTO body, MessageContext messageContext) throws APIManagementException {
    RestApiAdminUtils.validateThrottlePolicyNameProperty(body.getPolicyName());
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        SubscriptionPolicy subscriptionPolicy = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyDTOToModel(body);
        // Check if there's a policy exists before adding the new policy
        try {
            Policy policyIfExists = apiProvider.getSubscriptionPolicy(username, subscriptionPolicy.getPolicyName());
            if (policyIfExists != null) {
                RestApiUtil.handleResourceAlreadyExistsError("Subscription Policy with name " + subscriptionPolicy.getPolicyName() + " already exists", log);
            }
        } catch (PolicyNotFoundException ignore) {
        }
        // validate if permission info exists and halt the execution in case of an error
        validatePolicyPermissions(body);
        // Add the policy
        apiProvider.addPolicy(subscriptionPolicy);
        // update policy permissions
        updatePolicyPermissions(body);
        // retrieve the new policy and send back as the response
        SubscriptionPolicy newSubscriptionPolicy = apiProvider.getSubscriptionPolicy(username, body.getPolicyName());
        SubscriptionThrottlePolicyDTO policyDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyToDTO(newSubscriptionPolicy);
        // setting policy permissions
        setPolicyPermissionsToDTO(policyDTO);
        return Response.created(new URI(RestApiConstants.RESOURCE_PATH_THROTTLING_POLICIES_SUBSCRIPTION + "/" + policyDTO.getPolicyId())).entity(policyDTO).build();
    } catch (ParseException e) {
        String errorMessage = "Error while adding a Subscription level policy: " + body.getPolicyName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving Subscription Throttle policy location : " + body.getPolicyName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) PolicyNotFoundException(org.wso2.carbon.apimgt.api.PolicyNotFoundException) ParseException(org.json.simple.parser.ParseException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 93 with Permission

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

the class PoliciesApiServiceImpl method policiesMediationPost.

/**
 * Add a global mediation policy
 *
 * @param body              Mediation DTO as request body
 * @param contentType       Content-Type header
 * @return created mediation DTO as response
 */
@Override
public Response policiesMediationPost(String contentType, MediationDTO body, MessageContext messageContext) {
    InputStream contentStream = null;
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String content = body.getConfig();
        contentStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
        ResourceFile contentFile = new ResourceFile(contentStream, contentType);
        // Extracting mediation policy name from the mediation config
        String fileName = this.getMediationNameFromConfig(content);
        // constructing the registry resource path
        String mediationPolicyPath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION + RegistryConstants.PATH_SEPARATOR + body.getType() + RegistryConstants.PATH_SEPARATOR + fileName;
        if (apiProvider.checkIfResourceExists(mediationPolicyPath)) {
            RestApiUtil.handleConflict("Mediation policy already exists", log);
        }
        // Adding new global mediation sequence
        // No need to check API permission, hence null as api identifier
        String mediationPolicyUrl = apiProvider.addResourceFile(null, mediationPolicyPath, contentFile);
        if (StringUtils.isNotBlank(mediationPolicyUrl)) {
            // Getting the uuid of the created global mediation policy
            String uuid = apiProvider.getCreatedResourceUuid(mediationPolicyPath);
            // Getting created mediation policy
            Mediation createdMediation = apiProvider.getGlobalMediationPolicy(uuid);
            MediationDTO createdPolicy = MediationMappingUtil.fromMediationToDTO(createdMediation);
            URI uploadedMediationUri = new URI(mediationPolicyUrl);
            return Response.created(uploadedMediationUri).entity(createdPolicy).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding the global mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while getting location header for created " + "mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
    return null;
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) MediationDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MediationDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) URI(java.net.URI)

Example 94 with Permission

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

the class PoliciesApiServiceImpl method policiesMediationMediationPolicyIdPut.

/**
 * Updates an existing global mediation policy
 *
 * @param mediationPolicyId uuid of mediation policy
 * @param body              updated MediationDTO
 * @param contentType       Content-Type header
 * @return updated mediation DTO as response
 */
@Override
public Response policiesMediationMediationPolicyIdPut(String mediationPolicyId, String contentType, MediationDTO body, MessageContext messageContext) {
    InputStream contentStream = null;
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // Get registry resource correspond to given uuid
        Resource mediationResource = apiProvider.getCustomMediationResourceFromUuid(mediationPolicyId);
        if (mediationResource != null) {
            // extracting already existing name of the mediation policy
            String contentString = IOUtils.toString(mediationResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
            // Get policy name from the mediation config
            OMElement omElement = AXIOMUtil.stringToOM(contentString);
            OMAttribute attribute = omElement.getAttribute(new QName(PolicyConstants.MEDIATION_NAME_ATTRIBUTE));
            String existingMediationPolicyName = attribute.getAttributeValue();
            // replacing the name of the body with existing name
            body.setName(existingMediationPolicyName);
            // Getting mediation config to be update from the body
            contentStream = new ByteArrayInputStream(body.getConfig().getBytes(StandardCharsets.UTF_8));
            // Creating new resource file
            ResourceFile contentFile = new ResourceFile(contentStream, contentType);
            // Getting registry path of the existing resource
            String resourcePath = mediationResource.getPath();
            // Updating the existing global mediation policy
            // No need to check API permission, hence null as api identifier
            String updatedPolicyUrl = apiProvider.addResourceFile(null, resourcePath, contentFile);
            if (StringUtils.isNotBlank(updatedPolicyUrl)) {
                // Getting uuid of updated global mediation policy
                String uuid = apiProvider.getCreatedResourceUuid(resourcePath);
                // Getting updated mediation
                Mediation updatedMediation = apiProvider.getGlobalMediationPolicy(uuid);
                MediationDTO updatedMediationDTO = MediationMappingUtil.fromMediationToDTO(updatedMediation);
                URI uploadedMediationUri = new URI(updatedPolicyUrl);
                return Response.ok(uploadedMediationUri).entity(updatedMediationDTO).build();
            }
        } else {
            // If resource not exists
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while updating the global mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while getting location header for uploaded " + "mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (XMLStreamException e) {
        String errorMessage = "Error occurred while converting the existing content stream of " + " mediation " + "policy to string";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (RegistryException e) {
        String errorMessage = "Error occurred while getting the existing content stream ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (IOException e) {
        String errorMessage = "Error occurred while converting content stream in to string ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.api.Resource) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) MediationDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MediationDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) URI(java.net.URI) RegistryException(org.wso2.carbon.registry.api.RegistryException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 95 with Permission

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

the class JWTUtil 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).
 */
public static boolean validateScopes(HashMap<String, Object> message, OAuthTokenInfo tokenInfo) {
    String basePath = (String) message.get(RestApiConstants.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(RestApiConstants.REQUEST_URL);
    String verb = (String) message.get(RestApiConstants.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 = (Set<URITemplate>) message.get(RestApiConstants.URI_TEMPLATES);
    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 : Set(java.util.Set) 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)

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