X-Git-Url: https://dev.e-taxonomy.eu/gitweb/cdmlib.git/blobdiff_plain/29e24283bcf0b19d2553bf9b9bcdf2217a20879d..84ab49d70a39676f233056ef68502dff371b370d:/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/SecurityTest.java diff --git a/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/SecurityTest.java b/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/SecurityTest.java index ff2019c980..1c56ab3bbd 100644 --- a/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/SecurityTest.java +++ b/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/SecurityTest.java @@ -9,9 +9,14 @@ package eu.etaxonomy.cdm.api.service; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.io.FileNotFoundException; import java.util.Collection; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.UUID; @@ -19,75 +24,66 @@ import javax.sql.DataSource; import org.apache.log4j.Logger; import org.junit.Assert; -import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.dao.ReflectionSaltSource; import org.springframework.security.authentication.dao.SaltSource; -import org.springframework.security.authentication.encoding.Md5PasswordEncoder; import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.transaction.PlatformTransactionManager; import org.unitils.database.annotations.TestDataSource; import org.unitils.dbunit.annotation.DataSet; import org.unitils.spring.annotation.SpringBean; import org.unitils.spring.annotation.SpringBeanByType; -import eu.etaxonomy.cdm.database.EvaluationFailedException; +import com.mchange.util.AssertException; + +import sun.security.provider.PolicyParser.ParsingException; +import eu.etaxonomy.cdm.database.PermissionDeniedException; +import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl; import eu.etaxonomy.cdm.model.common.User; import eu.etaxonomy.cdm.model.description.DescriptionElementBase; -import eu.etaxonomy.cdm.model.description.Distribution; import eu.etaxonomy.cdm.model.description.Feature; import eu.etaxonomy.cdm.model.description.TaxonDescription; import eu.etaxonomy.cdm.model.description.TextData; import eu.etaxonomy.cdm.model.name.BotanicalName; import eu.etaxonomy.cdm.model.name.Rank; +import eu.etaxonomy.cdm.model.name.TaxonNameBase; +import eu.etaxonomy.cdm.model.name.ZoologicalName; +import eu.etaxonomy.cdm.model.reference.Reference; +import eu.etaxonomy.cdm.model.reference.ReferenceFactory; +import eu.etaxonomy.cdm.model.taxon.Classification; import eu.etaxonomy.cdm.model.taxon.Synonym; +import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType; import eu.etaxonomy.cdm.model.taxon.Taxon; import eu.etaxonomy.cdm.model.taxon.TaxonBase; import eu.etaxonomy.cdm.model.taxon.TaxonNode; +import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD; +import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmAuthority; +import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmPermissionClass; import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmPermissionEvaluator; -import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTestWithSecurity; +import eu.etaxonomy.cdm.persistence.hibernate.permission.Operation; +import eu.etaxonomy.cdm.persistence.query.MatchMode; @DataSet -public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ - - private static final UUID UUID_ACHERONTINII = UUID.fromString("928a0167-98cd-4555-bf72-52116d067625"); - - private static final UUID UUID_ACHERONTIA_STYX = UUID.fromString("7b8b5cb3-37ba-4dba-91ac-4c6ffd6ac331"); - - private static final UUID UUID_LACTUCA = UUID.fromString("b2b007a4-9c8c-43a1-8da4-20ed85464cf2"); - - private static final UUID PART_EDITOR_UUID = UUID.fromString("38a251bd-0ba4-426f-8fcb-5c09560749a7"); - - private static final String PASSWORD_TAXON_EDITOR = "test2"; - - private static final String PASSWORD_ADMIN = "sPePhAz6"; +public class SecurityTest extends AbstractSecurityTestBase{ - private static final UUID ACHERONTIA_NODE_UUID = UUID.fromString("20c8f083-5870-4cbd-bf56-c5b2b98ab6a7"); - - private static final UUID ACHERONTIINI_NODE_UUID = UUID.fromString("cecfa77f-f26a-4476-9d87-a8d993cb55d9"); - - private static final UUID ACHERONTIA_LACHESIS_UUID = UUID.fromString("bc09aca6-06fd-4905-b1e7-cbf7cc65d783"); private static final Logger logger = Logger.getLogger(SecurityTest.class); - /** - * The transaction manager to use - */ @SpringBeanByType - PlatformTransactionManager transactionManager; + private ITaxonService taxonService; @SpringBeanByType - private ITaxonService taxonService; + private INameService nameService; + + @SpringBeanByType + private IReferenceService referenceService; @SpringBeanByType private ITaxonNodeService taxonNodeService; @@ -98,11 +94,8 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ @SpringBeanByType private IUserService userService; - - @TestDataSource - protected DataSource dataSource; - - private Authentication authentication; + @SpringBeanByType + private IClassificationService classificationService; @SpringBeanByType private AuthenticationManager authenticationManager; @@ -116,94 +109,137 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ @SpringBean("cdmPermissionEvaluator") private CdmPermissionEvaluator permissionEvaluator; - private UsernamePasswordAuthenticationToken tokenForAdmin; + @TestDataSource + protected DataSource dataSource; - private UsernamePasswordAuthenticationToken tokenForTaxonEditor; + private Authentication authentication; - private UsernamePasswordAuthenticationToken tokenForDescriptionEditor; - private UsernamePasswordAuthenticationToken tokenForPartEditor; + /** + * no assertions in this test, since it is only used to create password hashes for test data + */ + @Test + public void testEncryptPassword(){ - private UsernamePasswordAuthenticationToken tokenForTaxonomist; + String password = PASSWORD_ADMIN; + User user = User.NewInstance("userManager", ""); + Object salt = this.saltSource.getSalt(user); + String passwordEncrypted = passwordEncoder.encodePassword(password, salt); + logger.info("encrypted password: " + passwordEncrypted ); + } - @Before - public void setUp(){ - /* User 'admin': - - ROLE_ADMIN - - ALL.ADMIN - - TAXONBASE.READ - - TAXONBASE.CREATE - - TAXONBASE.DELETE - - TAXONBASE.UPDATE - */ - tokenForAdmin = new UsernamePasswordAuthenticationToken("admin", PASSWORD_ADMIN); + @Test + @DataSet + public void testHasPermission(){ - /* User 'taxonEditor': - - TAXONBASE.CREATE - - TAXONBASE.UPDATE - */ - tokenForTaxonEditor = new UsernamePasswordAuthenticationToken("taxonEditor", PASSWORD_TAXON_EDITOR); + Taxon taxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()),null); - /* User 'descriptionEditor': - - DESCRIPTIONBASE.CREATE - - DESCRIPTIONBASE.UPDATE - - DESCRIPTIONELEMENT(Ecology).CREATE - - DESCRIPTIONELEMENT(Ecology).UPDATE - */ - tokenForDescriptionEditor = new UsernamePasswordAuthenticationToken("descriptionEditor", "test"); + authentication = authenticationManager.authenticate(tokenForTaxonomist); + boolean hasPermission = permissionEvaluator.hasPermission(authentication, taxon, Operation.UPDATE); + assertTrue(hasPermission); - /* User 'partEditor': - - TAXONBASE.ADMIN - - TAXONNODE.CREATE{20c8f083-5870-4cbd-bf56-c5b2b98ab6a7} - - TAXONNODE.UPDATE{20c8f083-5870-4cbd-bf56-c5b2b98ab6a7} - */ - tokenForPartEditor = new UsernamePasswordAuthenticationToken("partEditor", "test4"); + authentication = authenticationManager.authenticate(tokenForDescriptionEditor); + hasPermission = permissionEvaluator.hasPermission(authentication, taxon, Operation.UPDATE); + assertFalse(hasPermission); + } - /* User 'taxonomist': - - TAXONBASE.READ - - TAXONBASE.CREATE - - TAXONBASE.DELETE - - TAXONBASE.UPDATE - */ - tokenForTaxonomist = new UsernamePasswordAuthenticationToken("taxonomist", "test4"); + @Test + @DataSet + public void testListByUsernameAllow(){ + + authentication = authenticationManager.authenticate(tokenForTaxonomist); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + List userList = userService.listByUsername("Editor", MatchMode.ANYWHERE, null, null, 0, null, null); + Assert.assertTrue("The user list must have elements", userList.size() > 0 ); } - /** - * no assertions in this test, since it is only used to create password hashes for test data - */ @Test - public void testEncryptPassword(){ + @DataSet + public void testUserService_CreateDeny(){ - String password = PASSWORD_ADMIN; - User user = User.NewInstance("admin", ""); + authentication = authenticationManager.authenticate(tokenForTaxonomist); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + RuntimeException exception = null; + try { + userService.createUser(User.NewInstance("new guy", "alkjdsfalkj")); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.debug("Expected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + logger.debug("Expected failure of evaluation.", e); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNotNull("Must fail here!", exception); - Object salt = this.saltSource.getSalt(user); - String passwordEncrypted = passwordEncoder.encodePassword(password, salt); - logger.info("encrypted password: " + passwordEncrypted ); } + @Test + @DataSet + public void testUserService_CreateAllow(){ + + authentication = authenticationManager.authenticate(tokenForUserManager); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + RuntimeException exception = null; + try { + userService.createUser(User.NewInstance("new guy", "alkjdsfalkj")); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + logger.error("unexpected failure of evaluation.", exception); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNull("Must not fail here!", exception); + + } + + + @Test + @DataSet + @Ignore // FIXME http://dev.e-taxonomy.eu/trac/ticket/3098 + public void testHasPermissions(){ + + Taxon taxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()),null); + + authentication = authenticationManager.authenticate(tokenForTaxonomist); + boolean hasPermission = permissionEvaluator.hasPermission(authentication, taxon, Operation.ALL); + assertTrue(hasPermission); + } + + /** * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#saveTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}. */ @Test public final void testSaveTaxon() { - /* - Md5PasswordEncoder encoder =new Md5PasswordEncoder(); - ReflectionSaltSource saltSource = new ReflectionSaltSource(); - saltSource.setUserPropertyToUse("getUsername"); - User user = User.NewInstance("partEditor", "test4"); - System.err.println(encoder.encodePassword("test4", saltSource.getSalt(user))); - */ authentication = authenticationManager.authenticate(tokenForAdmin); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(authentication); Taxon expectedTaxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null); + expectedTaxon.getName().setTitleCache("Newby admin", true); UUID uuid = taxonService.save(expectedTaxon); commitAndStartNewTransaction(null); - //taxonService.getSession().flush(); TaxonBase actualTaxon = taxonService.load(uuid); assertEquals(expectedTaxon, actualTaxon); @@ -211,9 +247,193 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ context = SecurityContextHolder.getContext(); context.setAuthentication(authentication); expectedTaxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null); - taxonService.saveOrUpdate(actualTaxon); + expectedTaxon.getName().setTitleCache("Newby taxonEditor", true); + uuid = taxonService.saveOrUpdate(expectedTaxon); + commitAndStartNewTransaction(null); + actualTaxon = taxonService.load(uuid); + assertEquals(expectedTaxon, actualTaxon); + + } + + @Test + public final void testSaveNameAllow() { + + authentication = authenticationManager.authenticate(tokenForTaxonEditor); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + ZoologicalName newName = ZoologicalName.NewInstance(Rank.SPECIES()); + newName.setTitleCache("Newby taxonEditor", true); + UUID uuid = nameService.saveOrUpdate(newName); commitAndStartNewTransaction(null); + TaxonNameBase savedName = nameService.load(uuid); + assertEquals(newName, savedName); + } + + + @Test + public final void testReuseNameAllow() { + + authentication = authenticationManager.authenticate(tokenForTaxonEditor); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + TaxonBase taxon = taxonService.find(UUID_ACHERONTIA_STYX); + TaxonNameBase n_acherontia_thetis = taxon.getName(); + + Taxon newTaxon = Taxon.NewInstance(n_acherontia_thetis, ReferenceFactory.newGeneric()); + Exception exception = null; + try { + UUID uuid = taxonService.save(newTaxon); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNull("must not fail here!", exception); + } + + @Test + public final void testMakeTaxonNodeASynonymOfAnotherTaxonNodeAllow_1() { + + authentication = authenticationManager.authenticate(tokenForTaxonEditor); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + Reference book = referenceService.load(BOOK1_UUID); + + TaxonNode n_acherontia_styx = taxonNodeService.find(ACHERONTIA_STYX_NODE_UUID); + TaxonNode n_acherontia_lachersis = taxonNodeService.find(ACHERONTIA_LACHESIS_NODE_UUID); + + Exception exception = null; + try { + taxonNodeService.makeTaxonNodeASynonymOfAnotherTaxonNode(n_acherontia_styx, n_acherontia_lachersis, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF(), book , "33"); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + }finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNull("must not fail here!", exception); + } + + @Test + public final void testMakeTaxonNodeASynonymOfAnotherTaxonNodeAllow_2() { + + authentication = authenticationManager.authenticate(tokenForTaxonEditor); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + Reference book = referenceService.load(BOOK1_UUID); + + TaxonNode n_acherontia_styx = taxonNodeService.find(ACHERONTIA_STYX_NODE_UUID); + TaxonNode n_acherontia_lachersis = taxonNodeService.find(ACHERONTIA_LACHESIS_NODE_UUID); + + Exception exception = null; + try { + taxonNodeService.makeTaxonNodeASynonymOfAnotherTaxonNode(n_acherontia_lachersis, n_acherontia_styx, SynonymRelationshipType.HOMOTYPIC_SYNONYM_OF(), book , "33"); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNull("must not fail here!", exception); + } + + @Test + public final void testUpdateReferenceAllow() throws ParsingException { + + + authentication = authenticationManager.authenticate(tokenForUserManager); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + // add REFERENCE[UPDATE] to taxonEditor + User taxonEditor = userService.load(TAXON_EDITOR_UUID); + Set grantedAuthorities = new HashSet(); + grantedAuthorities.addAll(taxonEditor.getGrantedAuthorities()); + GrantedAuthorityImpl referenceUpdate_ga = new CdmAuthority(CdmPermissionClass.REFERENCE, null, EnumSet.of(CRUD.UPDATE), null).asNewGrantedAuthority(); + grantedAuthorities.add(referenceUpdate_ga); + taxonEditor.setGrantedAuthorities(grantedAuthorities); + userService.saveOrUpdate(taxonEditor); + commitAndStartNewTransaction(null); + + authentication = authenticationManager.authenticate(tokenForTaxonEditor); + context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + Reference book = referenceService.load(BOOK1_UUID); + book.setTitleCache("Mobydick", true); + Exception exception = null; + try { + referenceService.saveOrUpdate(book); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + logger.error("Unexpected failure of evaluation.", e); + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNull("must not fail here!", exception); + book = referenceService.load(BOOK1_UUID); + Assert.assertEquals("Mobydick", book.getTitleCache()); + } + + @Test + public final void testUpateReferenceDeny() { + + authentication = authenticationManager.authenticate(tokenForTaxonEditor); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(authentication); + + TaxonBase taxon = taxonService.find(UUID_ACHERONTIA_STYX); + taxon.getName().getNomenclaturalReference().setTitleCache("Mobydick", true); + Exception exception = null; + try { + UUID uuid = taxonService.saveOrUpdate(taxon); + commitAndStartNewTransaction(null); + } catch (AccessDeniedException e){ + logger.debug("Expected failure of evaluation.", e); + exception = e; + } catch (RuntimeException e){ + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + logger.debug("Expected failure of evaluation.", e); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNotNull("must fail here!", exception); } @Test @@ -253,7 +473,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ logger.error("Unexpected failure of evaluation.", e); exception = e; } catch (RuntimeException e){ - exception = findThrowableOfTypeIn(EvaluationFailedException.class, e); + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); logger.error("Unexpected failure of evaluation.", exception); } finally { // needed in case saveOrUpdate was interrupted by the RuntimeException @@ -280,7 +500,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ // check test preconditions user name and authorities Assert.assertEquals("descriptionEditor", context.getAuthentication().getName()); - Collection authorities = context.getAuthentication().getAuthorities(); + Collection authorities = context.getAuthentication().getAuthorities(); for(GrantedAuthority authority: authorities){ // role prefix 'ROLE_' is defined in org.springframework.security.access.vote.RoleVoter !!! Assert.assertNotSame("user must not have authority 'ROLE_ADMIN'", "ROLE_ADMIN", authority.getAuthority()); @@ -293,8 +513,8 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ logger.debug("Expected failure of evaluation.", e); exception = e; } catch (RuntimeException e){ - exception = findThrowableOfTypeIn(EvaluationFailedException.class, e); - logger.debug("Expected failure of evaluation.", exception); + exception = findThrowableOfTypeIn(PermissionDeniedException.class, e); + logger.debug("Expected failure of evaluation.", e); } finally { // needed in case saveOrUpdate was interrupted by the RuntimeException // commitAndStartNewTransaction() would raise an UnexpectedRollbackException @@ -336,7 +556,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ context.setAuthentication(authentication); RuntimeException securityException= null; - TaxonBase taxon = taxonService.load(UUID_ACHERONTIA_STYX); + TaxonBase taxon = taxonService.find(UUID_ACHERONTIA_STYX); Assert.assertFalse(taxon.isDoubtful()); taxon.setDoubtful(true); try{ @@ -353,8 +573,8 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ } Assert.assertNull("evaluation must not fail since the user is permitted, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); // reload taxon - taxon = taxonService.load(UUID_ACHERONTIA_STYX); - Assert.assertTrue("The change must be persited", taxon.isDoubtful()); + taxon = taxonService.find(UUID_ACHERONTIA_STYX); + Assert.assertTrue("The change must be persisted", taxon.isDoubtful()); } /** @@ -372,7 +592,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ context.setAuthentication(authentication); - TaxonBase taxon = taxonService.load(UUID_ACHERONTIA_STYX); + TaxonBase taxon = taxonService.find(UUID_ACHERONTIA_STYX); Assert.assertFalse(taxon.isDoubtful()); taxon.setDoubtful(true); try{ @@ -389,7 +609,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ } Assert.assertNull("evaluation must not fail since the user is permitted, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); // reload taxon - taxon = taxonService.load(UUID_ACHERONTIA_STYX); + taxon = taxonService.find(UUID_ACHERONTIA_STYX); Assert.assertTrue("The change must be persited", taxon.isDoubtful()); } @@ -405,7 +625,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ authentication = authenticationManager.authenticate(tokenForDescriptionEditor); context.setAuthentication(authentication); - TaxonBase taxon = taxonService.load(UUID_ACHERONTIA_STYX); + TaxonBase taxon = taxonService.find(UUID_ACHERONTIA_STYX); Assert.assertFalse(taxon.isDoubtful()); taxon.setDoubtful(true); @@ -424,15 +644,12 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ Assert.assertNotNull("evaluation must fail since the user is not permitted", securityException); // reload taxon - taxon = taxonService.load(UUID_ACHERONTIA_STYX); + taxon = taxonService.find(UUID_ACHERONTIA_STYX); Assert.assertFalse("The change must not be persited", taxon.isDoubtful()); } - /** - * test with admin account - should succeed - */ @Test - public final void testTaxonDeleteAllow_1() { + public final void testTaxonPublishAllow_ROLE_ADMIN() { SecurityContext context = SecurityContextHolder.getContext(); @@ -440,9 +657,12 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ context.setAuthentication(authentication); RuntimeException securityException= null; - TaxonBase taxon = taxonService.load(UUID_LACTUCA); + Taxon taxon = (Taxon) taxonService.find(UUID_ACHERONTIA_STYX); + + boolean lastIsPublish = taxon.isPublish(); + taxon.setPublish(!lastIsPublish); try{ - taxonService.delete(taxon); + taxonService.saveOrUpdate(taxon); commitAndStartNewTransaction(null); } catch (RuntimeException e){ securityException = findSecurityRuntimeException(e); @@ -453,31 +673,31 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ endTransaction(); startNewTransaction(); } - Assert.assertNull("evaluation must not fail since the user is permitted, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); + Assert.assertNull("evaluation must not fail since the user has ROLE_ADMIN, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); // reload taxon - taxon = taxonService.load(UUID_LACTUCA); - Assert.assertNull("The taxon must be deleted", taxon); + taxon = (Taxon) taxonService.find(UUID_ACHERONTIA_STYX); + Assert.assertTrue("The change must be persisted", taxon.isPublish() != lastIsPublish); } + /** - * test with admin account - should succeed + * test with Taxonomist account which has the ROLE_PUBLISH */ @Test - @Ignore - /*FIXME fails due to org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations) - * see ticket #3086 - */ - public final void testTaxonDeleteAllow_2() { + public final void testTaxonPublishAllow_ROLE_PUBLISH() { SecurityContext context = SecurityContextHolder.getContext(); - authentication = authenticationManager.authenticate(tokenForAdmin); + authentication = authenticationManager.authenticate(tokenForTaxonomist); context.setAuthentication(authentication); RuntimeException securityException= null; - TaxonBase taxon = taxonService.load(UUID_ACHERONTINII); + Taxon taxon = (Taxon) taxonService.find(UUID_ACHERONTIA_STYX); + + boolean lastIsPublish = taxon.isPublish(); + taxon.setPublish(!lastIsPublish); try{ - taxonService.delete(taxon); + taxonService.saveOrUpdate(taxon); commitAndStartNewTransaction(null); } catch (RuntimeException e){ securityException = findSecurityRuntimeException(e); @@ -488,29 +708,30 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ endTransaction(); startNewTransaction(); } - Assert.assertNull("evaluation must not fail since the user is permitted, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); + Assert.assertNull("evaluation must not fail since the user has ROLE_ADMIN, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); // reload taxon - taxon = taxonService.load(UUID_ACHERONTINII); - Assert.assertNull("The taxon must be deleted", taxon); + taxon = (Taxon) taxonService.find(UUID_ACHERONTIA_STYX); + Assert.assertTrue("The change must be persisted", taxon.isPublish() != lastIsPublish); } - /** - * test with tokenForDescriptionEditor account - should fail + * test with TaxonEditor account which has not the ROLE_PUBLISH */ @Test - public final void testTaxonDeleteDeny() { + public final void testTaxonPublishDeny() { SecurityContext context = SecurityContextHolder.getContext(); - RuntimeException securityException = null; - authentication = authenticationManager.authenticate(tokenForDescriptionEditor); + authentication = authenticationManager.authenticate(tokenForTaxonEditor); context.setAuthentication(authentication); + RuntimeException securityException= null; - TaxonBase taxon = taxonService.load(UUID_LACTUCA); + Taxon taxon = (Taxon) taxonService.find(UUID_ACHERONTIA_STYX); + boolean lastIsPublish = taxon.isPublish(); + taxon.setPublish(!lastIsPublish); try { - taxonService.delete(taxon); + taxonService.saveOrUpdate(taxon); commitAndStartNewTransaction(null); } catch (RuntimeException e){ securityException = findSecurityRuntimeException(e); @@ -524,8 +745,104 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ Assert.assertNotNull("evaluation must fail since the user is not permitted", securityException); // reload taxon + taxon = (Taxon) taxonService.find(UUID_ACHERONTIA_STYX); + Assert.assertTrue("The taxon must be unchanged", taxon.isPublish() == lastIsPublish); + } + + /** + * test with admin account - should succeed + */ + @Test + public final void testTaxonDeleteAllow_1() { + + SecurityContext context = SecurityContextHolder.getContext(); + + authentication = authenticationManager.authenticate(tokenForAdmin); + context.setAuthentication(authentication); + RuntimeException securityException= null; + + TaxonBase taxon = taxonService.load(UUID_LACTUCA); + taxonService.delete(taxon); + commitAndStartNewTransaction(null); + + + + + Assert.assertNull("evaluation must not fail since the user is permitted, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); + // reload taxon taxon = taxonService.load(UUID_LACTUCA); + Assert.assertNull("The taxon must be deleted", taxon); + } + + /** + * test with admin account - should succeed + */ + @Test + public final void testTaxonDeleteAllow_2() { + + SecurityContext context = SecurityContextHolder.getContext(); + + authentication = authenticationManager.authenticate(tokenForAdmin); + context.setAuthentication(authentication); + RuntimeException securityException= null; + + Taxon taxon = (Taxon)taxonService.load(UUID_ACHERONTINII); + try{ + // try { + DeleteResult result = taxonService.deleteTaxon(taxon.getUuid(), null, null); + /*} catch (DataChangeNoRollbackException e) { + Assert.fail(); + }*/ + if (!result.isOk()){ + Assert.fail(); + } + commitAndStartNewTransaction(null); + } catch (RuntimeException e){ + securityException = findSecurityRuntimeException(e); + logger.error("Unexpected failure of evaluation.", e); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + Assert.assertNull("evaluation must not fail since the user is permitted, CAUSE :" + (securityException != null ? securityException.getMessage() : ""), securityException); + // reload taxon + + taxon = (Taxon)taxonService.find(UUID_ACHERONTINII); + Assert.assertNull("The taxon must be deleted", taxon); + } + + + /** + * test with tokenForDescriptionEditor account - should fail + */ + @Test + public final void testTaxonDeleteDeny() { + + SecurityContext context = SecurityContextHolder.getContext(); + RuntimeException securityException = null; + + authentication = authenticationManager.authenticate(tokenForDescriptionEditor); + context.setAuthentication(authentication); + + Taxon taxon = (Taxon)taxonService.load(UUID_LACTUCA); + try{ + DeleteResult result = taxonService.deleteTaxon(taxon.getUuid(), null, null); + Assert.fail(); + }catch(PermissionDeniedException e){ + + } + endTransaction(); + startNewTransaction(); + + + //Assert.assertNotNull("evaluation must fail since the user is not permitted", securityException); + // reload taxon + taxon = (Taxon)taxonService.load(UUID_LACTUCA); + Assert.assertNotNull("The change must still exist", taxon); + Assert.assertNotNull("The name must still exist",taxon.getName()); } @@ -565,6 +882,90 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ assertTrue(taxon.getDescriptions().contains(description)); } + @Test + public void testMoveDescriptionElement(){ + + SecurityContext context = SecurityContextHolder.getContext(); + authentication = authenticationManager.authenticate(tokenForTaxonomist); + context.setAuthentication(authentication); + + RuntimeException securityException = null; + + Taxon t_acherontia_lachesis = (Taxon)taxonService.load(ACHERONTIA_LACHESIS_UUID); + Taxon t_acherontia_styx = (Taxon)taxonService.load(UUID_ACHERONTIA_STYX); + + TaxonDescription description_acherontia_styx = t_acherontia_styx.getDescriptions().iterator().next(); + TaxonDescription description_acherontia_lachesis = t_acherontia_lachesis.getDescriptions().iterator().next(); + + try { + descriptionService.moveDescriptionElementsToDescription(description_acherontia_styx.getElements(), description_acherontia_lachesis, false); + commitAndStartNewTransaction(null); + } catch (RuntimeException e){ + securityException = findSecurityRuntimeException(e); + logger.debug("Unexpected failure of evaluation.", securityException); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + /* + * Expectation: + */ + Assert.assertNull("evaluation should not fail since the user has sufficient permissions", securityException); + + } + +// @Ignore // FIXME http://dev.e-taxonomy.eu/trac/ticket/4081 : #4081 (TaxonNodeServiceImpl.makeTaxonNodeASynonymOfAnotherTaxonNode() requires TAXONNAMEBASE.[UPDATE]) + @Test + public void testAcceptedTaxonToSynomym(){ + + SecurityContext context = SecurityContextHolder.getContext(); + authentication = authenticationManager.authenticate(tokenForPartEditor); + context.setAuthentication(authentication); + + RuntimeException securityException = null; + + Taxon t_acherontia_lachesis = (Taxon)taxonService.load(ACHERONTIA_LACHESIS_UUID); + UUID name_acherontia_lachesis_uuid = t_acherontia_lachesis.getName().getUuid(); + Taxon t_acherontia_styx = (Taxon)taxonService.load(UUID_ACHERONTIA_STYX); + int countSynsBefore = t_acherontia_styx.getSynonyms().size(); + + TaxonNode n_acherontia_lachesis = t_acherontia_lachesis.getTaxonNodes().iterator().next(); + TaxonNode n_acherontia_styx = t_acherontia_styx.getTaxonNodes().iterator().next(); + + int numOfSynonymsBefore_styx = t_acherontia_styx.getSynonyms().size(); + int numOfSynonymsBefore_lachesis = t_acherontia_lachesis.getSynonyms().size(); + + + try { + DeleteResult result = taxonNodeService.makeTaxonNodeASynonymOfAnotherTaxonNode(n_acherontia_lachesis, n_acherontia_styx, SynonymRelationshipType.SYNONYM_OF(), null, null); +// synonymUuid = synonym.getUuid(); +// taxonService.saveOrUpdate(synonym); + commitAndStartNewTransaction(null); + } catch (RuntimeException e){ + securityException = findSecurityRuntimeException(e); + logger.error("Unexpected Exception ", e); + Assert.fail("Unexpected Exception: " + e.getMessage()); + } finally { + // needed in case saveOrUpdate was interrupted by the RuntimeException + // commitAndStartNewTransaction() would raise an UnexpectedRollbackException + endTransaction(); + startNewTransaction(); + } + /* + * Expectation: + */ + Assert.assertNull("evaluation should not fail since the user has sufficient permissions", securityException); + + // reload from db and check assertions + t_acherontia_styx = (Taxon)taxonService.load(UUID_ACHERONTIA_STYX); + Assert.assertEquals(numOfSynonymsBefore_styx +1 + numOfSynonymsBefore_lachesis, t_acherontia_styx.getSynonyms().size()); + + Assert.assertNotNull(nameService.load(name_acherontia_lachesis_uuid) ); + Assert.assertNull("The old TaxonNode should no longer exist", taxonNodeService.find(n_acherontia_lachesis.getUuid())); + } + @Test public void testCreateDescriptionWithElement(){ @@ -589,6 +990,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ commitAndStartNewTransaction(null); } catch (RuntimeException e){ securityException = findSecurityRuntimeException(e); + logger.error("RuntimeException caught"); logger.debug("Expected failure of evaluation.", securityException); } finally { // needed in case saveOrUpdate was interrupted by the RuntimeException @@ -748,11 +1150,11 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(authentication); RuntimeException securityException = null; - + Classification classification = classificationService.load(UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9")); // test for success TaxonNode acherontia_node = taxonNodeService.load(ACHERONTIA_NODE_UUID); long numOfChildNodes = acherontia_node.getChildNodes().size(); - TaxonNode childNode = acherontia_node.addChildTaxon(Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null), null, null, null); + TaxonNode childNode = acherontia_node.addChildTaxon(Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null), null, null); try{ taxonNodeService.saveOrUpdate(acherontia_node); @@ -784,7 +1186,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ securityException = null; TaxonNode acherontiini_node = taxonNodeService.load(ACHERONTIINI_NODE_UUID); int numOfChildNodes = acherontiini_node.getCountChildren(); - acherontiini_node.addChildTaxon(Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null), null, null, null); + acherontiini_node.addChildTaxon(Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null), null, null); try{ logger.debug("=============================="); @@ -806,4 +1208,13 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{ } + /* (non-Javadoc) + * @see eu.etaxonomy.cdm.test.integration.CdmIntegrationTest#createTestData() + */ + @Override + public void createTestDataSet() throws FileNotFoundException { + // TODO Auto-generated method stub + + } + }