Search in sources :

Example 46 with Permission

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

the class APIPublisherImplTestCase method testUpdateAPIException.

@Test(description = "Exception when updating API")
public void testUpdateAPIException() throws APIManagementException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Policy apiPolicy = new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY);
    apiPolicy.setUuid(UUID.randomUUID().toString());
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(apiPolicy);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, apiLifecycleManager, gatewaySourceGenerator, gateway, policyDAO);
    API.APIBuilder api = SampleTestObjectCreator.createDefaultAPI();
    String uuid = api.getId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.build());
    Mockito.when(identityProvider.getRoleId(ADMIN_ROLE)).thenReturn(ADMIN_ROLE_ID);
    Mockito.when(identityProvider.getRoleId(DEVELOPER_ROLE)).thenReturn(DEVELOPER_ROLE_ID);
    // APIMgtDAOException
    Mockito.doThrow(new APIMgtDAOException("Error occurred while updating the API - " + api.getName())).when(apiDAO).updateAPI(uuid, api.build());
    Mockito.when(apiDAO.getApiSwaggerDefinition(api.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
    try {
        apiPublisher.updateAPI(api);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while updating the API - " + api.getName());
    }
    // ParseException
    try {
        apiPublisher.updateAPI(api.apiPermission("data{{]"));
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while parsing the permission json from swagger - " + api.getName());
    }
    // GatewayException
    Mockito.doThrow(GatewayException.class).when(gateway).updateAPI(api.apiPermission("").build());
    try {
        apiPublisher.updateAPI(api.apiPermission(""));
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while updating API - " + api.getName() + " in gateway");
    }
    // Error path
    // When Parse Exception is thrown during getAPIByUUID - replacing group ids with names
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.apiPermission("data{{]").build());
    try {
        apiPublisher.updateAPI(api.apiPermission("data{{]"));
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while parsing the permission json string for API " + api.getName());
    }
}
Also used : SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) Test(org.testng.annotations.Test)

Example 47 with Permission

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

the class APIPublisherImplTestCase method testAddDocumentationInfo.

@Test(description = "Add Documentation Info")
public void testAddDocumentationInfo() throws APIManagementException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    DocumentInfo documentInfo = new DocumentInfo.Builder().fileName("sample_doc.pdf").name("howto_guide").id(DOC_ID).permission("[{\"groupId\": \"testGroup\",\"permission\":[\"READ\",\"UPDATE\",\"DELETE\"]}]").build();
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO);
    apiPublisher.addDocumentationInfo(API_ID, documentInfo);
    Mockito.verify(apiDAO, Mockito.times(1)).addDocumentInfo(API_ID, documentInfo);
}
Also used : ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo) Test(org.testng.annotations.Test)

Example 48 with Permission

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

the class OAuth2Authenticator method validateScopes.

/*
    * This method validates the given scope against scopes defined in the api resource
    * @param Request
    * @param ServiceMethodInfo
    * @param scopesToValidate scopes extracted from the access token
    * @return true if scope validation successful
    * */
@SuppressFBWarnings({ "DLS_DEAD_LOCAL_STORE" })
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate, String restAPIResource) throws APIMgtSecurityException {
    final boolean[] authorized = { false };
    String path = (String) request.getProperty(APIConstants.REQUEST_URL);
    String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
    if (log.isDebugEnabled()) {
        log.debug("Invoking rest api resource path " + verb + " " + path + " ");
        log.debug("LoggedIn user scopes " + scopesToValidate);
    }
    String[] scopesArr = new String[0];
    if (scopesToValidate != null) {
        scopesArr = scopesToValidate.split(" ");
    }
    if (scopesToValidate != null && scopesArr.length > 0) {
        final List<String> scopes = Arrays.asList(scopesArr);
        if (restAPIResource != null) {
            APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
            try {
                String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request, serviceMethodInfo);
                if (StringUtils.isEmpty(apiResourceDefinitionScopes)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Scope not defined in swagger for matching resource " + path + " and verb " + verb + " . Hence consider as anonymous permission and let request to continue.");
                    }
                    // scope validation gets through if no scopes found in the api definition
                    authorized[0] = true;
                } else {
                    Arrays.stream(apiResourceDefinitionScopes.split(" ")).forEach(scopeKey -> {
                        Optional<String> key = scopes.stream().filter(scp -> {
                            return scp.equalsIgnoreCase(scopeKey);
                        }).findAny();
                        if (key.isPresent()) {
                            // scope validation success if one of the
                            authorized[0] = true;
                        // apiResourceDefinitionScopes found.
                        }
                    });
                }
            } catch (APIManagementException e) {
                String message = "Error while validating scopes";
                log.error(message, e);
                throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Rest API resource could not be found for request path '" + path + "'");
            }
        }
    } else {
        // scope validation gets through if access token does not contain scopes to validate
        authorized[0] = true;
    }
    if (!authorized[0]) {
        String message = "Scope validation fails for the scopes " + scopesToValidate;
        throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
    }
    return authorized[0];
}
Also used : Arrays(java.util.Arrays) TypeToken(com.google.gson.reflect.TypeToken) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) RESTAPIAuthenticator(org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator) LoggerFactory(org.slf4j.LoggerFactory) Request(org.wso2.msf4j.Request) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) APIManagerFactory(org.wso2.carbon.apimgt.core.impl.APIManagerFactory) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) StringUtils(org.apache.commons.lang3.StringUtils) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) RestApiUtil(org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) Response(org.wso2.msf4j.Response) Locale(java.util.Locale) APIDefinition(org.wso2.carbon.apimgt.core.api.APIDefinition) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) Logger(org.slf4j.Logger) APIConstants(org.wso2.carbon.apimgt.rest.api.common.APIConstants) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) SystemVariableUtil(org.wso2.msf4j.util.SystemVariableUtil) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Optional(java.util.Optional) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) APIDefinition(org.wso2.carbon.apimgt.core.api.APIDefinition) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 49 with Permission

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

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
    businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add("testRple");
    List<String> labels = new ArrayList<>();
    labels.add("testLabel");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put("TestEndpoint", createMockEndpoint());
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 50 with Permission

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

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    List<String> defaultLabels = getDefaultLabels();
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).labels(defaultLabels).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(new HashSet<>()).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).securityScheme(3).threatProtectionPolicies(threatProtectionPolicies);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) ThreatProtectionPolicy(org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) HashMap(java.util.HashMap) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

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