Search in sources :

Example 1 with AuthorizationManager

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

the class APIConsumerImpl method isCandidateAPI.

private boolean isCandidateAPI(String apiPath, String loggedUsername, GenericArtifactManager artifactManager, int tenantId, boolean showAllAPIs, boolean allowMultipleVersions, String apiOwner, String providerId, Registry registry, Map<String, API> apiCollection) throws UserStoreException, RegistryException, APIManagementException {
    AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
    Comparator<API> versionComparator = new APIVersionComparator();
    Resource resource;
    String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
    boolean checkAuthorized;
    String userNameWithoutDomain = loggedUsername;
    if (!loggedUsername.isEmpty() && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(super.tenantDomain)) {
        String[] nameParts = loggedUsername.split("@");
        userNameWithoutDomain = nameParts[0];
    }
    int loggedInUserTenantDomain = -1;
    if (!StringUtils.isEmpty(loggedUsername)) {
        loggedInUserTenantDomain = APIUtil.getTenantId(loggedUsername);
    }
    if (loggedUsername.isEmpty()) {
        // Anonymous user is viewing.
        checkAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
    } else if (tenantId != loggedInUserTenantDomain) {
        // Cross tenant scenario
        providerId = APIUtil.replaceEmailDomainBack(providerId);
        String[] nameParts = providerId.split("@");
        String provideNameWithoutDomain = nameParts[0];
        checkAuthorized = manager.isUserAuthorized(provideNameWithoutDomain, path, ActionConstants.GET);
    } else {
        // Some user is logged in also user and api provider tenant domain are same.
        checkAuthorized = manager.isUserAuthorized(userNameWithoutDomain, path, ActionConstants.GET);
    }
    String apiArtifactId = null;
    if (checkAuthorized) {
        resource = registry.get(apiPath);
        apiArtifactId = resource.getUUID();
    }
    if (apiArtifactId != null) {
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        // check the API status
        String status = APIUtil.getLcStateFromArtifact(artifact);
        API api = null;
        // Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
        if (!showAllAPIs) {
            // then we are only interested in published APIs here...
            if (APIConstants.PUBLISHED.equals(status)) {
                api = APIUtil.getAPI(artifact);
            }
        } else {
            // else we are interested in both deprecated/published APIs here...
            if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
                api = APIUtil.getAPI(artifact);
            }
        }
        if (api != null) {
            String apiVisibility = api.getVisibility();
            if (!StringUtils.isEmpty(apiVisibility) && !APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(apiVisibility)) {
                String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
                String loginUserDomain = MultitenantUtils.getTenantDomain(loggedUsername);
                if (!StringUtils.isEmpty(providerDomain) && !StringUtils.isEmpty(loginUserDomain) && !providerDomain.equals(loginUserDomain)) {
                    return false;
                }
            }
            // apiOwner is the value coming from front end and compared against the API instance
            if (apiOwner != null && !apiOwner.isEmpty()) {
                if (APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && api.getApiOwner() != null && !api.getApiOwner().isEmpty() && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    // reject remote APIs when local admin user's API selected
                    return false;
                } else if (!APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    // reject local admin's APIs when remote API selected
                    return false;
                }
            }
            String key;
            // Check the configuration to allow showing multiple versions of an API true/false
            if (!allowMultipleVersions) {
                // If allow only showing the latest version of an API
                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                API existingAPI = apiCollection.get(key);
                if (existingAPI != null) {
                    // this one has a higher version number
                    if (versionComparator.compare(api, existingAPI) > 0) {
                        apiCollection.put(key, api);
                        return true;
                    }
                } else {
                    // We haven't seen this API before
                    apiCollection.put(key, api);
                    return true;
                }
            } else {
                // If allow showing multiple versions of an API
                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName() + COLON_CHAR + api.getId().getVersion();
                // we're not really interested in the key, so generate one for the sake of adding this element to
                // the map.
                key = key + '_' + apiCollection.size();
                apiCollection.put(key, api);
                return true;
            }
        }
    }
    return false;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) Resource(org.wso2.carbon.registry.core.Resource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager)

