Search in sources :

Example 21 with Tenant

use of org.wso2.carbon.user.core.tenant.Tenant in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method changeAPILifeCycle.

@Override
public void changeAPILifeCycle(Organization org, String apiId, String status) throws APIPersistenceException {
    GenericArtifactManager artifactManager = null;
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        if (GovernanceUtils.findGovernanceArtifactConfiguration(APIConstants.API_KEY, registry) != null) {
            artifactManager = new GenericArtifactManager(registry, APIConstants.API_KEY);
            GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
            String action = LCManagerFactory.getInstance().getLCManager().getTransitionAction(apiArtifact.getLifecycleState().toUpperCase(), status.toUpperCase());
            apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
        } else {
            log.warn("Couldn't find GovernanceArtifactConfiguration of RXT: " + APIConstants.API_KEY + ". Tenant id set in registry : " + ((UserRegistry) registry).getTenantId() + ", Tenant domain set in PrivilegedCarbonContext: " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        }
    } catch (GovernanceException e) {
        throw new APIPersistenceException("Error while changing the lifecycle. ", e);
    } catch (RegistryException e) {
        throw new APIPersistenceException("Error while accessing the registry. ", e);
    } catch (PersistenceException e) {
        throw new APIPersistenceException("Error while accessing the lifecycle. ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 22 with Tenant

use of org.wso2.carbon.user.core.tenant.Tenant in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchPaginatedPublisherAPIsByDoc.

private PublisherAPISearchResult searchPaginatedPublisherAPIsByDoc(Registry registry, int tenantID, String searchQuery, String username, int start, int offset) throws APIPersistenceException {
    PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
    try {
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        if (docArtifactManager == null) {
            String errorMessage = "Doc artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        SolrClient client = SolrClient.getInstance();
        Map<String, String> fields = new HashMap<String, String>();
        fields.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, "*" + APIConstants.API_ROOT_LOCATION + "*");
        fields.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, "*");
        if (tenantID == -1) {
            tenantID = MultitenantConstants.SUPER_TENANT_ID;
        }
        // PaginationContext.init(0, 10000, "ASC", APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, Integer.MAX_VALUE);
        SolrDocumentList documentList = client.query(searchQuery, tenantID, fields);
        org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
        username = MultitenantUtils.getTenantAwareUsername(username);
        List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
        for (SolrDocument document : documentList) {
            PublisherAPIInfo apiInfo = new PublisherAPIInfo();
            String filePath = (String) document.getFieldValue("path_s");
            String fileName = (String) document.getFieldValue("resourceName_s");
            int index = filePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
            filePath = filePath.substring(index);
            boolean isAuthorized;
            int indexOfContents = filePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
            String documentationPath = filePath.substring(0, indexOfContents) + fileName;
            String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + documentationPath);
            if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
                isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
            } else {
                isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
            }
            if (isAuthorized) {
                int indexOfDocumentation = filePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                String apiPath = documentationPath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
                if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
                    isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
                } else {
                    isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
                }
                if (isAuthorized) {
                    Resource resource = registry.get(apiPath);
                    String apiArtifactId = resource.getUUID();
                    if (apiArtifactId != null) {
                        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
                        String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
                        if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status)) {
                            apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
                            apiInfo.setId(artifact.getId());
                            apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
                            apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
                            apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
                            apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
                            apiInfo.setStatus(status);
                            apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
                            apiInfo.setCreatedTime(String.valueOf(resource.getCreatedTime().getTime()));
                            apiInfo.setUpdatedTime(resource.getLastModified());
                            apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
                            // apiInfo.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
                            apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
                            apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
                            publisherAPIInfoList.add(apiInfo);
                        }
                    } else {
                        throw new GovernanceException("artifact id is null of " + apiPath);
                    }
                }
            }
        }
        // Sort the publisherAPIInfoList according to the API name.
        Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
        searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
        searchResults.setTotalAPIsCount(publisherAPIInfoList.size());
        searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
    } catch (RegistryException | UserStoreException | APIPersistenceException | IndexerException e) {
        String msg = "Failed to search APIs with type";
        throw new APIPersistenceException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    return searchResults;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SolrDocument(org.apache.solr.common.SolrDocument) SolrClient(org.wso2.carbon.registry.indexing.solr.SolrClient) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) SolrDocumentList(org.apache.solr.common.SolrDocumentList) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) PublisherAPISearchResultComparator(org.wso2.carbon.apimgt.persistence.utils.PublisherAPISearchResultComparator)

Example 23 with Tenant

use of org.wso2.carbon.user.core.tenant.Tenant in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method loadTenantConfigBlockingMode.

public static void loadTenantConfigBlockingMode(String tenantDomain) {
    try {
        ConfigurationContext ctx = ServiceReferenceHolder.getContextService().getServerConfigContext();
        TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, ctx);
    } catch (Exception e) {
        log.error("Error while creating axis configuration for tenant " + tenantDomain, e);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ParseException(org.json.simple.parser.ParseException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) IOException(java.io.IOException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 24 with Tenant

use of org.wso2.carbon.user.core.tenant.Tenant in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method loadloadTenantAPIRXT.

public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // 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 (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File)

Example 25 with Tenant

use of org.wso2.carbon.user.core.tenant.Tenant in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testCheckForInValidTokenInTenant.

// Test case for Invalid,expired,revoked tokens when first time invocation
// Expectation : invalid token need to put into invalid token cache in tenant and super tenant
@Test
public void testCheckForInValidTokenInTenant() throws APISecurityException {
    try {
        String tenantDomain = "abc.com";
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("abc.com");
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername("admin");
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
        apiKeyValidationInfoDTO.setAuthorized(false);
        apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
        AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
        Cache tokenCache = Mockito.mock(Cache.class);
        Cache keyCache = Mockito.mock(Cache.class);
        Cache resourceCache = Mockito.mock(Cache.class);
        Cache invalidTokenCache = Mockito.mock(Cache.class);
        APIKeyDataStore apiKeyDataStore = Mockito.mock(APIKeyDataStore.class);
        APIKeyValidator apiKeyValidator = getAPIKeyValidator(axisConfiguration, invalidTokenCache, tokenCache, keyCache, resourceCache, apiKeyDataStore, "abc.com");
        Mockito.when(tokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(invalidTokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(apiKeyDataStore.getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>())).thenReturn(apiKeyValidationInfoDTO);
        apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>());
        Mockito.verify(tokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).get(Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).put(Mockito.any(APIKeyValidationInfoDTO.class), Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(2)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(apiKeyDataStore, Mockito.times(1)).getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>());
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) WSAPIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.WSAPIKeyDataStore) APIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

UserStoreException (org.wso2.carbon.user.api.UserStoreException)194 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)180 ArrayList (java.util.ArrayList)177 SQLException (java.sql.SQLException)170 PreparedStatement (java.sql.PreparedStatement)156 Connection (java.sql.Connection)155 HashMap (java.util.HashMap)128 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)110 ResultSet (java.sql.ResultSet)107 IOException (java.io.IOException)98 Map (java.util.Map)78 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)77 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)71 RealmService (org.wso2.carbon.user.core.service.RealmService)64 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)55 Test (org.testng.annotations.Test)54 List (java.util.List)50 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)48 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)48 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)48