diff --git a/rm-automation/rm-automation-community-rest-api/src/test/java/org/alfresco/rest/rm/community/search/CmisQueryTests.java b/rm-automation/rm-automation-community-rest-api/src/test/java/org/alfresco/rest/rm/community/search/CmisQueryTests.java new file mode 100644 index 0000000000..8624e2d00f --- /dev/null +++ b/rm-automation/rm-automation-community-rest-api/src/test/java/org/alfresco/rest/rm/community/search/CmisQueryTests.java @@ -0,0 +1,233 @@ +/* + * #%L + * Alfresco Records Management Module + * %% + * Copyright (C) 2005 - 2020 Alfresco Software Limited + * %% + * This file is part of the Alfresco software. + * - + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * - + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * - + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * - + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see . + * #L% + */ + +package org.alfresco.rest.rm.community.search; + +import static org.alfresco.rest.rm.community.model.user.UserRoles.ROLE_RM_MANAGER; +import static org.alfresco.rest.rm.community.util.CommonTestUtils.generateTestPrefix; +import static org.alfresco.utility.report.log.Step.STEP; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +import org.alfresco.dataprep.ContentActions; +import org.alfresco.rest.rm.community.base.BaseRMRestTest; +import org.alfresco.rest.rm.community.model.recordcategory.RecordCategoryChild; +import org.alfresco.rest.rm.community.model.user.UserPermissions; +import org.alfresco.test.AlfrescoTest; +import org.alfresco.utility.constants.UserRole; +import org.alfresco.utility.model.FileModel; +import org.alfresco.utility.model.FileType; +import org.alfresco.utility.model.SiteModel; +import org.alfresco.utility.model.UserModel; +import org.apache.chemistry.opencmis.client.api.ItemIterable; +import org.apache.chemistry.opencmis.client.api.OperationContext; +import org.apache.chemistry.opencmis.client.api.QueryResult; +import org.apache.chemistry.opencmis.client.runtime.OperationContextImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Test to check that RM doesn't break CMIS query + * + * @author jcule, Rodica Sutu + * @since 2.5.4 + * @since 3.3 + */ +public class CmisQueryTests extends BaseRMRestTest +{ + private static final String SEARCH_TERM = generateTestPrefix(CmisQueryTests.class); + private static final String SQL_WITH_NAME = + "SELECT cmis:name FROM cmis:document where CONTAINS('cmis:name:*" + SEARCH_TERM + "*')"; + + private SiteModel collaborationSite; + private UserModel nonRMUser, rmUser; + private RecordCategoryChild recordFolder; + + @Autowired + private ContentActions contentActions; + + /** + * Create some test data: + *
+     *     - a collaboration site with documents
+     *     - in place records
+     *     - category with folder and records
+     *     - a user with no rm rights (no rights to see the record from file plan)
+     *     - a user with rights to see the records and the other documents created
+     * 
+ */ + @BeforeClass (alwaysRun = true) + public void setupCmisQuery() throws Exception + { + STEP("Create a collaboration site"); + collaborationSite = dataSite.usingAdmin().createPrivateRandomSite(); + + STEP("Create 10 documents ending with SEARCH_TERM"); + for (int i = 0; ++i <= 10; ) + { + FileModel fileModel = new FileModel(String.format("%s.%s", "Doc" + i + SEARCH_TERM, + FileType.TEXT_PLAIN.extention)); + dataContent.usingAdmin().usingSite(collaborationSite).createContent(fileModel); + } + + STEP("Create a collaborator user for the collaboration site"); + nonRMUser = getDataUser().createRandomTestUser(); + getDataUser().addUserToSite(nonRMUser, collaborationSite, UserRole.SiteManager); + + STEP("Create 10 documents and declare as records"); + for (int i = 0; ++i <= 10; ) + { + FileModel fileModel = new FileModel(String.format("%s.%s", "InPlace " + SEARCH_TERM + i, + FileType.TEXT_PLAIN.extention)); + fileModel = dataContent.usingUser(nonRMUser).usingSite(collaborationSite).createContent(fileModel); + getRestAPIFactory().getFilesAPI(nonRMUser).declareAsRecord(fileModel.getNodeRefWithoutVersion()); + } + + STEP("Create record folder and some records "); + recordFolder = createCategoryFolderInFilePlan(); + for (int i = 0; ++i <= 10; ) + { + createElectronicRecord(recordFolder.getId(), "Record " + SEARCH_TERM + i); + } + STEP("Create an rm user with read permission over the category created and contributor role within the " + + "collaboration site"); + rmUser = getDataUser().createRandomTestUser(); + getRestAPIFactory().getRMUserAPI().assignRoleToUser(rmUser.getUsername(), ROLE_RM_MANAGER.roleId); + getRestAPIFactory().getRMUserAPI().addUserPermission(recordFolder.getParentId(), rmUser, UserPermissions.PERMISSION_READ_RECORDS); + getDataUser().addUserToSite(rmUser, collaborationSite, UserRole.SiteContributor); + + + //do a cmis query to wait for solr indexing + long currentTime = System.currentTimeMillis(); + long endTime = 0; + do + { + try + { + endTime = System.currentTimeMillis(); + ItemIterable results = contentActions.getCMISSession(getAdminUser().getUsername(), + getAdminUser().getPassword()).query(SQL_WITH_NAME, false); + assertEquals("Total number of items is not 30, got " + results.getTotalNumItems() + "total items", + 30, results.getTotalNumItems()); + break; + } + catch (AssertionError | Exception e) + { + if (endTime - currentTime > 30000) + { + throw new AssertionError("Maximum retry period reached, test failed.", e); + } + Thread.sleep(5000); + } + } while (true); + } + + /** + *
+     * Given the RM site created
+     * When I execute a cmis query to get all the documents names
+     * Then I get all documents names 100 per page
+     * 
+ */ + @Test + @AlfrescoTest (jira = "MNT-19442") + public void getAllDocumentsNamesCmisQuery() + { + // execute the cmis query + String cq = "SELECT cmis:name FROM cmis:document"; + ItemIterable results = + contentActions.getCMISSession(getAdminUser().getUsername(), getAdminUser().getPassword()).query(cq, + false); + + // check the total number of items is greater than 100 and has more items is true + assertTrue("Has more items not true.", results.getHasMoreItems()); + assertTrue("Total number of items is not greater than 100. Total number of items received" + results.getTotalNumItems(), + results.getTotalNumItems() > 100); + assertEquals("Expected 100 items per page and got " + results.getPageNumItems() + " per page.", 100, + results.getPageNumItems()); + } + + /** + *
+     * Given the RM site created
+     * When I execute a cmis query to get all the documents names with a particular name
+     * Then I get all documents names user has permission
+     * 
+ */ + @Test + @AlfrescoTest (jira = "MNT-19442") + public void getDocumentsWithSpecificNamesCmisQuery() throws Exception + { + // execute the cmis query + ItemIterable results = + contentActions.getCMISSession(nonRMUser.getUsername(), nonRMUser.getPassword()).query(SQL_WITH_NAME, + false); + assertEquals("Total number of items is not 20, got " + results.getTotalNumItems() + " total items", + 20, results.getTotalNumItems()); + // check the has more items is false + assertFalse("Has more items not false.", results.getHasMoreItems()); + assertEquals("Expected 20 items per page and got " + results.getPageNumItems() + " per page.", 20, + results.getPageNumItems()); + } + + /** + *
+     * Given the RM site created
+     * When I execute a cmis query to get all the documents names with a specific number per page
+     * Then I get all documents names paged as requested that the user has permission
+     * 
+ */ + @Test + @AlfrescoTest (jira = "MNT-19442") + public void getDocumentsCmisQueryWithPagination() throws Exception + { + OperationContext oc = new OperationContextImpl(); + oc.setMaxItemsPerPage(10); + ItemIterable results = + contentActions.getCMISSession(rmUser.getUsername(), rmUser.getPassword()).query(SQL_WITH_NAME, + false, oc); + + // check the total number of items and has more items is true + assertTrue("Has more items not true. ", results.getHasMoreItems()); + assertEquals("Total number of items is not 30 " + results.getTotalNumItems(), 30, + results.getTotalNumItems()); + assertEquals("Expected 10 items per page and got " + results.getPageNumItems() + " per page.", + 10, results.getPageNumItems()); + } + + @AfterClass + private void clearCmisQueryTests() + { + dataSite.usingAdmin().deleteSite(collaborationSite); + getRestAPIFactory().getRecordCategoryAPI().deleteRecordCategory(recordFolder.getParentId()); + getDataUser().usingAdmin().deleteUser(rmUser); + getDataUser().usingAdmin().deleteUser(nonRMUser); + } +} diff --git a/rm-community/rm-community-repo/config/alfresco/module/org_alfresco_module_rm/rm-public-services-security-context.xml b/rm-community/rm-community-repo/config/alfresco/module/org_alfresco_module_rm/rm-public-services-security-context.xml index ce4d04e6f8..2fcb3340c2 100644 --- a/rm-community/rm-community-repo/config/alfresco/module/org_alfresco_module_rm/rm-public-services-security-context.xml +++ b/rm-community/rm-community-repo/config/alfresco/module/org_alfresco_module_rm/rm-public-services-security-context.xml @@ -159,6 +159,7 @@ ${system.acl.maxPermissionChecks} + diff --git a/rm-community/rm-community-repo/source/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProvider.java b/rm-community/rm-community-repo/source/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProvider.java index ac37edeb46..f7ae3fc6c0 100644 --- a/rm-community/rm-community-repo/source/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProvider.java +++ b/rm-community/rm-community-repo/source/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProvider.java @@ -46,10 +46,10 @@ import net.sf.acegisecurity.vote.AccessDecisionVoter; import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel; +import org.alfresco.module.org_alfresco_module_rm.util.AuthenticationUtil; import org.alfresco.repo.search.SimpleResultSetMetaData; import org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet; import org.alfresco.repo.search.impl.querymodel.QueryEngineResults; -import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.permissions.PermissionCheckCollection; import org.alfresco.repo.security.permissions.PermissionCheckValue; import org.alfresco.repo.security.permissions.PermissionCheckedCollection.PermissionCheckedCollectionMixin; @@ -80,8 +80,8 @@ public class RMAfterInvocationProvider extends RMSecurityCommon private static final String AFTER_RM = "AFTER_RM"; + private AuthenticationUtil authenticationUtil; private int maxPermissionChecks; - private long maxPermissionCheckTimeMillis; public boolean supports(ConfigAttribute configAttribute) @@ -131,6 +131,16 @@ public class RMAfterInvocationProvider extends RMSecurityCommon this.maxPermissionCheckTimeMillis = maxPermissionCheckTimeMillis; } + /** + * Sets the authentication util + * + * @param authenticationUtil The authentication util to set + */ + public void setAuthenticationUtil(AuthenticationUtil authenticationUtil) + { + this.authenticationUtil = authenticationUtil; + } + @SuppressWarnings("rawtypes") public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config, Object returnedObject) { @@ -148,7 +158,7 @@ public class RMAfterInvocationProvider extends RMSecurityCommon } try { - if (AuthenticationUtil.isRunAsUserTheSystemUser()) + if (authenticationUtil.isRunAsUserTheSystemUser()) { if (logger.isDebugEnabled()) { @@ -564,6 +574,13 @@ public class RMAfterInvocationProvider extends RMSecurityCommon } } + if (maxSize != null) + { + LimitBy limitBy = returnedObject.length() > maxSize ? LimitBy.FINAL_SIZE : LimitBy.UNLIMITED; + filteringResultSet.setResultSetMetaData(new SimpleResultSetMetaData(limitBy, + PermissionEvaluationMode.EAGER, returnedObject.getResultSetMetaData().getSearchParameters())); + } + filteringResultSet.setNumberFound(returnedObject.getNumberFound()); return filteringResultSet; diff --git a/rm-community/rm-community-repo/unit-test/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProviderUnitTest.java b/rm-community/rm-community-repo/unit-test/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProviderUnitTest.java new file mode 100644 index 0000000000..36dc2efeb2 --- /dev/null +++ b/rm-community/rm-community-repo/unit-test/java/org/alfresco/module/org_alfresco_module_rm/capability/RMAfterInvocationProviderUnitTest.java @@ -0,0 +1,178 @@ +/* + * #%L + * Alfresco Records Management Module + * %% + * Copyright (C) 2005 - 2020 Alfresco Software Limited + * %% + * This file is part of the Alfresco software. + * - + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * - + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * - + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * - + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see . + * #L% + */ + +package org.alfresco.module.org_alfresco_module_rm.capability; + +import static java.util.Arrays.asList; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.List; + +import net.sf.acegisecurity.Authentication; +import net.sf.acegisecurity.ConfigAttribute; +import net.sf.acegisecurity.ConfigAttributeDefinition; +import org.alfresco.module.org_alfresco_module_rm.util.AuthenticationUtil; +import org.alfresco.repo.security.permissions.impl.acegi.FilteringResultSet; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.NodeService; +import org.alfresco.service.cmr.search.LimitBy; +import org.alfresco.service.cmr.search.ResultSet; +import org.alfresco.service.cmr.search.ResultSetMetaData; +import org.alfresco.service.cmr.search.SearchParameters; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; + +/** Unit tests for {@link RMAfterInvocationProvider}. */ +public class RMAfterInvocationProviderUnitTest +{ + private static final NodeRef NODE_A = new NodeRef("test://node/a"); + + /** The class under test. */ + @InjectMocks + private RMAfterInvocationProvider rmAfterInvocationProvider; + @Mock + private Authentication authentication; + @Mock + Object object; + @Mock + ConfigAttributeDefinition config; + @Mock + AuthenticationUtil authenticationUtil; + @Mock + NodeService nodeService; + @Mock + ChildAssociationRef childAssocRefA; + + /** Set up the mocks and common test data. */ + @Before + public void setUp() + { + initMocks(this); + + // Set up the nodes and associations. + when(nodeService.exists(NODE_A)).thenReturn(true); + when(childAssocRefA.getParentRef()).thenReturn(NODE_A); + + // Create the config object for use by the tests. + ConfigAttribute configAttribute = mock(ConfigAttribute.class); + when(configAttribute.getAttribute()).thenReturn("AFTER_RM.test"); + List configAttributes = asList(configAttribute); + when(config.getConfigAttributes()).thenReturn(configAttributes.iterator()); + } + + /** Check that when all the results fit into a page then we get a response of "UNLIMITED". */ + @Test + public void testDecide_resultSet_unlimited() + { + // The returned object is a search result set. + ResultSet returnedObject = mock(ResultSet.class); + ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); + when(returnedObject.getResultSetMetaData()).thenReturn(resultSetMetaData); + + // Simulate a single result, and the user has access to it. + when(returnedObject.length()).thenReturn(1); + when(returnedObject.getNumberFound()).thenReturn(1L); + when(returnedObject.getNodeRef(0)).thenReturn(NODE_A); + when(returnedObject.getChildAssocRef(0)).thenReturn(childAssocRefA); + + // Set the page size to 1 and skip count to 0. + SearchParameters searchParameters = mock(SearchParameters.class); + when(searchParameters.getMaxItems()).thenReturn(1); + when(searchParameters.getSkipCount()).thenReturn(0); + when(resultSetMetaData.getSearchParameters()).thenReturn(searchParameters); + + // Call the method under test. + FilteringResultSet filteringResultSet = (FilteringResultSet) rmAfterInvocationProvider.decide(authentication, object, config, returnedObject); + + assertEquals("Expected total of one result.", 1, filteringResultSet.getNumberFound()); + assertEquals("Expected one result returned.", 1, filteringResultSet.length()); + assertEquals("Expected that results were not limited by the page size.", LimitBy.UNLIMITED, filteringResultSet.getResultSetMetaData().getLimitedBy()); + } + + /** Check that results can skipped due to the skip count. */ + @Test + public void testDecide_resultSet_skipped() + { + // The returned object is a search result set. + ResultSet returnedObject = mock(ResultSet.class); + ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); + when(returnedObject.getResultSetMetaData()).thenReturn(resultSetMetaData); + + // Simulate a single result that was skipped due to the skip count. + when(returnedObject.length()).thenReturn(0); + when(returnedObject.getNumberFound()).thenReturn(1L); + + // Set the page size to 1 and skip count to 1 (so the result is skipped). + SearchParameters searchParameters = mock(SearchParameters.class); + when(searchParameters.getMaxItems()).thenReturn(1); + when(searchParameters.getSkipCount()).thenReturn(1); + when(resultSetMetaData.getSearchParameters()).thenReturn(searchParameters); + + // Call the method under test. + FilteringResultSet filteringResultSet = (FilteringResultSet) rmAfterInvocationProvider.decide(authentication, object, config, returnedObject); + + assertEquals("Expected total of one result.", 1, filteringResultSet.getNumberFound()); + assertEquals("Expected no results returned.", 0, filteringResultSet.length()); + assertEquals("Expected that results were not limited by the page size.", LimitBy.UNLIMITED, filteringResultSet.getResultSetMetaData().getLimitedBy()); + } + + /** Check that results can be limited by the page size. */ + @Test + public void testDecide_resultSet_pageSize() + { + // The returned object is a search result set. + ResultSet returnedObject = mock(ResultSet.class); + ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); + when(returnedObject.getResultSetMetaData()).thenReturn(resultSetMetaData); + + // Simulate a single result, and the user has access to it. + when(returnedObject.length()).thenReturn(1); + when(returnedObject.getNumberFound()).thenReturn(1L); + when(returnedObject.getNodeRef(0)).thenReturn(NODE_A); + when(returnedObject.getChildAssocRef(0)).thenReturn(childAssocRefA); + + // Set the page size to 0 and skip count to 0 (so the result is not in page). + SearchParameters searchParameters = mock(SearchParameters.class); + when(searchParameters.getMaxItems()).thenReturn(0); + when(searchParameters.getSkipCount()).thenReturn(0); + when(resultSetMetaData.getSearchParameters()).thenReturn(searchParameters); + + // Call the method under test. + FilteringResultSet filteringResultSet = (FilteringResultSet) rmAfterInvocationProvider.decide(authentication, object, config, returnedObject); + + assertEquals("Expected total of one result.", 1, filteringResultSet.getNumberFound()); + assertEquals("Expected no results returned.", 0, filteringResultSet.length()); + assertEquals("Expected that results were limited by page size.", LimitBy.FINAL_SIZE, filteringResultSet.getResultSetMetaData().getLimitedBy()); + } +}