Search in sources :

Example 1 with PentahoAccessControlException

use of org.pentaho.platform.api.engine.PentahoAccessControlException in project pentaho-platform by pentaho.

the class PentahoMetadataDomainRepository method getDomain.

/**
 * retrieve a domain from the repo. This does lazy loading of the repo, so it calls reloadDomains() if not already
 * loaded.
 *
 * @param domainId domain to get from the repository
 * @return domain object
 */
@Override
public Domain getDomain(final String domainId) {
    if (logger.isDebugEnabled()) {
        logger.debug("getDomain(" + domainId + ")");
    }
    if (StringUtils.isEmpty(domainId)) {
        throw new IllegalArgumentException(messages.getErrorString("PentahoMetadataDomainRepository.ERROR_0004_DOMAIN_ID_INVALID", domainId));
    }
    Domain domain = null;
    try {
        // Load the domain file
        final RepositoryFile file = getMetadataRepositoryFile(domainId);
        if (file != null) {
            if (hasAccessFor(file)) {
                SimpleRepositoryFileData data = repository.getDataForRead(file.getId(), SimpleRepositoryFileData.class);
                if (data != null) {
                    InputStream is = data.getStream();
                    try {
                        domain = xmiParser.parseXmi(is);
                    } finally {
                        IOUtils.closeQuietly(is);
                    }
                    domain.setId(domainId);
                    logger.debug("loaded domain");
                    // Load any I18N bundles
                    loadLocaleStrings(domainId, domain);
                    logger.debug("loaded I18N bundles");
                } else {
                    throw new UnifiedRepositoryException(messages.getErrorString("PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN", domainId, "data not found"));
                }
            } else {
                throw new PentahoAccessControlException(messages.getErrorString("PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN", domainId, "access denied"));
            }
        }
    } catch (Exception e) {
        if (!(e instanceof UnifiedRepositoryException || e instanceof PentahoAccessControlException)) {
            throw new UnifiedRepositoryException(messages.getErrorString("PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN", domainId, e.getLocalizedMessage()), e);
        }
    }
    // Return
    return domain;
}
Also used : SimpleRepositoryFileData(org.pentaho.platform.api.repository2.unified.data.simple.SimpleRepositoryFileData) ByteArrayInputStream(java.io.ByteArrayInputStream) RepositoryFileInputStream(org.pentaho.platform.repository2.unified.fileio.RepositoryFileInputStream) InputStream(java.io.InputStream) UnifiedRepositoryException(org.pentaho.platform.api.repository2.unified.UnifiedRepositoryException) RepositoryFile(org.pentaho.platform.api.repository2.unified.RepositoryFile) Domain(org.pentaho.metadata.model.Domain) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) DomainStorageException(org.pentaho.metadata.repository.DomainStorageException) UnifiedRepositoryException(org.pentaho.platform.api.repository2.unified.UnifiedRepositoryException) DomainIdNullException(org.pentaho.metadata.repository.DomainIdNullException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) DomainAlreadyExistsException(org.pentaho.metadata.repository.DomainAlreadyExistsException) IOException(java.io.IOException)

Example 2 with PentahoAccessControlException

use of org.pentaho.platform.api.engine.PentahoAccessControlException in project pentaho-platform by pentaho.

the class RepositoryImportResource method validateAccess.

protected void validateAccess(String importDir) throws PentahoAccessControlException {
    IAuthorizationPolicy policy = PentahoSystem.get(IAuthorizationPolicy.class);
    // check if we are admin or have publish permisson
    boolean isAdmin = policy.isAllowed(RepositoryReadAction.NAME) && policy.isAllowed(RepositoryCreateAction.NAME) && (policy.isAllowed(AdministerSecurityAction.NAME) || policy.isAllowed(PublishAction.NAME));
    if (!isAdmin) {
        // the user does not have admin or publish permisson, so we will check if the user imports to their home folder
        boolean importingToHomeFolder = false;
        String tenatedUserName = PentahoSessionHolder.getSession().getName();
        // get user home home folder path
        String userHomeFolderPath = ServerRepositoryPaths.getUserHomeFolderPath(JcrTenantUtils.getUserNameUtils().getTenant(tenatedUserName), JcrTenantUtils.getUserNameUtils().getPrincipleName(tenatedUserName));
        if (userHomeFolderPath != null && userHomeFolderPath.length() > 0) {
            // we pass the relative path so add serverside root folder for every home folder
            importingToHomeFolder = (ServerRepositoryPaths.getTenantRootFolderPath() + importDir).contains(userHomeFolderPath);
        }
        if (!(importingToHomeFolder && policy.isAllowed(RepositoryCreateAction.NAME) && policy.isAllowed(RepositoryReadAction.NAME))) {
            throw new PentahoAccessControlException("User is not authorized to perform this operation");
        }
    }
}
Also used : IAuthorizationPolicy(org.pentaho.platform.api.engine.IAuthorizationPolicy) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException)

