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;
}
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");
}
}
}
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">
* <html>
* <head>
* <title>Repository Import Log</title>
* </head>
* <body bgcolor="#FFFFFF" topmargin="6" leftmargin="6" style="font-family: arial,sans-serif; font-size: x-small">
* <hr size="1" noshade>
* Log session start time Thu Feb 26 11:04:19 BRT 2015<br>
* <br>
* <table cellspacing="0" cellpadding="4" border="1" bordercolor="#224466" width="100%">
* <tr style="background: #336699; color: #FFFFFF; text-align: left">
* <th>Import File</th>
* <th>Level</th>
* <th>Message</th>
* </tr>
* <td title="importFile">/public</td>
* <td title="Level">INFO</td>
* <td title="Message">Start Import Job</td>
* </tr>
* <td title="importFile">/public/fileNameOverriden.csv</td>
* <td title="Level">INFO</td>
* <td title="Message">Start File Import</td>
* </tr>
* <td title="importFile">/public/fileNameOverriden.csv</td>
* <td title="Level"><font color="#993300"><strong>WARN</strong></font></td>
* <td title="Message">fileNameOverriden.csv</td>
* </tr>
* <td title="importFile">/public</td>
* <td title="Level">INFO</td>
* <td title="Message">End Import Job</td>
* </tr>
* </table>
* <br>
* </body></html>
* </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();
}
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
}
}
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);
}
}
}
Aggregations