Search in sources :

Example 1 with CmisPermissionDeniedException

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());
}
Also used : ContentStreamImpl(org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl) HashMap(java.util.HashMap) AlfrescoFolder(org.alfresco.cmis.client.AlfrescoFolder) Folder(org.apache.chemistry.opencmis.client.api.Folder) AlfrescoDocument(org.alfresco.cmis.client.AlfrescoDocument) Document(org.apache.chemistry.opencmis.client.api.Document) NodeRef(org.alfresco.service.cmr.repository.NodeRef) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) FileableCmisObject(org.apache.chemistry.opencmis.client.api.FileableCmisObject) CmisObject(org.apache.chemistry.opencmis.client.api.CmisObject) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) AlfrescoObjectFactoryImpl(org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl) CmisSession(org.alfresco.rest.api.tests.client.PublicApiClient.CmisSession) FileContentWriter(org.alfresco.repo.content.filestore.FileContentWriter) ContentReader(org.alfresco.service.cmr.repository.ContentReader) CmisUpdateConflictException(org.apache.chemistry.opencmis.commons.exceptions.CmisUpdateConflictException) CmisConstraintException(org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) CmisInvalidArgumentException(org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) FileContentWriter(org.alfresco.repo.content.filestore.FileContentWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) TestNetwork(org.alfresco.rest.api.tests.RepoService.TestNetwork) FileableCmisObject(org.apache.chemistry.opencmis.client.api.FileableCmisObject) CmisObject(org.apache.chemistry.opencmis.client.api.CmisObject) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) VersionableAspectTest(org.alfresco.repo.version.VersionableAspectTest) Test(org.junit.Test)

Example 2 with CmisPermissionDeniedException

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);
    // }
    }
}
Also used : ActorSystem(akka.actor.ActorSystem) CmisNotSupportedException(org.apache.chemistry.opencmis.commons.exceptions.CmisNotSupportedException) ActorRef(akka.actor.ActorRef) IUserObject(com.pogeyan.cmis.api.auth.IUserObject) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) ServletException(javax.servlet.ServletException) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) CmisUnauthorizedException(org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException) CmisNotSupportedException(org.apache.chemistry.opencmis.commons.exceptions.CmisNotSupportedException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseMessage(com.pogeyan.cmis.api.BaseMessage) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) CmisUnauthorizedException(org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException)

Example 3 with CmisPermissionDeniedException

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!");
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException)

Example 4 with CmisPermissionDeniedException

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);
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) CmisConstraintException(org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) Principal(org.structr.core.entity.Principal)

Example 5 with CmisPermissionDeniedException

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);
}
Also used : CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) LoginProperties(com.pogeyan.cmis.ldap.model.LoginProperties) LDAPLogin(com.pogeyan.cmis.ldap.model.LDAPLogin) InvalidTargetObjectTypeException(javax.management.modelmbean.InvalidTargetObjectTypeException) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) InvalidObjectException(java.io.InvalidObjectException)

Aggregations

CmisPermissionDeniedException (org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException)5 CmisConstraintException (org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException)2 CmisObjectNotFoundException (org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException)2 ActorRef (akka.actor.ActorRef)1 ActorSystem (akka.actor.ActorSystem)1 BaseMessage (com.pogeyan.cmis.api.BaseMessage)1 IUserObject (com.pogeyan.cmis.api.auth.IUserObject)1 LDAPLogin (com.pogeyan.cmis.ldap.model.LDAPLogin)1 LoginProperties (com.pogeyan.cmis.ldap.model.LoginProperties)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 InvalidObjectException (java.io.InvalidObjectException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashMap (java.util.HashMap)1 InvalidTargetObjectTypeException (javax.management.modelmbean.InvalidTargetObjectTypeException)1 AsyncContext (javax.servlet.AsyncContext)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1