Example 3 with PentahoAccessControlException

use of org.pentaho.platform.api.engine.PentahoAccessControlException in project pentaho-platform by pentaho.

the class RepositoryImportResource method doPostImport.

/**
 * Attempts to import all files from the zip archive or single file. A log file is produced at the end of import.
 *
 * <p><b>Example Request:</b><br />
 *    POST pentaho/api/repo/files/import
 *    <br /><b>POST data:</b>
 *    <pre function="syntax.xml">
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="importDir"
 *
 *      /public
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="fileUpload"; filename="test.csv"
 *      Content-Type: application/vnd.ms-excel
 *
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="overwriteFile"
 *
 *      true
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="overwriteAclPermissions"
 *
 *      true
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="applyAclPermissions"
 *
 *      true
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="retainOwnership"
 *
 *      true
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="charSet"
 *
 *      UTF-8
 *      ------WebKitFormBoundaryB9hzsGp4wR5SGAZD
 *      Content-Disposition: form-data; name="logLevel"
 *
 *      INFO
 *      ------WebKitFormBoundaryd1z6iZhXyx12RYxV
 *      Content-Disposition: form-data; name="fileNameOverride"
 *
 *      fileNameOverriden.csv
 *      ------WebKitFormBoundaryd1z6iZhXyx12RYxV--
 *    </pre>
 * </p>
 *
 * @param importDir               JCR Directory to which the zip structure or single file will be uploaded to.
 * @param fileUpload              Input stream for the file.
 * @param overwriteFile           The flag indicates ability to overwrite existing file.
 * @param overwriteAclPermissions The flag indicates ability to overwrite Acl permissions.
 * @param applyAclPermissions     The flag indicates ability to apply Acl permissions.
 * @param retainOwnership         The flag indicates ability to retain ownership.
 * @param charSet                 The charset for imported file.
 * @param logLevel                The level of logging.
 * @param fileNameOverride        If present and the content represents a single file, this parameter contains the filename to use
 *                                when storing the file in the repository. If not present, the fileInfo.getFileName will be used.
 *                                Note that the later cannot reliably handle foreign character sets.
 *
 * @return A jax-rs Response object with the appropriate header and body.
 *
 * <p><b>Example Response:</b></p>
 * <pre function="syntax.xml">
 *   &lt;html&gt;
 *   &lt;head&gt;
 *   &lt;title&gt;Repository Import Log&lt;/title&gt;
 *   &lt;/head&gt;
 *   &lt;body bgcolor="#FFFFFF" topmargin="6" leftmargin="6" style="font-family: arial,sans-serif; font-size: x-small"&gt;
 *   &lt;hr size="1" noshade&gt;
 *   Log session start time Thu Feb 26 11:04:19 BRT 2015&lt;br&gt;
 *   &lt;br&gt;
 *   &lt;table cellspacing="0" cellpadding="4" border="1" bordercolor="#224466" width="100%"&gt;
 *   &lt;tr style="background: #336699; color: #FFFFFF; text-align: left"&gt;
 *   &lt;th&gt;Import File&lt;/th&gt;
 *   &lt;th&gt;Level&lt;/th&gt;
 *   &lt;th&gt;Message&lt;/th&gt;
 *   &lt;/tr&gt;
 *   &lt;td title="importFile"&gt;/public&lt;/td&gt;
 *   &lt;td title="Level"&gt;INFO&lt;/td&gt;
 *   &lt;td title="Message"&gt;Start Import Job&lt;/td&gt;
 *   &lt;/tr&gt;
 *   &lt;td title="importFile"&gt;/public/fileNameOverriden.csv&lt;/td&gt;
 *   &lt;td title="Level"&gt;INFO&lt;/td&gt;
 *   &lt;td title="Message"&gt;Start File Import&lt;/td&gt;
 *   &lt;/tr&gt;
 *   &lt;td title="importFile"&gt;/public/fileNameOverriden.csv&lt;/td&gt;
 *   &lt;td title="Level"&gt;&lt;font color="#993300"&gt;&lt;strong&gt;WARN&lt;/strong&gt;&lt;/font&gt;&lt;/td&gt;
 *   &lt;td title="Message"&gt;fileNameOverriden.csv&lt;/td&gt;
 *   &lt;/tr&gt;
 *   &lt;td title="importFile"&gt;/public&lt;/td&gt;
 *   &lt;td title="Level"&gt;INFO&lt;/td&gt;
 *   &lt;td title="Message"&gt;End Import Job&lt;/td&gt;
 *   &lt;/tr&gt;
 *   &lt;/table&gt;
 *   &lt;br&gt;
 *   &lt;/body&gt;&lt;/html&gt;
 * </pre>
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
@Facet(name = "Unsupported")
public Response doPostImport(@FormDataParam("importDir") String importDir, @FormDataParam("fileUpload") InputStream fileUpload, @FormDataParam("overwriteFile") String overwriteFile, @FormDataParam("overwriteAclPermissions") String overwriteAclPermissions, @FormDataParam("applyAclPermissions") String applyAclPermission, @FormDataParam("retainOwnership") String retainOwnership, @FormDataParam("charSet") String charSet, @FormDataParam("logLevel") String logLevel, @FormDataParam("fileUpload") FormDataContentDisposition fileInfo, @FormDataParam("fileNameOverride") String fileNameOverride) {
    IRepositoryImportLogger importLogger = null;
    ByteArrayOutputStream importLoggerStream = new ByteArrayOutputStream();
    boolean logJobStarted = false;
    if (StringUtils.isBlank(charSet)) {
        charSet = DEFAULT_CHAR_SET;
    }
    try {
        validateAccess(importDir);
        boolean overwriteFileFlag = ("false".equals(overwriteFile) ? false : true);
        boolean overwriteAclSettingsFlag = ("true".equals(overwriteAclPermissions) ? true : false);
        boolean applyAclSettingsFlag = ("true".equals(applyAclPermission) ? true : false);
        boolean retainOwnershipFlag = ("true".equals(retainOwnership) ? true : false);
        // If logLevel is null then we will default to ERROR
        if (logLevel == null || logLevel.length() <= 0) {
            logLevel = "ERROR";
        }
        // Non-admins cannot process a manifest
        FileService fileService = new FileService();
        if (!fileService.doCanAdminister()) {
            applyAclSettingsFlag = false;
            retainOwnershipFlag = true;
        }
        Level level = Level.toLevel(logLevel);
        ImportSession.getSession().setAclProperties(applyAclSettingsFlag, retainOwnershipFlag, overwriteAclSettingsFlag);
        // The fileNameOverride was added because the formDataContentDispositionfile object cannot reliable
        // contain non US-ASCII characters.  See RFC283 section 2.3 for details
        String fileName = fileNameOverride != null ? fileNameOverride : fileInfo.getFileName();
        RepositoryFileImportBundle.Builder bundleBuilder = new RepositoryFileImportBundle.Builder();
        bundleBuilder.input(fileUpload);
        bundleBuilder.charSet(charSet);
        bundleBuilder.path(importDir);
        bundleBuilder.overwriteFile(overwriteFileFlag);
        bundleBuilder.applyAclSettings(applyAclSettingsFlag);
        bundleBuilder.overwriteAclSettings(overwriteAclSettingsFlag);
        bundleBuilder.retainOwnership(retainOwnershipFlag);
        bundleBuilder.name(fileName);
        IPlatformImportBundle bundle = bundleBuilder.build();
        IPlatformMimeResolver mimeResolver = PentahoSystem.get(IPlatformMimeResolver.class);
        String mimeTypeFromFile = mimeResolver.resolveMimeForFileName(fileName);
        if (mimeTypeFromFile == null) {
            return Response.ok("INVALID_MIME_TYPE", MediaType.TEXT_HTML).build();
        }
        bundleBuilder.mime(mimeTypeFromFile);
        IPlatformImporter importer = PentahoSystem.get(IPlatformImporter.class);
        importLogger = importer.getRepositoryImportLogger();
        final String mimeType = bundle.getMimeType() != null ? bundle.getMimeType() : mimeResolver.resolveMimeForBundle(bundle);
        if (mimeType == null) {
            return Response.ok("INVALID_MIME_TYPE", MediaType.TEXT_HTML).build();
        }
        logJobStarted = true;
        importLogger.startJob(importLoggerStream, importDir, level);
        importer.importFile(bundle);
        // Flush the Mondrian cache to show imported data-sources.
        IMondrianCatalogService mondrianCatalogService = PentahoSystem.get(IMondrianCatalogService.class, "IMondrianCatalogService", PentahoSessionHolder.getSession());
        mondrianCatalogService.reInit(PentahoSessionHolder.getSession());
    } catch (PentahoAccessControlException e) {
        return Response.serverError().entity(e.toString()).build();
    } catch (Exception e) {
        return Response.serverError().entity(e.toString()).build();
    } finally {
        ImportSession.clearSession();
        if (logJobStarted == true) {
            importLogger.endJob();
        }
    }
    String responseBody;
    try {
        responseBody = importLoggerStream.toString(charSet);
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Encoding of response body is failed. (charSet=" + charSet + ")", e);
        responseBody = importLoggerStream.toString();
    }
    return Response.ok(responseBody, MediaType.TEXT_HTML).build();
}
Also used : FileService(org.pentaho.platform.web.http.api.resources.services.FileService) IRepositoryImportLogger(org.pentaho.platform.plugin.services.importexport.IRepositoryImportLogger) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IMondrianCatalogService(org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IPlatformImportBundle(org.pentaho.platform.api.repository2.unified.IPlatformImportBundle) IPlatformMimeResolver(org.pentaho.platform.api.mimetype.IPlatformMimeResolver) Level(org.apache.log4j.Level) RepositoryFileImportBundle(org.pentaho.platform.plugin.services.importer.RepositoryFileImportBundle) IPlatformImporter(org.pentaho.platform.plugin.services.importer.IPlatformImporter) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Facet(org.codehaus.enunciate.Facet)

Example 4 with PentahoAccessControlException

use of org.pentaho.platform.api.engine.PentahoAccessControlException in project pentaho-platform by pentaho.

the class RepositoryPublishServiceTest method testWriteFileException.

@Test
public void testWriteFileException() throws Exception {
    String pathId = "path:to:file";
    InputStream stubInputStream = IOUtils.toInputStream("some test data for my input stream");
    Boolean overwriteFile = true;
    doReturn(mockRepositoryFileImportBundle).when(repositoryPublishService).buildBundle(pathId, stubInputStream, overwriteFile);
    /*
     * Test 1
     */
    doReturn(false).when(repositoryPublishService.policy).isAllowed(anyString());
    doReturn(repositoryPublishService.policy).when(repositoryPublishService).getPolicy();
    try {
        repositoryPublishService.writeFile(pathId, stubInputStream, overwriteFile);
        fail();
    } catch (PentahoAccessControlException e) {
    // Expected
    } catch (Throwable t) {
        fail();
    }
    /*
     * Test 2
     */
    doReturn(true).when(repositoryPublishService.policy).isAllowed(anyString());
    doThrow(new PlatformImportException("")).when(repositoryPublishService.platformImporter).importFile(mockRepositoryFileImportBundle);
    try {
        repositoryPublishService.writeFile(pathId, stubInputStream, overwriteFile);
        fail();
    } catch (PlatformImportException e) {
    // Expected
    } catch (Exception e) {
        fail();
    }
    /*
     * Test 3
     */
    doReturn(true).when(repositoryPublishService.policy).isAllowed(anyString());
    doThrow(new InternalError()).when(repositoryPublishService.platformImporter).importFile(mockRepositoryFileImportBundle);
    try {
        repositoryPublishService.writeFile(pathId, stubInputStream, overwriteFile);
        fail();
    } catch (PlatformImportException e) {
        fail();
    } catch (InternalError e) {
    // Expected
    }
}
Also used : PlatformImportException(org.pentaho.platform.plugin.services.importer.PlatformImportException) InputStream(java.io.InputStream) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) PlatformImportException(org.pentaho.platform.plugin.services.importer.PlatformImportException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) Test(org.junit.Test)