Example 2 with AuthorizationManager

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

the class APIManagerComponentTest method testShouldActivateWhenAllPrerequisitesMet.

@Test
public void testShouldActivateWhenAllPrerequisitesMet() throws Exception {
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(AuthorizationUtils.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(SQLConstantManagerFactory.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    ComponentContext componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService configurationService = Mockito.mock(APIManagerConfigurationService.class);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    Registry registry = Mockito.mock(Registry.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    OutputEventAdapterService adapterService = Mockito.mock(OutputEventAdapterService.class);
    ThrottleProperties throttleProperties = new ThrottleProperties();
    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.doNothing().when(authManager).authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Mockito.doNothing().when(adapterService).create(null);
    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("").thenReturn(null);
    Mockito.when(bundleContext.registerService("", CommonConfigDeployer.class, null)).thenReturn(null);
    Mockito.when(authManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(configurationService);
    Mockito.when(serviceReferenceHolder.getOutputEventAdapterService()).thenReturn(adapterService);
    Mockito.when(configurationService.getAPIManagerConfiguration()).thenReturn(configuration);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(configuration.getThrottleProperties()).thenReturn(throttleProperties);
    PowerMockito.doNothing().when(APIMgtDBUtil.class, "initialize");
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantExternalStoreConfig", Mockito.anyString());
    PowerMockito.doNothing().when(AuthorizationUtils.class, "addAuthorizeRoleListener", Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    PowerMockito.doNothing().when(SQLConstantManagerFactory.class, "initializeSQLConstantManager");
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    APIManagerComponent apiManagerComponent = new APIManagerComponentWrapper(registry);
    GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
    Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setInitDelay(0);
    eventHubConfigurationDto.setUsername("a");
    eventHubConfigurationDto.setPassword("sss".toCharArray());
    eventHubConfigurationDto.setServiceUrl("https://localhost");
    EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = new EventHubConfigurationDto.EventHubPublisherConfiguration();
    eventHubConfigurationDto.setEventHubPublisherConfiguration(eventHubPublisherConfiguration);
    Mockito.when(config.getEventHubConfigurationDto()).thenReturn(eventHubConfigurationDto);
    try {
        apiManagerComponent.activate(componentContext);
    } catch (FileNotFoundException f) {
        // Exception thrown here means that method was continued without the configuration file
        Assert.fail("Should not throw an exception");
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) ComponentContext(org.osgi.service.component.ComponentContext) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) FileNotFoundException(java.io.FileNotFoundException) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) Registry(org.wso2.carbon.registry.api.Registry) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) OutputEventAdapterService(org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService) APIManagerComponentWrapper(org.wso2.carbon.apimgt.impl.internal.util.APIManagerComponentWrapper) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) BundleContext(org.osgi.framework.BundleContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with AuthorizationManager

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

the class APIUtil method clearResourcePermissions.

/**
 * This function is to set resource permissions based on its visibility
 *
 * @param artifactPath API/Product resource path
 * @throws APIManagementException Throwing exception
 */
public static void clearResourcePermissions(String artifactPath, Identifier id, int tenantId) throws APIManagementException {
    try {
        String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(id.getProviderName()));
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            authManager.clearResourceAuthorizations(resourcePath);
        } else {
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            authorizationManager.clearResourceAuthorizations(resourcePath);
        }
    } catch (UserStoreException e) {
        handleException("Error while adding role permissions to API", e);
    }
}
Also used : RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 4 with AuthorizationManager

use of org.wso2.carbon.user.api.AuthorizationManager 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 5 with AuthorizationManager

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

the class APIProviderImplTest method testCreateNewAPIVersion.

@Test
public void testCreateNewAPIVersion() throws Exception {
    // Create Original API
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId);
    api.setContext("/test");
    api.setVisibility("Public");
    api.setStatus(APIConstants.CREATED);
    api.setWsdlUrl("https://localhost:9443/services/echo?wsdl");
    api.setOrganization("carbon.super");
    long time = System.currentTimeMillis();
    String newVersion = "1.0.1";
    // Create new API object
    APIIdentifier newApiId = new APIIdentifier("admin", "API1", "1.0.1");
    final API newApi = new API(newApiId);
    newApi.setStatus(APIConstants.CREATED);
    newApi.setContext("/test");
    newApi.setWsdlUrl("/registry/resource/_system/governance/apimgt/applicationdata/wsdls/admin--API11.0.0.wsdl");
    // Create Documentation List
    List<Documentation> documentationList = getDocumentationList();
    final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    GenericArtifact artifactNew = Mockito.mock(GenericArtifact.class);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, newApi)).thenReturn(artifactNew);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    Mockito.when(publisherAPI.getVersionTimestamp()).thenReturn(String.valueOf(time));
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    API returnedAPI = apiProvider.addAPI(api);
    Assert.assertTrue(StringUtils.isNotEmpty(returnedAPI.getVersionTimestamp()));
    String targetPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + newVersion + APIConstants.API_RESOURCE_NAME;
    String apiSourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + APIConstants.API_RESOURCE_NAME;
    PowerMockito.when(APIUtil.getAPIPath(apiId)).thenReturn(apiSourcePath);
    String apiSourceUUID = "87ty543-899hyt";
    Mockito.when(apiProvider.registry.resourceExists(targetPath)).thenReturn(false);
    Mockito.doNothing().when(apiProvider.registry).beginTransaction();
    Mockito.doNothing().when(apiProvider.registry).commitTransaction();
    Resource apiSourceArtifact = Mockito.mock(Resource.class);
    Mockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
    // Mocking Old API retrieval
    Mockito.when(apiSourceArtifact.getUUID()).thenReturn(apiSourceUUID);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT)).thenReturn("test");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE)).thenReturn("test/{version}");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_WEBSOCKET)).thenReturn("false");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES)).thenReturn("admin, subscriber");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceUUID)).thenReturn(artifact);
    // Mocking thumbnail
    String thumbUrl = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
    Resource image = Mockito.mock(Resource.class);
    Mockito.when(apiProvider.registry.get(thumbUrl)).thenReturn(image);
    Mockito.when(apiProvider.registry.resourceExists(thumbUrl)).thenReturn(true);
    // Mocking In sequence retrieval
    String inSeqFilePath = "API1/1.0.0/in";
    PowerMockito.when(APIUtil.getSequencePath(api.getId(), "in")).thenReturn(inSeqFilePath);
    Mockito.when(apiProvider.registry.resourceExists(inSeqFilePath)).thenReturn(true);
    Collection inSeqCollection = Mockito.mock(Collection.class);
    Mockito.when(apiProvider.registry.get(inSeqFilePath)).thenReturn(inSeqCollection);
    String[] inSeqChildPaths = { "path1" };
    Mockito.when(inSeqCollection.getChildren()).thenReturn(inSeqChildPaths);
    Mockito.when(apiProvider.registry.get(inSeqChildPaths[0])).thenReturn(apiSourceArtifact);
    InputStream responseStream = IOUtils.toInputStream("<sequence name=\"in-seq\"></sequence>", "UTF-8");
    OMElement seqElment = buildOMElement(responseStream);
    PowerMockito.when(APIUtil.buildOMElement(responseStream)).thenReturn(seqElment);
    Mockito.when(apiSourceArtifact.getContentStream()).thenReturn(responseStream);
    // Mocking Out sequence retrieval
    Resource apiSourceArtifact1 = Mockito.mock(Resource.class);
    String outSeqFilePath = "API1/1.0.0/out";
    PowerMockito.when(APIUtil.getSequencePath(api.getId(), "out")).thenReturn(outSeqFilePath);
    Mockito.when(apiProvider.registry.resourceExists(outSeqFilePath)).thenReturn(true);
    Collection outSeqCollection = Mockito.mock(Collection.class);
    Mockito.when(apiProvider.registry.get(outSeqFilePath)).thenReturn(outSeqCollection);
    String[] outSeqChildPaths = { "path2" };
    Mockito.when(outSeqCollection.getChildren()).thenReturn(outSeqChildPaths);
    Mockito.when(apiProvider.registry.get(outSeqChildPaths[0])).thenReturn(apiSourceArtifact1);
    InputStream responseStream2 = IOUtils.toInputStream("<sequence name=\"in-seq\"></sequence>", "UTF-8");
    OMElement seqElment2 = buildOMElement(responseStream2);
    PowerMockito.when(APIUtil.buildOMElement(responseStream2)).thenReturn(seqElment2);
    Mockito.when(apiSourceArtifact1.getContentStream()).thenReturn(responseStream2);
    // Mock Adding new API artifact with new version
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            apiProvider.createAPI(newApi);
            return null;
        }
    }).when(artifactManager).addGenericArtifact(artifact);
    Mockito.doNothing().when(artifact).attachLifecycle(APIConstants.API_LIFE_CYCLE);
    PowerMockito.when(APIUtil.getAPIProviderPath(api.getId())).thenReturn("/dummy/provider/path");
    Mockito.doNothing().when(apiProvider.registry).addAssociation("/dummy/provider/path", targetPath, APIConstants.PROVIDER_ASSOCIATION);
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, artifact.getId())).thenReturn(artifactPath);
    PowerMockito.doNothing().when(APIUtil.class);
    String[] roles = { "admin", "subscriber" };
    APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
    // Mock no tags case
    Mockito.when(apiProvider.registry.getTags(apiSourcePath)).thenReturn(null);
    // Mock WSDL retrieval
    String wsdlUrl = APIUtil.getWSDLDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
    PowerMockito.when(apiProvider.registry.resourceExists(wsdlUrl)).thenReturn(true);
    // Mock new API retrieval
    String newApiPath = "API1/1.0.1/";
    PowerMockito.when(APIUtil.getAPIPath(newApi.getId())).thenReturn(newApiPath);
    String newApiUUID = "87ty543-899hy23";
    GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
    Resource newApiResource = Mockito.mock(Resource.class);
    Mockito.when(newApiResource.getUUID()).thenReturn(newApiUUID);
    Mockito.when(apiProvider.registry.get(newApiPath)).thenReturn(newApiResource);
    Mockito.when(artifactManager.getGenericArtifact(newApiUUID)).thenReturn(newArtifact);
    PowerMockito.when(APIUtil.getAPI(newArtifact, apiProvider.registry, api.getId(), "test")).thenReturn(newApi);
    // Swagger resource
    String resourcePath = APIUtil.getOpenAPIDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
    Mockito.when(apiProvider.registry.resourceExists(resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME)).thenReturn(true);
    PowerMockito.mockStatic(OASParserUtil.class);
    Mockito.when(OASParserUtil.getAPIDefinition(apiId, apiProvider.registry)).thenReturn("{\"info\": {\"swagger\":\"data\"}}");
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
    // WSDL
    String newWsdlResourcePath = APIUtil.getWSDLDefinitionFilePath(newApi.getId().getApiName(), newApi.getId().getVersion(), newApi.getId().getProviderName());
    PowerMockito.when(apiProvider.registry.copy(resourcePath, newWsdlResourcePath)).thenReturn(newWsdlResourcePath);
    // Mock Config system registry
    PowerMockito.when(tenantManager.getTenantId(Matchers.anyString())).thenReturn(-1234);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    PowerMockito.when(realmService.getTenantUserRealm(-1234)).thenReturn(userRealm);
    PowerMockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) OMElement(org.apache.axiom.om.OMElement) UserRealm(org.wso2.carbon.user.api.UserRealm) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RealmService(org.wso2.carbon.user.core.service.RealmService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Collection(org.wso2.carbon.registry.core.Collection) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

AuthorizationManager (org.wso2.carbon.user.api.AuthorizationManager)11 RegistryAuthorizationManager (org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 Resource (org.wso2.carbon.registry.core.Resource)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 Test (org.junit.Test)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)4 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)4 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)3 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)3 UserRealm (org.wso2.carbon.user.api.UserRealm)3 File (java.io.File)2 FilenameFilter (java.io.FilenameFilter)2 IOException (java.io.IOException)2 APIResource (org.wso2.carbon.apimgt.api.doc.model.APIResource)2 API (org.wso2.carbon.apimgt.api.model.API)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2