use of org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException in project alfresco-remote-api by Alfresco.
the class TestCMIS method testDeleteNonCurrentVersion.
/**
* Test delete version on versions other than latest (most recent) version (MNT-17228)
*/
@Test
public void testDeleteNonCurrentVersion() throws Exception {
final TestNetwork network1 = getTestFixture().getRandomNetwork();
String username = "user" + System.currentTimeMillis();
PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
TestPerson person = network1.createUser(personInfo);
String personId = person.getId();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), personId));
CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.browser, CMIS_VERSION_11, AlfrescoObjectFactoryImpl.class.getName());
Folder homeFolder = (Folder) cmisSession.getObjectByPath("/User Homes/" + personId);
assertNotNull(homeFolder.getId());
// Create a document
String name = String.format(TEST_DOCUMENT_NAME_PATTERN, GUID.generate());
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
properties.put(PropertyIds.NAME, name);
ContentStreamImpl fileContent = new ContentStreamImpl();
ByteArrayInputStream stream = new ByteArrayInputStream(GUID.generate().getBytes());
fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
fileContent.setStream(stream);
Document doc = homeFolder.createDocument(properties, fileContent, VersioningState.MAJOR);
String versionLabel = doc.getVersionLabel();
assertEquals("1.0", versionLabel);
Document docVersionToDelete = null;
Document latestDoc = doc;
int cnt = 4;
for (int i = 1; i <= cnt; i++) {
// Update content to create new versions (1.1, 1.2, 1.3, 1.4)
fileContent = new ContentStreamImpl();
{
ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
writer.putContent("Ipsum and so on and so on " + i);
ContentReader reader = writer.getReader();
fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
fileContent.setStream(reader.getContentInputStream());
}
latestDoc.setContentStream(fileContent, true);
latestDoc = latestDoc.getObjectOfLatestVersion(false);
versionLabel = latestDoc.getVersionLabel();
assertEquals("1." + i, versionLabel);
assertEquals(1 + i, cmisSession.getAllVersions(latestDoc.getId()).size());
if (i == 2) {
// ie. 1.2
docVersionToDelete = latestDoc;
}
}
// Test delete with a user without permissions
String username2 = "user" + System.currentTimeMillis();
PersonInfo person2Info = new PersonInfo(username2, username2, username2, TEST_PASSWORD, null, null, null, null, null, null, null);
TestPerson person2 = network1.createUser(person2Info);
String person2Id = person2.getId();
TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
@Override
public Void doWork() throws Exception {
String nodeId = stripCMISSuffix(doc.getId());
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId);
// Give user person2 READ permissions to access the node
permissionService.setPermission(nodeRef, person2Id, PermissionService.READ, true);
return null;
}
}, network1.getId());
// Connect with person2
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2Id));
CmisSession cmisSession2 = publicApiClient.createPublicApiCMISSession(Binding.browser, CMIS_VERSION_11, AlfrescoObjectFactoryImpl.class.getName());
CmisObject docVersionToDeleteBy2 = cmisSession2.getObject(docVersionToDelete.getId());
try {
// (-) Delete v 1.2 (without DELETE permission)
docVersionToDeleteBy2.delete(false);
fail("Node version was deleted without permissions.");
} catch (CmisPermissionDeniedException ex) {
// expected
}
// (+) Delete v 1.2 (with permission)
docVersionToDelete.delete(false);
// eg. 1.0, 1.2, 1.3, 1.4 (not 1.1)
assertEquals(cnt, cmisSession.getAllVersions(doc.getId()).size());
}
use of org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException in project copper-cms by PogeyanOSS.
the class AkkaCmisBrowserBindingServlet method service.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final ActorSystem system = (ActorSystem) request.getServletContext().getAttribute("ActorSystem");
// CSRF token check
String method = request.getMethod();
if (!METHOD_GET.equals(method) && !METHOD_HEAD.equals(method)) {
checkCsrfToken(request, response, false, false);
}
// set default headers
response.addHeader("Cache-Control", "private, max-age=0");
response.addHeader("Server", ServerVersion.OPENCMIS_SERVER);
// split path
String[] pathFragments = HttpUtils.splitPath(request);
final AsyncContext ctx = request.startAsync(request, response);
if (Helpers.isPerfMode()) {
MetricsInputs.get().getCounter("counter_requests_total").inc();
}
if (pathFragments != null && pathFragments.length > 0 && StringUtils.isBlank(pathFragments[0])) {
BaseMessage bm = gettingBaseMessage(method, pathFragments, null, request, response);
if (bm != null) {
// create actor on-the-fly
ActorRef servletActor = system.actorOf(Props.create(ServletActor.class, ctx));
servletActor.tell(bm, ActorRef.noSender());
} else {
throw new CmisNotSupportedException("Unsupported method");
}
} else {
this.verifyLogin(request, pathFragments, system, (s) -> {
try {
IUserObject loginSession = (IUserObject) s;
BaseMessage bm = gettingBaseMessage(method, pathFragments, loginSession, request, response);
if (bm != null) {
// create actor on-the-fly
ActorRef servletActor = system.actorOf(Props.create(ServletActor.class, ctx));
servletActor.tell(bm, ActorRef.noSender());
} else {
throw new CmisNotSupportedException("Unsupported method");
}
} catch (Exception e1) {
MetricsInputs.markBindingServletErrorMeter();
LOG.error("Service execution exception: {}, stack: {}", e1.getMessage(), ExceptionUtils.getStackTrace(e1));
ServletHelpers.printError(e1, request, response);
}
}, (err) -> {
HttpServletResponse asyncResponse = (HttpServletResponse) ctx.getResponse();
asyncResponse.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\", charset=\"UTF-8\"");
try {
asyncResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
} catch (Exception e1) {
MetricsInputs.markBindingServletErrorMeter();
ServletHelpers.printError(e1, (HttpServletRequest) ctx.getRequest(), asyncResponse);
}
ctx.complete();
});
}
} catch (Exception e) {
MetricsInputs.markBindingServletErrorMeter();
if (e instanceof CmisUnauthorizedException) {
response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\", charset=\"UTF-8\"");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
} else if (e instanceof CmisPermissionDeniedException) {
response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\", charset=\"UTF-8\"");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
} else {
ServletHelpers.printError(e, request, response);
}
} finally {
// in any case close the content stream if one has been provided
// if (request instanceof POSTHttpServletRequestWrapper) {
// InputStream stream = ((POSTHttpServletRequestWrapper)
// request).getStream();
// if (stream != null) {
// try {
// stream.close();
// } catch (IOException e) {
// LOG.error("Could not close POST stream: {}", e.toString(), e);
// }
// }
// }
// // we are done.
// try {
// response.flushBuffer();
// } catch (IOException ioe) {
// LOG.error("Could not flush resposne: {}", ioe.toString(), ioe);
// }
}
}
use of org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException in project copper-cms by PogeyanOSS.
the class CsrfManager method check.
public void check(HttpServletRequest req, HttpServletResponse resp, boolean isRepositoryInfoRequest, boolean isContentRequest) {
if (csrfHeader == null) {
// no CSRF protection
return;
}
HttpSession httpSession = req.getSession(true);
String token = (String) httpSession.getAttribute(CSRF_ATTR);
String headerValue = req.getHeader(csrfHeader);
// request
if (headerValue == null || headerValue.isEmpty()) {
if (isContentRequest && csrfParameter != null) {
String paramValue = req.getParameter(csrfParameter);
if (paramValue != null && paramValue.equals(token)) {
return;
}
}
throw new CmisPermissionDeniedException("Invalid CSRF token!");
}
// check if a new token is requested
if (isRepositoryInfoRequest && FETCH_VALUE.equals(headerValue) && token == null) {
token = generateNewToken();
httpSession.setAttribute(CSRF_ATTR, token);
resp.addHeader(csrfHeader, token);
return;
}
// check if there is a token
if (token == null) {
throw new CmisPermissionDeniedException("Invalid CSRF token!");
}
// finally, check the token
if (!token.equals(headerValue)) {
throw new CmisPermissionDeniedException("Invalid CSRF token!");
}
}
use of org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException in project structr by structr.
the class CMISObjectService method deleteObject.
@Override
public void deleteObject(String repositoryId, String objectId, Boolean allVersions, ExtensionsData extension) {
final App app = StructrApp.getInstance(securityContext);
try (final Tx tx = app.tx()) {
final Principal principal = securityContext.getUser(false);
final AbstractNode obj = app.get(AbstractNode.class, objectId);
if (obj != null) {
if (principal.isGranted(Permission.delete, securityContext)) {
if (obj.isNode()) {
// getSyncNode() returns the node or null
app.delete(obj.getSyncNode());
} else {
// getSyncRelationship() return the relationship or null
app.delete(obj.getSyncRelationship());
}
} else {
throw new CmisPermissionDeniedException("Cannot delete object with ID " + objectId);
}
} else {
throw new CmisObjectNotFoundException("Object with ID " + objectId + " does not exist");
}
tx.success();
} catch (FrameworkException fex) {
throw new CmisConstraintException(fex.getMessage(), fex);
}
}
use of org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException in project copper-cms by PogeyanOSS.
the class LDAPAuthService method authenticateInternal.
/**
* fetch repository MRepository based on RepositoryId from CallContext and
* Takes user and password from the CallContext and checks them.
*/
private LDAPLogin authenticateInternal(String repositoryId, String userName, String password) throws CmisPermissionDeniedException {
LoginProperties loginProperties = new LoginProperties();
if (StringUtils.isNotBlank(this.storeSettings.getCompanyName())) {
loginProperties.setCompanyName(this.storeSettings.getCompanyName());
}
loginProperties.setAdminUser(this.storeSettings.getAdminUser());
loginProperties.setPort(this.storeSettings.getPort());
loginProperties.setServerName(this.storeSettings.getServerName());
loginProperties.setUserName(userName);
loginProperties.setPassword(password);
loginProperties.setMasterCompany(this.storeSettings.getMastercompany());
loginProperties.setUserIdAttribute(this.storeSettings.getUserIdAttribute());
LDAPLogin login;
try {
login = LDAPUtils.login(loginProperties);
if (login != null) {
LOG.info("LDAP login successfull {}", userName);
return login;
}
} catch (Exception e) {
LOG.error("writeContent exception: {}, {}", e.getMessage(), ExceptionUtils.getStackTrace(e));
}
throw new CmisPermissionDeniedException("Login authentication failed for user: " + userName);
}
Aggregations