Example 5 with PentahoAccessControlException

use of org.pentaho.platform.api.engine.PentahoAccessControlException in project pentaho-platform by pentaho.

the class OlapServiceImpl method getConnection.

public OlapConnection getConnection(String catalogName, IPentahoSession session) throws IOlapServiceException {
    if (catalogName == null) {
        // This is normal. It happens on XMLA's DISCOVER_DATASOURCES
        try {
            return getServer().getConnection(DATASOURCE_NAME, null, null, new Properties());
        } catch (Exception e) {
            throw new IOlapServiceException(e);
        }
    }
    // Check Access
    if (!hasAccess(catalogName, EnumSet.of(RepositoryFilePermission.READ), session)) {
        // $NON-NLS-1$
        LOG.debug("user does not have access; throwing exception");
        throw new IOlapServiceException(Messages.getInstance().getErrorString(// $NON-NLS-1$
        "OlapServiceImpl.ERROR_0003_INSUFFICIENT_PERMISSION"), IOlapServiceException.Reason.ACCESS_DENIED);
    }
    // Check its existence.
    if (!getCatalogNames(session).contains(catalogName)) {
        throw new IOlapServiceException(Messages.getInstance().getErrorString("MondrianCatalogHelper.ERROR_0015_CATALOG_NOT_FOUND", catalogName));
    }
    // Check if it is a remote server
    if (getHelper().getOlap4jServers().contains(catalogName)) {
        return makeOlap4jConnection(catalogName);
    }
    final StringBuilder roleName = new StringBuilder();
    Entry roleMonikor = null;
    if (this.role != null) {
        // We must use a custom role implementation.
        // Register the instance with the mondrian server.
        roleMonikor = getServer().getLockBox().register(this.role);
        roleName.append(roleMonikor.getMoniker());
    } else {
        final IConnectionUserRoleMapper mapper = PentahoSystem.get(IConnectionUserRoleMapper.class, MDXConnection.MDX_CONNECTION_MAPPER_KEY, // Don't use the user session here yet.
        null);
        String[] effectiveRoles = new String[0];
        /*
       * If Catalog/Schema are null (this happens with high level metadata requests,
       * like DISCOVER_DATASOURCES) we can't use the role mapper, even if it
       * is present and configured.
       */
        if (session != null && mapper != null) {
            // Use the role mapper.
            try {
                effectiveRoles = mapper.mapConnectionRoles(session, catalogName);
                if (effectiveRoles == null) {
                    effectiveRoles = new String[0];
                }
            } catch (PentahoAccessControlException e) {
                throw new IOlapServiceException(e);
            }
        }
        // Now we tokenize that list.
        boolean addComma = false;
        for (String role : effectiveRoles) {
            if (addComma) {
                // $NON-NLS-1$
                roleName.append(",");
            }
            roleName.append(role);
            addComma = true;
        }
    }
    // Populate some properties, like locale.
    final Properties properties = new Properties();
    properties.put(RolapConnectionProperties.Locale.name(), getLocale().toString());
    // Return a connection
    try {
        return getServer().getConnection(DATASOURCE_NAME, catalogName, Util.isEmpty(roleName.toString()) ? null : roleName.toString(), properties);
    } catch (Exception e) {
        throw new IOlapServiceException(e);
    } finally {
        // Cleanup our lockbox entry.
        if (roleMonikor != null) {
            getServer().getLockBox().deregister(roleMonikor);
        }
    }
}
Also used : Entry(mondrian.util.LockBox.Entry) IConnectionUserRoleMapper(org.pentaho.platform.api.engine.IConnectionUserRoleMapper) IOlapServiceException(org.pentaho.platform.plugin.action.olap.IOlapServiceException) RolapConnectionProperties(mondrian.rolap.RolapConnectionProperties) Properties(java.util.Properties) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) FileSystemException(org.apache.commons.vfs2.FileSystemException) OlapException(org.olap4j.OlapException) SQLException(java.sql.SQLException) IOlapServiceException(org.pentaho.platform.plugin.action.olap.IOlapServiceException)

Aggregations

PentahoAccessControlException (org.pentaho.platform.api.engine.PentahoAccessControlException)48 Test (org.junit.Test)28 InputStream (java.io.InputStream)13 Response (javax.ws.rs.core.Response)13 FileNotFoundException (java.io.FileNotFoundException)10 WebApplicationException (javax.ws.rs.WebApplicationException)10 IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)6 ConnectionServiceException (org.pentaho.platform.dataaccess.datasource.wizard.service.ConnectionServiceException)6 PlatformInitializationException (org.pentaho.platform.engine.core.system.boot.PlatformInitializationException)6 PlatformImportException (org.pentaho.platform.plugin.services.importer.PlatformImportException)6 DataAccessException (org.springframework.dao.DataAccessException)6 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)6 Domain (org.pentaho.metadata.model.Domain)5 IAuthorizationPolicy (org.pentaho.platform.api.engine.IAuthorizationPolicy)5 FileInputStream (java.io.FileInputStream)4 Consumes (javax.ws.rs.Consumes)4 Facet (org.codehaus.enunciate.Facet)4 Matchers.anyString (org.mockito.Matchers.anyString)4 ModelerWorkspace (org.pentaho.agilebi.modeler.ModelerWorkspace)4 FormDataContentDisposition (com.sun.jersey.core.header.FormDataContentDisposition)3