From 6f1192e01e6fadc19fce3425c9f50d65336665d7 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Wed, 13 Dec 2017 17:36:03 +0100 Subject: [PATCH 01/13] POC --- .../security/boundary/PermissionBoundary.java | 111 ++++++++++++++++++ .../rest/dtos/RestrictionsCreationDTO.java | 69 +++++++++++ .../rest/permissions/RestrictionsRest.java | 21 ++++ 3 files changed, 201 insertions(+) create mode 100644 AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index be1579d0b..8eec0b832 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -457,6 +457,117 @@ public Integer createRestriction(String roleName, String userName, String permis throw new AMWException("No permission to create this permission"); } + /** + * Creates multiple RestrctionEntites and returns how many that have been created + * + * @param roleName + * @param userNames + * @param permissionNames + * @param resourceGroupIds + * @param resourceTypeNames + * @param resourceTypePermission + * @param contextNames + * @param actions + * @return + */ + @HasPermission(permission = Permission.ASSIGN_REMOVE_PERMISSION, action = Action.CREATE) + public Integer createMultipleRestrictions(String roleName, List userNames, List permissionNames, List resourceGroupIds, List resourceTypeNames, + ResourceTypePermission resourceTypePermission, List contextNames, List actions) throws AMWException { + int count = 0; + for (String permissionName : permissionNames) { + for (Action action : actions) { + if (userNames == null || userNames.isEmpty()) { + if (resourceGroupIds != null && !resourceGroupIds.isEmpty()) { + for (Integer resourceGroupId : resourceGroupIds) { + if (contextNames == null || contextNames.isEmpty()) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, null, permissionName, resourceGroupId, null, + resourceTypePermission, null, action, restriction); + if (created != null) { + count++; + } + } else { + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, null, permissionName, resourceGroupId, null, + resourceTypePermission, contextName, action, restriction); + if (created != null) { + count++; + } + } + } + } + } else { + for (String resourceTypeName : resourceTypeNames) { + if (contextNames.isEmpty()) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, null, permissionName, null, resourceTypeName, + resourceTypePermission, null, action, restriction); + if (created != null) { + count++; + } + } else { + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, null, permissionName, null, resourceTypeName, + resourceTypePermission, contextName, action, restriction); + if (created != null) { + count++; + } + } + } + } + } + } else { + for (String userName : userNames) { + if (!resourceGroupIds.isEmpty()) { + for (Integer resourceGroupId : resourceGroupIds) { + if (contextNames.isEmpty()) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, userName, permissionName, resourceGroupId, null, + resourceTypePermission, null, action, restriction); + if (created != null) { + count++; + } + } else { + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, userName, permissionName, resourceGroupId, null, + resourceTypePermission, contextName, action, restriction); + if (created != null) { + count++; + } + } + } + } + } else { + for (String resourceTypeName : resourceTypeNames) { + if (contextNames.isEmpty()) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, userName, permissionName, null, resourceTypeName, + resourceTypePermission, null, action, restriction); + if (created != null) { + count++; + } + } else { + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + Integer created = createRestriction(roleName, userName, permissionName, null, resourceTypeName, + resourceTypePermission, contextName, action, restriction); + if (created != null) { + count++; + } + } + } + } + } + } + } + } + } + return count; + } + public boolean canDelegatePermissionsForThisResource(ResourceEntity resource, ContextEntity context) { return (permissionService.hasPermission(Permission.PERMISSION_DELEGATION) && canDelegateThisPermission(Permission.RESOURCE.name(), resource.getResourceGroup().getId(), null, context.getName(), null)); } diff --git a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java new file mode 100644 index 000000000..4c39830b0 --- /dev/null +++ b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java @@ -0,0 +1,69 @@ +/* + * AMW - Automated Middleware allows you to manage the configurations of + * your Java EE applications on an unlimited number of different environments + * with various versions, including the automated deployment of those apps. + * Copyright (C) 2013-2016 by Puzzle ITC + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package ch.mobi.itc.mobiliar.rest.dtos; + +import ch.puzzle.itc.mobiliar.business.security.entity.Action; +import ch.puzzle.itc.mobiliar.business.security.entity.ResourceTypePermission; +import lombok.Data; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "restrictionsCreation") +@XmlAccessorType(XmlAccessType.FIELD) +@Data +public class RestrictionsCreationDTO { + + private String roleName; + + private List userNames; + + private List permissions; + + private List resourceGroupIds; + + private List resourceTypeNames; + + private ResourceTypePermission resourceTypePermission; + + private List contextNames; + + private List actions; + + RestrictionsCreationDTO(){} + + public RestrictionsCreationDTO(String roleName, List userNames, List permissions, + List resourceGroupIds, List resourceTypeNames, + ResourceTypePermission resourceTypePermission, List contextNames, + List actions) { + this.roleName = roleName; + this.userNames = userNames; + this.permissions = permissions; + this.resourceGroupIds = resourceGroupIds; + this.resourceTypeNames = resourceTypeNames; + this.resourceTypePermission = resourceTypePermission; + this.contextNames = contextNames; + this.actions = actions; + } + +} diff --git a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java index fadf61bcc..e03c2770c 100644 --- a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java +++ b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java @@ -22,6 +22,7 @@ import ch.mobi.itc.mobiliar.rest.dtos.PermissionDTO; import ch.mobi.itc.mobiliar.rest.dtos.RestrictionDTO; +import ch.mobi.itc.mobiliar.rest.dtos.RestrictionsCreationDTO; import ch.mobi.itc.mobiliar.rest.exceptions.ExceptionDto; import ch.puzzle.itc.mobiliar.business.environment.boundary.ContextLocator; import ch.puzzle.itc.mobiliar.business.security.boundary.PermissionBoundary; @@ -85,6 +86,26 @@ public Response addRestriction(@ApiParam("Add a Restriction, either a role- or a return Response.status(CREATED).header("Location", "/permissions/restrictions/" + id).build(); } + @POST + @Path("/multi/") + @ApiOperation(value = "Add a multiple Restrictions") + public Response addRestriction(@ApiParam("Add multiple Restriction, either a role- or one or more userNames must be set") RestrictionsCreationDTO request) { + if (request.getPermissions().isEmpty()) { + return Response.status(BAD_REQUEST).entity(new ExceptionDto("At least on Permission is required")).build(); + } + Integer count; + try { + count = permissionBoundary.createMultipleRestrictions(request.getRoleName(), request.getUserNames(), request.getPermissions(), request.getResourceGroupIds(), + request.getResourceTypeNames(), request.getResourceTypePermission(), request.getContextNames(), request.getActions()); + } catch (AMWException e) { + return Response.status(BAD_REQUEST).entity(new ExceptionDto(e.getMessage())).build(); + } + if (count == null) { + return Response.status(PRECONDITION_FAILED).entity(new ExceptionDto("Similar permissions already exists")).build(); + } + return Response.status(CREATED).header("X-Total-Count", count).build(); + } + /** * Find a Restriction by its id * From af05ba9056259205c9c0ca4b0f44999a88808923 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Tue, 19 Dec 2017 14:28:13 +0100 Subject: [PATCH 02/13] Renaming and additional checks --- .../security/boundary/PermissionBoundary.java | 16 ++++++++-------- .../security/control/PermissionRepository.java | 5 +++-- .../boundary/PermissionBoundaryTest.java | 4 +++- .../rest/dtos/RestrictionsCreationDTO.java | 6 +++--- .../rest/permissions/RestrictionsRest.java | 6 +++--- 5 files changed, 20 insertions(+), 17 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index 762a3cb50..c0b2d7471 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -501,7 +501,7 @@ public Integer createMultipleRestrictions(String roleName, List userName } } else { for (String resourceTypeName : resourceTypeNames) { - if (contextNames.isEmpty()) { + if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); Integer created = createRestriction(roleName, null, permissionName, null, resourceTypeName, resourceTypePermission, null, action, restriction); @@ -522,9 +522,9 @@ public Integer createMultipleRestrictions(String roleName, List userName } } else { for (String userName : userNames) { - if (!resourceGroupIds.isEmpty()) { + if (resourceGroupIds != null && !resourceGroupIds.isEmpty()) { for (Integer resourceGroupId : resourceGroupIds) { - if (contextNames.isEmpty()) { + if (contextNames == null ||contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); Integer created = createRestriction(roleName, userName, permissionName, resourceGroupId, null, resourceTypePermission, null, action, restriction); @@ -544,7 +544,7 @@ public Integer createMultipleRestrictions(String roleName, List userName } } else { for (String resourceTypeName : resourceTypeNames) { - if (contextNames.isEmpty()) { + if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); Integer created = createRestriction(roleName, userName, permissionName, null, resourceTypeName, resourceTypePermission, null, action, restriction); @@ -789,17 +789,17 @@ private void validateRestriction(String roleName, String userName, String permis } if (permissionName != null) { - try { - restriction.setPermission(permissionRepository.getPermissionByName(permissionName)); - } catch (NoResultException ne) { + PermissionEntity permission = permissionRepository.getPermissionByName(permissionName); + if (permission == null) { throw new AMWException("Permission " + permissionName + " not found."); } + restriction.setPermission(permission); } else { throw new AMWException("Missing PermissionName"); } if (resourceTypePermission == null || resourceTypePermission.equals(ResourceTypePermission.ANY)) { - if (resourceGroupId != null && resourceTypeName!= null) { + if (resourceGroupId != null && resourceTypeName != null) { throw new AMWException("Only ResourceGroup OR ResourceType must be set"); } } else if (resourceGroupId != null || resourceTypeName!= null) { diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/control/PermissionRepository.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/control/PermissionRepository.java index 67ec75b2c..7f2df014b 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/control/PermissionRepository.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/control/PermissionRepository.java @@ -87,8 +87,9 @@ public List getAllUserRestrictionNames() { } public PermissionEntity getPermissionByName(String permissionName) { - return entityManager.createQuery("from PermissionEntity p where LOWER(p.value) =:permission", PermissionEntity.class) - .setParameter("permission", permissionName.toLowerCase()).getSingleResult(); + List result = entityManager.createQuery("from PermissionEntity p where LOWER(p.value) =:permission", PermissionEntity.class) + .setParameter("permission", permissionName.toLowerCase()).getResultList(); + return result == null || result.isEmpty() ? null : result.get(0); } public List getAllPermissions() { diff --git a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java index 038b8fcb2..9e42fd535 100644 --- a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java +++ b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java @@ -148,7 +148,7 @@ public void shouldThrowAMWExceptionOnUpdateIfPermissionCanNotBeFound() throws AM // given when(restrictionRepository.find(1)).thenReturn(new RestrictionEntity()); when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("invalid")).thenThrow(new NoResultException()); + when(permissionRepository.getPermissionByName("invalid")).thenReturn(null); // when // then permissionBoundary.updateRestriction(1, "existing", null, "invalid", null, null, null, null, null); } @@ -270,6 +270,7 @@ public void shouldCheckIfCallerHasSimilarRestrictionIfHeWantsToDelegatePermissio // given when(permissionService.hasPermissionToDelegatePermission(Permission.SHAKEDOWNTEST, null, null, null, CREATE)).thenReturn(true); when(permissionRepository.getUserRestrictionByName("fed")).thenReturn(new UserRestrictionEntity()); + when(permissionRepository.getPermissionByName(anyString())).thenReturn(new PermissionEntity()); // when permissionBoundary.createRestriction(null, "fred", "SHAKEDOWNTEST", null, null, null, null, CREATE, true); // then @@ -772,6 +773,7 @@ public void shouldCreateAllSelfAssignedPermissionsIfCallerHasTheRequiredPermissi when(permissionService.getCurrentUserName()).thenReturn("tester"); when(permissionService.hasPermission(Permission.ADD_ADMIN_PERMISSIONS_ON_CREATED_RESOURCE)).thenReturn(true); when(resourceGroupRepository.find(resource.getResourceGroup().getId())).thenReturn(resource.getResourceGroup()); + when(permissionRepository.getPermissionByName(anyString())).thenReturn(new PermissionEntity()); // when permissionBoundary.createAutoAssignedRestrictions(resource); diff --git a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java index 4c39830b0..1a62b8866 100644 --- a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java +++ b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/RestrictionsCreationDTO.java @@ -38,7 +38,7 @@ public class RestrictionsCreationDTO { private List userNames; - private List permissions; + private List permissionNames; private List resourceGroupIds; @@ -52,13 +52,13 @@ public class RestrictionsCreationDTO { RestrictionsCreationDTO(){} - public RestrictionsCreationDTO(String roleName, List userNames, List permissions, + public RestrictionsCreationDTO(String roleName, List userNames, List permissionNames, List resourceGroupIds, List resourceTypeNames, ResourceTypePermission resourceTypePermission, List contextNames, List actions) { this.roleName = roleName; this.userNames = userNames; - this.permissions = permissions; + this.permissionNames = permissionNames; this.resourceGroupIds = resourceGroupIds; this.resourceTypeNames = resourceTypeNames; this.resourceTypePermission = resourceTypePermission; diff --git a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java index e03c2770c..16a35106d 100644 --- a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java +++ b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java @@ -89,13 +89,13 @@ public Response addRestriction(@ApiParam("Add a Restriction, either a role- or a @POST @Path("/multi/") @ApiOperation(value = "Add a multiple Restrictions") - public Response addRestriction(@ApiParam("Add multiple Restriction, either a role- or one or more userNames must be set") RestrictionsCreationDTO request) { - if (request.getPermissions().isEmpty()) { + public Response addRestriction(@ApiParam("Add multiple Restrictions, either a role- or one or more userNames must be set") RestrictionsCreationDTO request) { + if (request.getPermissionNames().isEmpty()) { return Response.status(BAD_REQUEST).entity(new ExceptionDto("At least on Permission is required")).build(); } Integer count; try { - count = permissionBoundary.createMultipleRestrictions(request.getRoleName(), request.getUserNames(), request.getPermissions(), request.getResourceGroupIds(), + count = permissionBoundary.createMultipleRestrictions(request.getRoleName(), request.getUserNames(), request.getPermissionNames(), request.getResourceGroupIds(), request.getResourceTypeNames(), request.getResourceTypePermission(), request.getContextNames(), request.getActions()); } catch (AMWException e) { return Response.status(BAD_REQUEST).entity(new ExceptionDto(e.getMessage())).build(); From 7fc1615ac288411867d886fe3bc800edfaedfa30 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Wed, 20 Dec 2017 10:47:20 +0100 Subject: [PATCH 03/13] Additional tests for forced removal of property descriptors --- .../PropertyDescriptorServiceTest.java | 143 +++++++++++++++--- 1 file changed, 121 insertions(+), 22 deletions(-) diff --git a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyDescriptorServiceTest.java b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyDescriptorServiceTest.java index c6ee3531e..e8733e64a 100644 --- a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyDescriptorServiceTest.java +++ b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyDescriptorServiceTest.java @@ -27,7 +27,13 @@ import javax.persistence.EntityManager; import javax.persistence.TypedQuery; +import ch.puzzle.itc.mobiliar.builders.PropertyEntityBuilder; +import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceContextEntity; import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceEntity; +import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceTypeEntity; +import ch.puzzle.itc.mobiliar.business.resourcerelation.entity.ConsumedResourceRelationEntity; +import ch.puzzle.itc.mobiliar.business.resourcerelation.entity.ResourceRelationContextEntity; +import ch.puzzle.itc.mobiliar.business.resourcerelation.entity.ResourceRelationTypeEntity; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -72,7 +78,6 @@ public class PropertyDescriptorServiceTest { @InjectMocks PropertyDescriptorService service; - @Before public void setUp() { MockitoAnnotations.initMocks(this); @@ -107,6 +112,7 @@ public void testManageChangeOfEncryptedPropertyDescriptorDecryptNotAuthorized() public void testManageChangeOfEncryptedPropertyDescriptorEncryptNotAuthorized() throws Exception { testManageChangeOfEncryptedPropertyDescriptor(Boolean.TRUE, false); } + /** * We don't expect an exception since nothing is changed */ @@ -119,46 +125,41 @@ void testManageChangeOfEncryptedPropertyDescriptor(Boolean encrypt, boolean hasP TypedQuery queryMock = mock(TypedQuery.class); when(entityManagerMock.createQuery(anyString(), any(Class.class))).thenReturn(queryMock); when(queryMock.setParameter(anyString(), any())).thenReturn(queryMock); - if(hasPermission){ + if (hasPermission) { doNothing().when(permissionServiceMock).checkPermissionAndFireException(any(Permission.class), anyString()); - } - else{ + } else { doThrow(NotAuthorizedException.class).when(permissionServiceMock).checkPermissionAndFireException(any(Permission.class), anyString()); } PropertyEntity p = mock(PropertyEntity.class); when(queryMock.getResultList()).thenReturn(Arrays.asList(p)); PropertyDescriptorEntity propertyDescriptorEntity = new PropertyDescriptorEntity(); - if(encrypt!=null){ + if (encrypt != null) { propertyDescriptorEntity.setEncrypt(encrypt); } propertyDescriptorEntity.setId(1); List encryptedProperties; - if(encrypt==null || encrypt){ - encryptedProperties = Collections.emptyList(); - } - else{ + if (encrypt == null || encrypt) { + encryptedProperties = Collections.emptyList(); + } else { encryptedProperties = Arrays.asList(propertyDescriptorEntity.getId()); } service.manageChangeOfEncryptedPropertyDescriptor(propertyDescriptorEntity, encryptedProperties, hasPermission); - if(encrypt!=null){ - if(encrypt){ + if (encrypt != null) { + if (encrypt) { verify(p, times(0)).decrypt(); verify(p, times(1)).encrypt(); - } - else{ + } else { verify(p, times(1)).decrypt(); verify(p, times(0)).encrypt(); } - } - else{ + } else { verify(p, times(0)).decrypt(); verify(p, times(0)).encrypt(); } } - @Test(expected = AMWException.class) public void savePropertyDescriptorForOwnerWhenDescriptorIsNullShouldThrowException() throws AMWException { // given @@ -170,7 +171,7 @@ public void savePropertyDescriptorForOwnerWhenDescriptorIsNullShouldThrowExcepti ResourceEntity resourceEntityMock = mock(ResourceEntity.class); // when - service.savePropertyDescriptorForOwner(changingOwner, abstractContextMock, descriptor, tags, resourceEntityMock ); + service.savePropertyDescriptorForOwner(changingOwner, abstractContextMock, descriptor, tags, resourceEntityMock); } @Test(expected = AMWException.class) @@ -179,7 +180,8 @@ public void savePropertyDescriptorForOwnerWhenTechnicalKeyIsInvalidShouldThrowEx ForeignableOwner changingOwner = ForeignableOwner.AMW; AbstractContext abstractContextMock = mock(AbstractContext.class); - PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().build();; + PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().build(); + List tags = new ArrayList<>(); Assert.assertNull(descriptor.getId()); ResourceEntity resourceEntityMock = mock(ResourceEntity.class); @@ -325,25 +327,62 @@ public void deletePropertyDescriptorByOwnerWhenDeletingOwnerIsOwnerOfDescriptorB } @Test - public void deletePropertyDescriptorByOwnerIncludingPropertyValuesWhenDeletingOwnerIsOwnerOfDescriptorWithPropertiesShouldSucceed() throws AMWException { + public void deletePropertyDescriptorByOwnerIncludingPropertyValuesWhenDeletingOwnerIsOwnerOfDescriptorWithPropertiesOnResourceShouldSucceed() throws AMWException { // given ForeignableOwner deletingOwner = ForeignableOwner.AMW; AbstractContext abstractContextMock = mock(AbstractContext.class); ResourceEntity resourceEntityMock = mock(ResourceEntity.class); + PropertyEntity property = new PropertyEntity(); Set properties = new HashSet<>(); - properties.add(new PropertyEntity()); + properties.add(property); + PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().withOwner(deletingOwner).withId(1).withProperties(properties).build(); + Assert.assertEquals(deletingOwner, descriptor.getOwner()); + ResourceContextEntity resourceContextEntityMock = mock(ResourceContextEntity.class); + + TypedQuery queryMock = mock(TypedQuery.class); + when(entityManagerMock.createQuery("from PropertyDescriptorEntity d left join fetch d.propertyTags where d.id = :propertyDescriptorId ", PropertyDescriptorEntity.class)).thenReturn(queryMock); + when(queryMock.getSingleResult()).thenReturn(descriptor); + when(resourceEntityMock.getContexts()).thenReturn(Collections.singleton(resourceContextEntityMock)); + when(resourceContextEntityMock.getProperties()).thenReturn(properties); + + // when + service.deletePropertyDescriptorByOwnerIncludingPropertyValues(descriptor, abstractContextMock, resourceEntityMock); + + // then + verify(resourceContextEntityMock).removeProperty(property); + verify(entityManagerMock).remove(descriptor); + } + + @Test + public void deletePropertyDescriptorByOwnerIncludingPropertyValuesWhenDeletingOwnerIsOwnerOfDescriptorWithPropertiesOnResourceRelationShouldSucceed() throws AMWException { + // given + ForeignableOwner deletingOwner = ForeignableOwner.AMW; + + AbstractContext abstractContextMock = mock(AbstractContext.class); + ResourceEntity resourceEntityMock = mock(ResourceEntity.class); + PropertyEntity property = new PropertyEntity(); + Set properties = new HashSet<>(); + properties.add(property); PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().withOwner(deletingOwner).withId(1).withProperties(properties).build(); Assert.assertEquals(deletingOwner, descriptor.getOwner()); + ResourceContextEntity resourceContextEntityMock = mock(ResourceContextEntity.class); + ConsumedResourceRelationEntity consumedResourceRelationEntityMock = mock(ConsumedResourceRelationEntity.class); + ResourceRelationContextEntity resourceRelationContextEntityMock = mock(ResourceRelationContextEntity.class); TypedQuery queryMock = mock(TypedQuery.class); when(entityManagerMock.createQuery("from PropertyDescriptorEntity d left join fetch d.propertyTags where d.id = :propertyDescriptorId ", PropertyDescriptorEntity.class)).thenReturn(queryMock); when(queryMock.getSingleResult()).thenReturn(descriptor); + when(resourceEntityMock.getContexts()).thenReturn(Collections.singleton(resourceContextEntityMock)); + when(resourceEntityMock.getConsumedSlaveRelations()).thenReturn(Collections.singleton(consumedResourceRelationEntityMock)); + when(consumedResourceRelationEntityMock.getContexts()).thenReturn(Collections.singleton(resourceRelationContextEntityMock)); + when(resourceRelationContextEntityMock.getProperties()).thenReturn(properties); // when service.deletePropertyDescriptorByOwnerIncludingPropertyValues(descriptor, abstractContextMock, resourceEntityMock); // then + verify(resourceRelationContextEntityMock).removeProperty(property); verify(entityManagerMock).remove(descriptor); } @@ -360,7 +399,6 @@ public void deletePropertyDescriptorByOwnerWhenDeletingOwnerIsOwnerOfDescriptorW PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().withOwner(deletingOwner).withTags(tag1, tag2).withId(1).build(); Assert.assertEquals(deletingOwner, descriptor.getOwner()); - TypedQuery queryMock = mock(TypedQuery.class); when(entityManagerMock.createQuery("from PropertyDescriptorEntity d left join fetch d.propertyTags where d.id = :propertyDescriptorId ", PropertyDescriptorEntity.class)).thenReturn(queryMock); when(queryMock.getSingleResult()).thenReturn(descriptor); @@ -369,7 +407,6 @@ public void deletePropertyDescriptorByOwnerWhenDeletingOwnerIsOwnerOfDescriptorW when(entityManagerMock.find(PropertyTagEntity.class, tag1.getId())).thenReturn(tag1); when(entityManagerMock.find(PropertyTagEntity.class, tag2.getId())).thenReturn(tag2); - // when service.deletePropertyDescriptorByOwner(descriptor, abstractContextMock); @@ -378,5 +415,67 @@ public void deletePropertyDescriptorByOwnerWhenDeletingOwnerIsOwnerOfDescriptorW verify(entityManagerMock).remove(tag2); } + @Test + public void deletePropertyDescriptorByOwnerIncludingPropertyValuesWhenDeletingOwnerIsOwnerOfDescriptorDefinedOnResourceTypeWithPropertiesOnResourceShouldSucceed() throws AMWException { + // given + ForeignableOwner deletingOwner = ForeignableOwner.AMW; + + AbstractContext abstractContextMock = mock(AbstractContext.class); + ResourceTypeEntity resourceTypeEntityMock = mock(ResourceTypeEntity.class); + ResourceEntity resourceEntityMock = mock(ResourceEntity.class); + ResourceContextEntity resourceContextEntityMock = mock(ResourceContextEntity.class); + PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().withOwner(deletingOwner).withId(1).build(); + PropertyEntity property = new PropertyEntityBuilder().buildPropertyEntity("propVal", descriptor); + descriptor.addProperty(property); + Set properties = new HashSet<>(); + properties.add(property); + + TypedQuery queryMock = mock(TypedQuery.class); + when(entityManagerMock.createQuery("from PropertyDescriptorEntity d left join fetch d.propertyTags where d.id = :propertyDescriptorId ", PropertyDescriptorEntity.class)).thenReturn(queryMock); + when(queryMock.getSingleResult()).thenReturn(descriptor); + when(entityManagerMock.find(PropertyDescriptorEntity.class, descriptor.getId())).thenReturn(descriptor); + when(resourceTypeEntityMock.getResources()).thenReturn(Collections.singleton(resourceEntityMock)); + when(resourceEntityMock.getContexts()).thenReturn(Collections.singleton(resourceContextEntityMock)); + when(resourceContextEntityMock.getProperties()).thenReturn(properties); + + // when + service.deletePropertyDescriptorByOwnerIncludingPropertyValues(descriptor, abstractContextMock, resourceTypeEntityMock); + + // then + verify(resourceContextEntityMock).removeProperty(property); + verify(entityManagerMock).remove(descriptor); + } + + @Test + public void deletePropertyDescriptorByOwnerIncludingPropertyValuesWhenDeletingOwnerIsOwnerOfDescriptorDefinedOnResourceTypeWithPropertiesOnResourceRelationShouldSucceed() throws AMWException { + // given + ForeignableOwner deletingOwner = ForeignableOwner.AMW; + + AbstractContext abstractContextMock = mock(AbstractContext.class); + ResourceTypeEntity resourceTypeEntityMock = mock(ResourceTypeEntity.class); + PropertyEntity property = new PropertyEntity(); + Set properties = new HashSet<>(); + properties.add(property); + PropertyDescriptorEntity descriptor = new PropertyDescriptorEntityBuilder().withOwner(deletingOwner).withId(1).withProperties(properties).build(); + Assert.assertEquals(deletingOwner, descriptor.getOwner()); + ResourceRelationTypeEntity resourceRelationTypeEntityMock = mock(ResourceRelationTypeEntity.class); + ConsumedResourceRelationEntity consumedResourceRelationEntityMock = mock(ConsumedResourceRelationEntity.class); + ResourceRelationContextEntity resourceRelationContextEntityMock = mock(ResourceRelationContextEntity.class); + + TypedQuery queryMock = mock(TypedQuery.class); + when(entityManagerMock.createQuery("from PropertyDescriptorEntity d left join fetch d.propertyTags where d.id = :propertyDescriptorId ", PropertyDescriptorEntity.class)).thenReturn(queryMock); + when(queryMock.getSingleResult()).thenReturn(descriptor); + when(resourceTypeEntityMock.getResourceRelationTypesB()).thenReturn(Collections.singleton(resourceRelationTypeEntityMock)); + when(resourceRelationTypeEntityMock.getConsumedResourceRelations()).thenReturn(Collections.singleton(consumedResourceRelationEntityMock)); + when(consumedResourceRelationEntityMock.getContexts()).thenReturn(Collections.singleton(resourceRelationContextEntityMock)); + when(resourceRelationContextEntityMock.getProperties()).thenReturn(properties); + + // when + service.deletePropertyDescriptorByOwnerIncludingPropertyValues(descriptor, abstractContextMock, resourceTypeEntityMock); + + // then + verify(resourceRelationContextEntityMock).removeProperty(property); + verify(entityManagerMock).remove(descriptor); + } } \ No newline at end of file From eb1d9955ba913959f1fc3fce9fe2be1e9abdfb08 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Wed, 20 Dec 2017 15:32:28 +0100 Subject: [PATCH 04/13] Display warning for props defined on related slave resource on relation props --- .../control/PropertyEditingService.java | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java index 4b051a50f..0f440eadc 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java @@ -308,9 +308,9 @@ public Map getPropertyOverviewForResourceType(ResourceTypeEntity public Map getPropertyOverviewForRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { switch (relation.getMode()) { case CONSUMED: - return getPropertyOverviewForConsumedRelation(relation.getResRelId(), property, relevantContexts); + return getPropertyOverviewForConsumedRelation(relation, property, relevantContexts); case PROVIDED: - return getPropertyOverviewForProvidedRelation(relation.getResRelId(), property, relevantContexts); + return getPropertyOverviewForProvidedRelation(relation, property, relevantContexts); default: String msg = String.format("Relation mode '%s' is not supported for property overview (property id: %d)", relation.getMode().name(), @@ -321,41 +321,56 @@ public Map getPropertyOverviewForRelation(ResourceEditRelation re } /** * - * @param relationId + * @param relation * @param property * @param relevantContexts - * @return a Map containing all properties which override the value of its parent context. + * @return a Map containing all properties which would be overridden by setting the property on the relation. *
    *
  • Map.key = context Name
  • *
  • Map.value = context of the value
  • *
*/ - private Map getPropertyOverviewForConsumedRelation(int relationId, ResourceEditProperty property, List relevantContexts) { + private Map getPropertyOverviewForConsumedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { return Collections.EMPTY_MAP; } List relevantContextIds = buildRelevantContextIdsList(relevantContexts); - Query query = queries.getPropertyOverviewForConsumedRelatedResourceQuery(property.getTechnicalKey(), relationId, relevantContextIds); - return getDifferingProperties(property, query); + Query query = queries.getPropertyOverviewForConsumedRelatedResourceQuery(property.getTechnicalKey(), relation.getResRelId(), relevantContextIds); + Map differingProperties = getDifferingProperties(property, query); + // TODO check if we need the first query/diff at all + // global context is relevant here + relevantContextIds.add(contextHierarchy.getContextWithParentIds(relevantContexts.get(0)).get(0)); + differingProperties.putAll(getPropertyDefinedOnResource(relation, property, relevantContextIds)); + return differingProperties; } /** * - * @param relationId + * @param relation * @param property * @param relevantContexts - * @return a Map containing all properties which override the value of its parent context. + * @return a Map containing all properties which would be overridden by setting the property on the relation. *
    *
  • Map.key = context Name
  • *
  • Map.value = context of the value
  • *
*/ - private Map getPropertyOverviewForProvidedRelation(int relationId, ResourceEditProperty property, List relevantContexts) { + private Map getPropertyOverviewForProvidedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { return Collections.EMPTY_MAP; } List relevantContextIds = buildRelevantContextIdsList(relevantContexts); - Query query = queries.getPropertyOverviewForProvidedRelatedResourceQuery(property.getTechnicalKey(), relationId, relevantContextIds); + Query query = queries.getPropertyOverviewForProvidedRelatedResourceQuery(property.getTechnicalKey(), relation.getResRelId(), relevantContextIds); + Map differingProperties = getDifferingProperties(property, query); + // TODO check if we need the first query/diff at all + // global context is relevant here + relevantContextIds.add(contextHierarchy.getContextWithParentIds(relevantContexts.get(0)).get(0)); + differingProperties.putAll(getPropertyDefinedOnResource(relation, property, relevantContextIds)); + return differingProperties; + } + + private Map getPropertyDefinedOnResource(ResourceEditRelation relation, ResourceEditProperty property, List relevantContextIds) { + Query query = queries.getPropertyOverviewForResourceQuery(property.getTechnicalKey(), relation.getSlaveId(), relevantContextIds); return getDifferingProperties(property, query); } From a4218075f2a70ff11718eaa4db808e4b8436dfa5 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Wed, 20 Dec 2017 16:02:10 +0100 Subject: [PATCH 05/13] Some simplification --- .../security/boundary/PermissionBoundary.java | 65 ++++++++----------- .../rest/permissions/RestrictionsRest.java | 12 +++- 2 files changed, 36 insertions(+), 41 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index c0b2d7471..a195572dc 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -45,7 +45,6 @@ import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.persistence.EntityManager; -import javax.persistence.NoResultException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -424,14 +423,14 @@ public void createAutoAssignedRestrictions(ResourceEntity resource) throws AMWEx Integer resourceGroupId = resource.getResourceGroup().getId(); if (resourceGroupId != null && getUserName() != null && permissionService.hasPermission(Permission.ADD_ADMIN_PERMISSIONS_ON_CREATED_RESOURCE)) { - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE_AMWFUNCTION.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE_PROPERTY_DECRYPT.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE_TEMPLATE.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE_TEST_GENERATION.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.RESOURCE_TEST_GENERATION_RESULT.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); - createAutoAssignedRestriction(null, getUserName(), Permission.DEPLOYMENT.name(), resourceGroupId, null, null, null, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE_AMWFUNCTION.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE_PROPERTY_DECRYPT.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE_TEMPLATE.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE_TEST_GENERATION.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.RESOURCE_TEST_GENERATION_RESULT.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); + createAutoAssignedRestriction(getUserName(), Permission.DEPLOYMENT.name(), resourceGroupId, Action.ALL, new RestrictionEntity()); } } @@ -473,7 +472,7 @@ public Integer createRestriction(String roleName, String userName, String permis * @return */ @HasPermission(permission = Permission.ASSIGN_REMOVE_PERMISSION, action = Action.CREATE) - public Integer createMultipleRestrictions(String roleName, List userNames, List permissionNames, List resourceGroupIds, List resourceTypeNames, + public int createMultipleRestrictions(String roleName, List userNames, List permissionNames, List resourceGroupIds, List resourceTypeNames, ResourceTypePermission resourceTypePermission, List contextNames, List actions) throws AMWException { int count = 0; for (String permissionName : permissionNames) { @@ -483,17 +482,15 @@ public Integer createMultipleRestrictions(String roleName, List userName for (Integer resourceGroupId : resourceGroupIds) { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, null, permissionName, resourceGroupId, null, - resourceTypePermission, null, action, restriction); - if (created != null) { + if (createRestriction(roleName, null, permissionName, resourceGroupId, null, + resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, null, permissionName, resourceGroupId, null, - resourceTypePermission, contextName, action, restriction); - if (created != null) { + if (createRestriction(roleName, null, permissionName, resourceGroupId, null, + resourceTypePermission, contextName, action, restriction) != null) { count++; } } @@ -503,17 +500,15 @@ public Integer createMultipleRestrictions(String roleName, List userName for (String resourceTypeName : resourceTypeNames) { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, null, permissionName, null, resourceTypeName, - resourceTypePermission, null, action, restriction); - if (created != null) { + if (createRestriction(roleName, null, permissionName, null, resourceTypeName, + resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, null, permissionName, null, resourceTypeName, - resourceTypePermission, contextName, action, restriction); - if (created != null) { + if (createRestriction(roleName, null, permissionName, null, resourceTypeName, + resourceTypePermission, contextName, action, restriction) != null) { count++; } } @@ -526,17 +521,15 @@ public Integer createMultipleRestrictions(String roleName, List userName for (Integer resourceGroupId : resourceGroupIds) { if (contextNames == null ||contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, userName, permissionName, resourceGroupId, null, - resourceTypePermission, null, action, restriction); - if (created != null) { + if (createRestriction(roleName, userName, permissionName, resourceGroupId, null, + resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, userName, permissionName, resourceGroupId, null, - resourceTypePermission, contextName, action, restriction); - if (created != null) { + if (createRestriction(roleName, userName, permissionName, resourceGroupId, null, + resourceTypePermission, contextName, action, restriction) != null) { count++; } } @@ -546,17 +539,15 @@ public Integer createMultipleRestrictions(String roleName, List userName for (String resourceTypeName : resourceTypeNames) { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, userName, permissionName, null, resourceTypeName, - resourceTypePermission, null, action, restriction); - if (created != null) { + if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - Integer created = createRestriction(roleName, userName, permissionName, null, resourceTypeName, - resourceTypePermission, contextName, action, restriction); - if (created != null) { + if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + resourceTypePermission, contextName, action, restriction) != null) { count++; } } @@ -598,11 +589,9 @@ private Integer createRestriction(String roleName, String userName, String permi return id; } - private Integer createAutoAssignedRestriction(String roleName, String userName, String permissionName, Integer resourceGroupId, String resourceTypeName, - ResourceTypePermission resourceTypePermission, String contextName, Action action, RestrictionEntity restriction) + private Integer createAutoAssignedRestriction(String userName, String permissionName, Integer resourceGroupId, Action action, RestrictionEntity restriction) throws AMWException { - validateRestriction(roleName, userName, permissionName, resourceGroupId, resourceTypeName, resourceTypePermission, - contextName, action, restriction); + validateRestriction(null, userName, permissionName, resourceGroupId, null, null, null, action, restriction); if (permissionService.callerHasIdenticalOrMoreGeneralRestriction(restriction)) { return null; } diff --git a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java index 16a35106d..91b9eaffa 100644 --- a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java +++ b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java @@ -86,21 +86,27 @@ public Response addRestriction(@ApiParam("Add a Restriction, either a role- or a return Response.status(CREATED).header("Location", "/permissions/restrictions/" + id).build(); } + /** + * Creates new restrictions + * + * @param request containing a RestrictionsCreationDTO + * @return the total count of created restrictions in the header + */ @POST @Path("/multi/") @ApiOperation(value = "Add a multiple Restrictions") public Response addRestriction(@ApiParam("Add multiple Restrictions, either a role- or one or more userNames must be set") RestrictionsCreationDTO request) { if (request.getPermissionNames().isEmpty()) { - return Response.status(BAD_REQUEST).entity(new ExceptionDto("At least on Permission is required")).build(); + return Response.status(BAD_REQUEST).entity(new ExceptionDto("At least one Permission is required")).build(); } - Integer count; + int count; try { count = permissionBoundary.createMultipleRestrictions(request.getRoleName(), request.getUserNames(), request.getPermissionNames(), request.getResourceGroupIds(), request.getResourceTypeNames(), request.getResourceTypePermission(), request.getContextNames(), request.getActions()); } catch (AMWException e) { return Response.status(BAD_REQUEST).entity(new ExceptionDto(e.getMessage())).build(); } - if (count == null) { + if (count == 0) { return Response.status(PRECONDITION_FAILED).entity(new ExceptionDto("Similar permissions already exists")).build(); } return Response.status(CREATED).header("X-Total-Count", count).build(); From 89cba1556ad64f7be2a2c33fdc2dcab61ff8493e Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Wed, 20 Dec 2017 15:32:28 +0100 Subject: [PATCH 06/13] Display warning for props defined on related slave resource on relation props --- .../control/PropertyEditingService.java | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java index 4b051a50f..80f36219b 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java @@ -308,9 +308,9 @@ public Map getPropertyOverviewForResourceType(ResourceTypeEntity public Map getPropertyOverviewForRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { switch (relation.getMode()) { case CONSUMED: - return getPropertyOverviewForConsumedRelation(relation.getResRelId(), property, relevantContexts); + return getPropertyOverviewForConsumedRelation(relation, property, relevantContexts); case PROVIDED: - return getPropertyOverviewForProvidedRelation(relation.getResRelId(), property, relevantContexts); + return getPropertyOverviewForProvidedRelation(relation, property, relevantContexts); default: String msg = String.format("Relation mode '%s' is not supported for property overview (property id: %d)", relation.getMode().name(), @@ -321,41 +321,54 @@ public Map getPropertyOverviewForRelation(ResourceEditRelation re } /** * - * @param relationId + * @param relation * @param property * @param relevantContexts - * @return a Map containing all properties which override the value of its parent context. + * @return a Map containing all properties which would be overridden by setting the property on the relation. *
    *
  • Map.key = context Name
  • *
  • Map.value = context of the value
  • *
*/ - private Map getPropertyOverviewForConsumedRelation(int relationId, ResourceEditProperty property, List relevantContexts) { + private Map getPropertyOverviewForConsumedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { return Collections.EMPTY_MAP; } List relevantContextIds = buildRelevantContextIdsList(relevantContexts); - Query query = queries.getPropertyOverviewForConsumedRelatedResourceQuery(property.getTechnicalKey(), relationId, relevantContextIds); - return getDifferingProperties(property, query); + Query query = queries.getPropertyOverviewForConsumedRelatedResourceQuery(property.getTechnicalKey(), relation.getResRelId(), relevantContextIds); + Map differingProperties = getDifferingProperties(property, query); + // global context is relevant here + relevantContextIds.add(contextHierarchy.getContextWithParentIds(relevantContexts.get(0)).get(0)); + differingProperties.putAll(getPropertyDefinedOnResource(relation, property, relevantContextIds)); + return differingProperties; } /** * - * @param relationId + * @param relation * @param property * @param relevantContexts - * @return a Map containing all properties which override the value of its parent context. + * @return a Map containing all properties which would be overridden by setting the property on the relation. *
    *
  • Map.key = context Name
  • *
  • Map.value = context of the value
  • *
*/ - private Map getPropertyOverviewForProvidedRelation(int relationId, ResourceEditProperty property, List relevantContexts) { + private Map getPropertyOverviewForProvidedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { return Collections.EMPTY_MAP; } List relevantContextIds = buildRelevantContextIdsList(relevantContexts); - Query query = queries.getPropertyOverviewForProvidedRelatedResourceQuery(property.getTechnicalKey(), relationId, relevantContextIds); + Query query = queries.getPropertyOverviewForProvidedRelatedResourceQuery(property.getTechnicalKey(), relation.getResRelId(), relevantContextIds); + Map differingProperties = getDifferingProperties(property, query); + // global context is relevant here + relevantContextIds.add(contextHierarchy.getContextWithParentIds(relevantContexts.get(0)).get(0)); + differingProperties.putAll(getPropertyDefinedOnResource(relation, property, relevantContextIds)); + return differingProperties; + } + + private Map getPropertyDefinedOnResource(ResourceEditRelation relation, ResourceEditProperty property, List relevantContextIds) { + Query query = queries.getPropertyOverviewForResourceQuery(property.getTechnicalKey(), relation.getSlaveId(), relevantContextIds); return getDifferingProperties(property, query); } From bf42d4a49757d5de701e04719de247856bd07f5e Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Mon, 8 Jan 2018 13:22:16 +0100 Subject: [PATCH 07/13] Selective warnings for relation properties --- .../property/boundary/PropertyEditor.java | 11 +- .../control/PropertyEditingService.java | 104 +++++++++--------- .../PropertyEditDataProvider.java | 13 ++- .../resources/mobi/configOverviewPopup.xhtml | 15 ++- 4 files changed, 77 insertions(+), 66 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/boundary/PropertyEditor.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/boundary/PropertyEditor.java index 93dab9040..6ec63359f 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/boundary/PropertyEditor.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/boundary/PropertyEditor.java @@ -18,11 +18,6 @@ * along with this program. If not, see . */ -/* - * To change this license header, choose License Headers in Project Properties. To change this template file, - * choose Tools | Templates and open the template in the editor. - */ - package ch.puzzle.itc.mobiliar.business.property.boundary; import ch.puzzle.itc.mobiliar.business.environment.boundary.ContextLocator; @@ -790,15 +785,15 @@ private ResourceEditProperty findByName(String propertyName, throw new NoResultException("Could not find property " + propertyName); } - public Map getPropertyOverviewForResource(ResourceEntity resourceEntity, ResourceEditProperty property, List relevantContexts) { + public List getPropertyOverviewForResource(ResourceEntity resourceEntity, ResourceEditProperty property, List relevantContexts) { return propertyEditingService.getPropertyOverviewForResource(resourceEntity, property, relevantContexts); } - public Map getPropertyOverviewForResourceType(ResourceTypeEntity resourceTypeEntity, ResourceEditProperty property, List relevantContexts) { + public List getPropertyOverviewForResourceType(ResourceTypeEntity resourceTypeEntity, ResourceEditProperty property, List relevantContexts) { return propertyEditingService.getPropertyOverviewForResourceType(resourceTypeEntity, property, relevantContexts); } - public Map getPropertyOverviewForRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { + public List getPropertyOverviewForRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { return propertyEditingService.getPropertyOverviewForRelation(relation, property, relevantContexts); } } diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java index 80f36219b..174f0aa3d 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java @@ -18,10 +18,6 @@ * along with this program. If not, see . */ -/* - * To change this license header, choose License Headers in Project Properties. To change this template file, - * choose Tools | Templates and open the template in the editor. - */ package ch.puzzle.itc.mobiliar.business.property.control; import ch.puzzle.itc.mobiliar.business.database.control.JpaSqlResultMapper; @@ -35,7 +31,7 @@ import ch.puzzle.itc.mobiliar.business.resourcegroup.control.ResourceEditService; import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceEntity; import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceTypeEntity; -import org.apache.commons.collections.MapUtils; +import lombok.Getter; import javax.inject.Inject; import javax.persistence.Query; @@ -76,7 +72,7 @@ public class PropertyEditingService { */ public List loadPropertiesForEditResource(Integer resourceId, ResourceTypeEntity type, ContextEntity currentContext) { - Map propMap = new HashMap(); + Map propMap = new HashMap<>(); List contextList = contextHierarchy.getContextWithParentIds(currentContext); List typeList = getTypeWithParentIds(null, type); @@ -90,7 +86,7 @@ public List loadPropertiesForEditResource(Integer resource propMap.put(prop.getDescriptorId(), findChildPropAndSetParent(prop, propMap.get(prop.getDescriptorId()), contextList)); } - return new ArrayList(new TreeSet(propMap.values())); + return new ArrayList<>(new TreeSet<>(propMap.values())); } @@ -104,7 +100,7 @@ public List loadPropertiesForEditResource(Integer resource * @return a list of containers which contain the required property information */ public List loadPropertiesForEditResourceType(ResourceTypeEntity resourceType, ContextEntity currentContext) { - Map propMap = new HashMap(); + Map propMap = new HashMap<>(); List contextList = contextHierarchy.getContextWithParentIds(currentContext); List typeList = getTypeWithParentIds(null, resourceType); @@ -124,7 +120,7 @@ public List loadPropertiesForEditResourceType(ResourceType prop.setDefinedOnSuperResourceType(true); } } - return new ArrayList(new TreeSet(propMap.values())); + return new ArrayList<>(new TreeSet<>(propMap.values())); } @@ -132,7 +128,7 @@ public List loadPropertiesForEditRelation(Mode relationTyp Integer resourceRelationId, Integer relatedResourceId, ResourceTypeEntity masterResourceType, ResourceTypeEntity slaveResourceType, ContextEntity currentContext) { - Map propMap = new HashMap(); + Map propMap = new HashMap<>(); List contextList = contextHierarchy.getContextWithParentIds(currentContext); List masterResourceTypeList = getTypeWithParentIds(null, masterResourceType); List slaveResourceTypeList = getTypeWithParentIds(null, slaveResourceType); @@ -156,7 +152,7 @@ public List loadPropertiesForEditRelation(Mode relationTyp propMap.put(prop.getDescriptorId(), findChildPropAndSetParent(prop, propMap.get(prop.getDescriptorId()), contextList)); } - return new ArrayList(new TreeSet(propMap.values())); + return new ArrayList<>(new TreeSet<>(propMap.values())); } @@ -179,7 +175,7 @@ public List loadPropertiesForEditResourceTypeRelation(Reso propMap.put(prop.getDescriptorId(), findChildPropAndSetParent(prop, propMap.get(prop.getDescriptorId()), contextList)); } - return new ArrayList(new TreeSet(propMap.values())); + return new ArrayList<>(new TreeSet<>(propMap.values())); } @@ -254,7 +250,7 @@ else if(existing.isDefinedOnInstance() != candidate.isDefinedOnInstance()){ protected List getTypeWithParentIds(List result, ResourceTypeEntity type) { if (result == null) { - result = new ArrayList(); + result = new ArrayList<>(); } if (type != null) { result.add(type.getId()); @@ -276,13 +272,13 @@ protected List getTypeWithParentIds(List result, ResourceTypeE *
  • Map.value = context of the value
  • * */ - public Map getPropertyOverviewForResource(ResourceEntity resource, ResourceEditProperty property, List relevantContexts) { + public List getPropertyOverviewForResource(ResourceEntity resource, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { - return Collections.EMPTY_MAP; + return Collections.EMPTY_LIST; } List contextIds = buildRelevantContextIdsList(relevantContexts); Query query = queries.getPropertyOverviewForResourceQuery(property.getTechnicalKey(), resource.getId(), contextIds); - return getDifferingProperties(property, query); + return getDifferingProperties(property, query, Origin.INSTANCE); } /** @@ -290,22 +286,18 @@ public Map getPropertyOverviewForResource(ResourceEntity resourc * @param resourceType * @param property * @param relevantContexts - * @return a Map containing all properties which override the value of its parent context. - *
      - *
    • Map.key = context Name
    • - *
    • Map.value = context of the value
    • - *
    + * @return a List containing all properties which override the value of its parent context. */ - public Map getPropertyOverviewForResourceType(ResourceTypeEntity resourceType, ResourceEditProperty property, List relevantContexts) { + public List getPropertyOverviewForResourceType(ResourceTypeEntity resourceType, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { - return Collections.EMPTY_MAP; + return Collections.EMPTY_LIST; } List contextIds = buildRelevantContextIdsList(relevantContexts); Query query = queries.getPropertyOverviewForResourceTypeQuery(property.getTechnicalKey(), resourceType.getId(), contextIds); - return getDifferingProperties(property, query); + return getDifferingProperties(property, query, Origin.INSTANCE); } - public Map getPropertyOverviewForRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { + public List getPropertyOverviewForRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { switch (relation.getMode()) { case CONSUMED: return getPropertyOverviewForConsumedRelation(relation, property, relevantContexts); @@ -316,7 +308,7 @@ public Map getPropertyOverviewForRelation(ResourceEditRelation re relation.getMode().name(), property.getPropertyId()); log.warning(msg); - return MapUtils.EMPTY_MAP; + return Collections.EMPTY_LIST; } } /** @@ -324,22 +316,18 @@ public Map getPropertyOverviewForRelation(ResourceEditRelation re * @param relation * @param property * @param relevantContexts - * @return a Map containing all properties which would be overridden by setting the property on the relation. - *
      - *
    • Map.key = context Name
    • - *
    • Map.value = context of the value
    • - *
    + * @return a List containing all properties which would be overridden by setting the property on the relation. */ - private Map getPropertyOverviewForConsumedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { + private List getPropertyOverviewForConsumedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { - return Collections.EMPTY_MAP; + return Collections.EMPTY_LIST; } List relevantContextIds = buildRelevantContextIdsList(relevantContexts); Query query = queries.getPropertyOverviewForConsumedRelatedResourceQuery(property.getTechnicalKey(), relation.getResRelId(), relevantContextIds); - Map differingProperties = getDifferingProperties(property, query); - // global context is relevant here + List differingProperties = getDifferingProperties(property, query, Origin.RELATION); + // obtain property values defined on the (slave) resource, which would be overwritten by defining one on the relation - global context is relevant here relevantContextIds.add(contextHierarchy.getContextWithParentIds(relevantContexts.get(0)).get(0)); - differingProperties.putAll(getPropertyDefinedOnResource(relation, property, relevantContextIds)); + differingProperties.addAll(getPropertyDefinedOnResource(relation, property, relevantContextIds, Origin.INSTANCE)); return differingProperties; } @@ -348,36 +336,32 @@ private Map getPropertyOverviewForConsumedRelation(ResourceEditR * @param relation * @param property * @param relevantContexts - * @return a Map containing all properties which would be overridden by setting the property on the relation. - *
      - *
    • Map.key = context Name
    • - *
    • Map.value = context of the value
    • - *
    + * @return a List containing all properties which would be overridden by setting the property on the relation. */ - private Map getPropertyOverviewForProvidedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { + private List getPropertyOverviewForProvidedRelation(ResourceEditRelation relation, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { - return Collections.EMPTY_MAP; + return Collections.EMPTY_LIST; } List relevantContextIds = buildRelevantContextIdsList(relevantContexts); Query query = queries.getPropertyOverviewForProvidedRelatedResourceQuery(property.getTechnicalKey(), relation.getResRelId(), relevantContextIds); - Map differingProperties = getDifferingProperties(property, query); - // global context is relevant here + List differingProperties = getDifferingProperties(property, query, Origin.RELATION); + // obtain property values defined on the (slave) resource, which would be overwritten by defining one on the relation - global context is relevant here relevantContextIds.add(contextHierarchy.getContextWithParentIds(relevantContexts.get(0)).get(0)); - differingProperties.putAll(getPropertyDefinedOnResource(relation, property, relevantContextIds)); + differingProperties.addAll(getPropertyDefinedOnResource(relation, property, relevantContextIds, Origin.INSTANCE)); return differingProperties; } - private Map getPropertyDefinedOnResource(ResourceEditRelation relation, ResourceEditProperty property, List relevantContextIds) { + private List getPropertyDefinedOnResource(ResourceEditRelation relation, ResourceEditProperty property, List relevantContextIds, Origin origin) { Query query = queries.getPropertyOverviewForResourceQuery(property.getTechnicalKey(), relation.getSlaveId(), relevantContextIds); - return getDifferingProperties(property, query); + return getDifferingProperties(property, query, origin); } - private Map getDifferingProperties(ResourceEditProperty property, Query query) { - HashMap differingProps = new HashMap<>(); + private List getDifferingProperties(ResourceEditProperty property, Query query, Origin origin) { + List differingProps = new ArrayList<>(); List resultList = query.getResultList(); for (Object o : resultList) { Map.Entry entry = createEntryForOverridenProperty(o, property.getPropertyId()); - differingProps.put(entry.getKey(), entry.getValue()); + differingProps.add(new DifferingProperty(origin, entry.getKey(), entry.getValue())); } return differingProps; } @@ -412,4 +396,22 @@ private Map.Entry createEntryForOverridenProperty(Object resultS } return new AbstractMap.SimpleEntry(contextName, valueForContext); } + + @Getter + public class DifferingProperty { + private Origin origin; + private String env; + private String val; + + /** + * @param origin Origin where the Property value is set (Instance / Relation) + * @param env String identifying the environment (ContextEntity.name) + * @param val String the Property value on that environment + */ + public DifferingProperty(Origin origin, String env, String val) { + this.origin = origin; + this.env = env; + this.val = val; + } + } } diff --git a/AMW_web/src/main/java/ch/puzzle/itc/mobiliar/presentation/propertyEdit/PropertyEditDataProvider.java b/AMW_web/src/main/java/ch/puzzle/itc/mobiliar/presentation/propertyEdit/PropertyEditDataProvider.java index 363c87c00..4048ea8bb 100644 --- a/AMW_web/src/main/java/ch/puzzle/itc/mobiliar/presentation/propertyEdit/PropertyEditDataProvider.java +++ b/AMW_web/src/main/java/ch/puzzle/itc/mobiliar/presentation/propertyEdit/PropertyEditDataProvider.java @@ -26,6 +26,7 @@ import ch.puzzle.itc.mobiliar.business.foreignable.entity.ForeignableOwnerViolationException; import ch.puzzle.itc.mobiliar.business.generator.control.extracted.templates.AppServerRelationsTemplateProcessor; import ch.puzzle.itc.mobiliar.business.property.boundary.PropertyEditor; +import ch.puzzle.itc.mobiliar.business.property.control.PropertyEditingService; import ch.puzzle.itc.mobiliar.business.property.entity.ResourceEditProperty; import ch.puzzle.itc.mobiliar.business.property.entity.ResourceEditRelation; import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.NamedIdentifiable; @@ -95,9 +96,8 @@ public class PropertyEditDataProvider implements Serializable { List filteredRelationProperties; - // Env, value @Getter - Map valuesForConfigOverview; + List valuesForConfigOverview; @Getter ResourceEditProperty propertyForConfigOverview; @@ -204,7 +204,14 @@ public void loadConfigOverviewForProperty(ResourceEditProperty property) { showWarningForPotentialPropertyOverwriting = false; } else if (property.getLoadedFor() == ResourceEditProperty.Origin.RELATION) { valuesForConfigOverview = editor.getPropertyOverviewForRelation(currentRelation, property, relevantContexts); - showWarningForPotentialPropertyOverwriting = true; + showWarningForPotentialPropertyOverwriting = false; + for (PropertyEditingService.DifferingProperty differingProperty : valuesForConfigOverview) { + // only show warning if Properties defined directly on the Resource would be overwritten + if (differingProperty.getOrigin() == ResourceEditProperty.Origin.INSTANCE) { + showWarningForPotentialPropertyOverwriting = true; + break; + } + } } } diff --git a/AMW_web/src/main/webapp/resources/mobi/configOverviewPopup.xhtml b/AMW_web/src/main/webapp/resources/mobi/configOverviewPopup.xhtml index 3d2723b38..538f1cdb7 100644 --- a/AMW_web/src/main/webapp/resources/mobi/configOverviewPopup.xhtml +++ b/AMW_web/src/main/webapp/resources/mobi/configOverviewPopup.xhtml @@ -33,13 +33,13 @@

    WARNING!



    - By changing the value of this property you will override the value of the following environments. + Changing this property will override the values defined on the resource (instance).
    - Environment - #{entry.key} + #{entry.env} + + + + + Origin + + #{entry.origin} Value - #{entry.value} + #{entry.val} From f9e9ccd2b224c3e35b0dfc83cba0d2bef567164c Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Mon, 8 Jan 2018 14:35:03 +0100 Subject: [PATCH 08/13] Prevent creation of restricted global permissions --- .../security/boundary/PermissionBoundary.java | 9 +- .../boundary/PermissionBoundaryTest.java | 176 +++++++++++------- 2 files changed, 118 insertions(+), 67 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index a195572dc..9fa76a0d3 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -746,7 +746,7 @@ public List getAllCallerRestrictions() { return permissionService.getAllCallerRestrictions(); } - private void validateRestriction(String roleName, String userName, String permissionName, Integer resourceGroupId, String resourceTypeName, + protected void validateRestriction(String roleName, String userName, String permissionName, Integer resourceGroupId, String resourceTypeName, ResourceTypePermission resourceTypePermission, String contextName, Action action, RestrictionEntity restriction) throws AMWException { if (roleName == null && userName == null) { @@ -783,6 +783,13 @@ private void validateRestriction(String roleName, String userName, String permis throw new AMWException("Permission " + permissionName + " not found."); } restriction.setPermission(permission); + if (Permission.valueOf(permission.getValue()).isOld()) { + resourceTypePermission = null; + resourceGroupId = null; + resourceTypeName = null; + contextName = null; + action = null; + } } else { throw new AMWException("Missing PermissionName"); } diff --git a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java index 9e42fd535..bf6a7c765 100644 --- a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java +++ b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java @@ -50,7 +50,10 @@ import static ch.puzzle.itc.mobiliar.business.security.entity.Action.*; import static ch.puzzle.itc.mobiliar.business.security.entity.ResourceTypePermission.*; import static junit.framework.TestCase.assertTrue; +import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @@ -77,6 +80,8 @@ public class PermissionBoundaryTest { @Mock EntityManager entityManager; + private PermissionEntity resourcePermission; + @Before public void setup() { permissionBoundary = new PermissionBoundary(); @@ -98,6 +103,8 @@ public void setup() { permissionBoundary.permissionService = permissionService; entityManager = Mockito.mock(EntityManager.class); permissionBoundary.entityManager = entityManager; + resourcePermission = new PermissionEntity(); + resourcePermission.setValue("RESOURCE"); } @Test(expected=AMWException.class) @@ -127,11 +134,11 @@ public void shouldCreateRoleOnUpdateIfRoleCanNotBeFound() throws AMWException { // given when(restrictionRepository.find(1)).thenReturn(new RestrictionEntity()); when(permissionRepository.getRoleByName("newRole")).thenReturn(null); - when(permissionRepository.getPermissionByName("valid")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("valid")).thenReturn(resourcePermission); // when permissionBoundary.updateRestriction(1, "newRole", null, "valid", null, null, null, null, null); // then - verify(permissionRepository, times(1)).createRole("newRole"); + verify(permissionRepository).createRole("newRole"); } @Test(expected=AMWException.class) @@ -158,7 +165,7 @@ public void shouldThrowAMWExceptionOnUpdateIfContextCanNotBeFound() throws AMWEx // given when(restrictionRepository.find(1)).thenReturn(new RestrictionEntity()); when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); when(contextLocator.getContextByName("bad")).thenThrow(new NoResultException()); // when // then permissionBoundary.updateRestriction(1, "existing", null, "good", null, null, null, "bad", null); @@ -169,7 +176,7 @@ public void shouldThrowAMWExceptionOnUpdateIfResourceTypeCanNotBeFound() throws // given when(restrictionRepository.find(1)).thenReturn(new RestrictionEntity()); when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); when(resourceTypeRepository.getByName("bad")).thenReturn(null); // when // then permissionBoundary.updateRestriction(1, "existing", null, "good", null, "bad", null, null, null); @@ -180,12 +187,12 @@ public void shouldUpdateIfContextAndActionAreNull() throws AMWException { // given when(restrictionRepository.find(1)).thenReturn(new RestrictionEntity()); when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when permissionBoundary.updateRestriction(1, "existing", null, "good", null, null, null, null, null); // then - verify(restrictionRepository, times(1)).merge(any(RestrictionEntity.class)); - verify(permissionRepository, times(1)).forceReloadingOfLists(); + verify(restrictionRepository).merge(any(RestrictionEntity.class)); + verify(permissionRepository).forceReloadingOfLists(); } @Test(expected=AMWException.class) @@ -210,59 +217,59 @@ public void shouldThrowAMWExceptionOnCreateIfTrimmedUserNameIsEmpty() throws AMW public void shouldCreateRoleAndUserRestrictionOnCreateIfRoleCanNotBeFound() throws AMWException { // given when(permissionRepository.getRoleByName("newRole")).thenReturn(null); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when permissionBoundary.createRestriction("newRole", null, "good", null, null, null, null, null, false); // then - verify(permissionRepository, times(1)).createRole("newRole"); - verify(restrictionRepository, times(1)).create(any(RestrictionEntity.class)); + verify(permissionRepository).createRole("newRole"); + verify(restrictionRepository).create(any(RestrictionEntity.class)); } @Test public void shouldCreateUserRestrictionAndRestrictionIfUserNameIsNotNull() throws AMWException { // given - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when permissionBoundary.createRestriction(null, "hans", "good", null, null, null, null, null, false); // then - verify(permissionRepository, times(1)).getUserRestrictionByName("hans"); - verify(permissionRepository, times(1)).createUserRestriciton("hans"); - verify(restrictionRepository, times(1)).create(any(RestrictionEntity.class)); + verify(permissionRepository).getUserRestrictionByName("hans"); + verify(permissionRepository).createUserRestriciton("hans"); + verify(restrictionRepository).create(any(RestrictionEntity.class)); } @Test public void shouldAssignUserRestrictionAndCreateRestrictionIfUserNameHasBeenFound() throws AMWException { // given - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); when(permissionRepository.getUserRestrictionByName("fritz")).thenReturn(new UserRestrictionEntity()); // when permissionBoundary.createRestriction(null, "fritz", "good", null, null, null, null, null, false); // then verify(permissionRepository, never()).createUserRestriciton(anyString()); - verify(restrictionRepository, times(1)).create(any(RestrictionEntity.class)); + verify(restrictionRepository).create(any(RestrictionEntity.class)); } @Test public void shouldCreateIfContextIsNull() throws AMWException { // given when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when permissionBoundary.createRestriction("existing", null, "good", null, null, null, null, CREATE, false); // then - verify(restrictionRepository, times(1)).create(any(RestrictionEntity.class)); + verify(restrictionRepository).create(any(RestrictionEntity.class)); } @Test public void shouldCreateIfContextAndActionAreNull() throws AMWException { // given when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when permissionBoundary.createRestriction("existing", null, "good", null, null, null, null, null, false); // then - verify(restrictionRepository, times(1)).create(any(RestrictionEntity.class)); - verify(permissionRepository, times(1)).forceReloadingOfLists(); + verify(restrictionRepository).create(any(RestrictionEntity.class)); + verify(permissionRepository).forceReloadingOfLists(); } @Test @@ -270,12 +277,12 @@ public void shouldCheckIfCallerHasSimilarRestrictionIfHeWantsToDelegatePermissio // given when(permissionService.hasPermissionToDelegatePermission(Permission.SHAKEDOWNTEST, null, null, null, CREATE)).thenReturn(true); when(permissionRepository.getUserRestrictionByName("fed")).thenReturn(new UserRestrictionEntity()); - when(permissionRepository.getPermissionByName(anyString())).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName(anyString())).thenReturn(resourcePermission); // when permissionBoundary.createRestriction(null, "fred", "SHAKEDOWNTEST", null, null, null, null, CREATE, true); // then - verify(permissionService, times(1)).hasPermissionToDelegatePermission(Permission.SHAKEDOWNTEST, null, null, null, CREATE); - verify(restrictionRepository, times(1)).create(any(RestrictionEntity.class)); + verify(permissionService).hasPermissionToDelegatePermission(Permission.SHAKEDOWNTEST, null, null, null, CREATE); + verify(restrictionRepository).create(any(RestrictionEntity.class)); } @Test(expected=AMWException.class) @@ -286,7 +293,7 @@ public void shouldThrowAMWExceptionIfCallerIsNotAllowedToDelegatePermission() th // when permissionBoundary.createRestriction(null, "fred", "SHAKEDOWNTEST", null, null, null, null, CREATE, true); // then - verify(permissionService, times(1)).hasPermissionToDelegatePermission(Permission.SHAKEDOWNTEST, null, null, null, CREATE); + verify(permissionService).hasPermissionToDelegatePermission(Permission.SHAKEDOWNTEST, null, null, null, CREATE); verify(restrictionRepository, never()).create(any(RestrictionEntity.class)); } @@ -294,7 +301,7 @@ public void shouldThrowAMWExceptionIfCallerIsNotAllowedToDelegatePermission() th public void shouldThrowAMWExceptionOnCreateIfResourceIdCanNotBeFound() throws AMWException { // given when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); when(resourceGroupRepository.find(7)).thenReturn(null); // when // then permissionBoundary.createRestriction("existing", null, "good", 7, null, null, null, null, false); @@ -304,7 +311,7 @@ public void shouldThrowAMWExceptionOnCreateIfResourceIdCanNotBeFound() throws AM public void shouldThrowAMWExceptionOnCreateIfResourceGroupAndResourceTypeAreSet() throws AMWException { // given when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when // then permissionBoundary.createRestriction("existing", null, "good", 7, "bad", null, null, null, false); } @@ -313,7 +320,7 @@ public void shouldThrowAMWExceptionOnCreateIfResourceGroupAndResourceTypeAreSet( public void shouldThrowAMWExceptionOnCreateIfResourceTypePermissionIsNotEmptyAndResourceGroupIsSet() throws AMWException { // given when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when // then permissionBoundary.createRestriction("existing", null, "good", 7, null, DEFAULT_ONLY, null, null, false); } @@ -322,11 +329,48 @@ public void shouldThrowAMWExceptionOnCreateIfResourceTypePermissionIsNotEmptyAnd public void shouldThrowAMWExceptionOnCreateIfResourceTypePermissionIsNotEmptyAndResourceTypeIsSet() throws AMWException { // given when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); - when(permissionRepository.getPermissionByName("good")).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); // when // then permissionBoundary.createRestriction("existing", null, "good", null, "bad", NON_DEFAULT_ONLY, null, null, false); } + @Test + public void shouldPreserveRestrictionPropertiesIfPermissionIsNotOld() throws AMWException { + // given + ContextEntity envX = new ContextEntity(); + envX.setName("X"); + RestrictionEntity restriction = new RestrictionEntity(); + when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(resourcePermission); + when(contextLocator.getContextByName("X")).thenReturn(envX); + // when + permissionBoundary.validateRestriction("existing", null, "good", null, null, ResourceTypePermission.NON_DEFAULT_ONLY, "X", CREATE, restriction); + // then + assertThat(restriction.getResourceTypePermission(), is(ResourceTypePermission.NON_DEFAULT_ONLY)); + assertThat(restriction.getAction(), is(CREATE)); + assertThat(restriction.getContext(), is(envX)); + assertNull(restriction.getResourceGroup()); + assertNull(restriction.getResourceType()); + } + + @Test + public void shouldResetRestrictionPropertiesIfPermissionIsOld() throws AMWException { + // given + PermissionEntity globalPerm = new PermissionEntity(); + globalPerm.setValue("APP_TAB"); + RestrictionEntity restriction = new RestrictionEntity(); + when(permissionRepository.getRoleByName("existing")).thenReturn(new RoleEntity()); + when(permissionRepository.getPermissionByName("good")).thenReturn(globalPerm); + // when + permissionBoundary.validateRestriction("existing", null, "good", 1, null, ResourceTypePermission.NON_DEFAULT_ONLY, "X", CREATE, restriction); + // then + assertThat(restriction.getResourceTypePermission(), is(ResourceTypePermission.ANY)); + assertThat(restriction.getAction(), is(ALL)); + assertNull(restriction.getContext()); + assertNull(restriction.getResourceGroup()); + assertNull(restriction.getResourceType()); + } + @Test(expected=AMWException.class) public void shouldThrowAMWExceptionIfRestrictionToBeDeletedCanNotBeFound() throws AMWException { // given // when // then @@ -340,8 +384,8 @@ public void shouldRemoveRestrictionToBeDeleted() throws AMWException { // when permissionBoundary.removeRestriction(42); // then - verify(restrictionRepository, times(1)).deleteRestrictionById(42); - verify(permissionRepository, times(1)).forceReloadingOfLists(); + verify(restrictionRepository).deleteRestrictionById(42); + verify(permissionRepository).forceReloadingOfLists(); } @Test @@ -351,7 +395,7 @@ public void shouldInvokePermissionServiceIfPermissionHasBeenFound() { // when boolean result = permissionBoundary.hasPermission("RESOURCE"); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE); + verify(permissionService).hasPermission(Permission.RESOURCE); assertTrue(result); } @@ -362,7 +406,7 @@ public void shouldDelegatePermissionCheckToPermissionService() { // when boolean result = permissionBoundary.hasPermission(Permission.RESOURCE); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE); + verify(permissionService).hasPermission(Permission.RESOURCE); assertTrue(result); } @@ -373,7 +417,7 @@ public void shouldInvokePermissionServiceIfPermissionAndActionHaveBeenFound() { // when boolean result = permissionBoundary.hasPermission("RESOURCE", "READ"); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, READ); + verify(permissionService).hasPermission(Permission.RESOURCE, READ); assertTrue(result); } @@ -384,7 +428,7 @@ public void shouldDelegatePermissionAndActionCheckToPermissionService() { // when boolean result = permissionBoundary.hasPermission(Permission.RESOURCE, READ); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, READ); + verify(permissionService).hasPermission(Permission.RESOURCE, READ); assertTrue(result); } @@ -413,7 +457,7 @@ public void shouldInvokeResourceTypeRepository() { // given // when permissionBoundary.hasPermissionForResourceType("RESOURCE", "CREATE", "APP"); // then - verify(resourceTypeRepository, times(1)).getByName("APP"); + verify(resourceTypeRepository).getByName("APP"); } @Test @@ -425,8 +469,8 @@ public void shouldInvokePermissionServiceIfResourceTypeHasBeenFound() { // when boolean result = permissionBoundary.hasPermissionForResourceType("RESOURCE", "CREATE", "APP"); // then - verify(resourceTypeRepository, times(1)).getByName("APP"); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, CREATE, resType); + verify(resourceTypeRepository).getByName("APP"); + verify(permissionService).hasPermission(Permission.RESOURCE, CREATE, resType); assertTrue(result); } @@ -441,8 +485,8 @@ public void shouldInvokePermissionServiceIfResourceTypeAndContextHaveBeenFound() // when boolean result = permissionBoundary.hasPermissionForResourceType("RESOURCE", "CREATE", "APP", 1); // then - verify(resourceTypeRepository, times(1)).getByName("APP"); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, context, CREATE, null, resType); + verify(resourceTypeRepository).getByName("APP"); + verify(permissionService).hasPermission(Permission.RESOURCE, context, CREATE, null, resType); assertTrue(result); } @@ -459,7 +503,7 @@ public void shouldInvokePermissionServiceWithAllParams() { // when boolean result = permissionBoundary.hasPermission(Permission.RESOURCE, context, CREATE, resource, type); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, context, CREATE, rg, type); + verify(permissionService).hasPermission(Permission.RESOURCE, context, CREATE, rg, type); assertTrue(result); } @@ -470,7 +514,7 @@ public void shouldInvokeTheRightMethodOnPermissionServiceToCheckIfHasPermissionT // when permissionBoundary.hasPermissionToRemoveInstanceOfResType(resType); // then - verify(permissionService, times(1)).hasPermissionToRemoveInstanceOfResType(resType); + verify(permissionService).hasPermissionToRemoveInstanceOfResType(resType); } @Test @@ -485,7 +529,7 @@ public void shouldInvokePermissionServiceWithCorrectParametersOnCanCopyFromResou // when permissionBoundary.canCopyFromResource(resource); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); + verify(permissionService).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); } @Test @@ -504,8 +548,8 @@ public void shouldInvokePermissionServiceWithCorrectParametersOnCanCopyFromSpeci when(permissionService.hasPermission(Permission.RESOURCE, null, READ, org, type)).thenReturn(false); // when boolean can = permissionBoundary.canCopyFromSpecificResource(resource, org); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, null, READ, org, type); + verify(permissionService).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); + verify(permissionService).hasPermission(Permission.RESOURCE, null, READ, org, type); assertFalse(can); } @@ -525,7 +569,7 @@ public void shouldInvokePermissionServiceWithCorrectParametersOnCanCopyFromSpeci when(permissionService.hasPermission(Permission.RESOURCE, null, READ, org, type)).thenReturn(true); // when boolean can = permissionBoundary.canCopyFromSpecificResource(resource, org); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); + verify(permissionService).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); verify(permissionService, never()).hasPermission(Permission.RESOURCE, null, READ, org, type); assertFalse(can); } @@ -546,8 +590,8 @@ public void shouldInvokePermissionServiceWithCorrectParametersOnCanCopyFromSpeci when(permissionService.hasPermission(Permission.RESOURCE, null, READ, org, type)).thenReturn(true); // when boolean can = permissionBoundary.canCopyFromSpecificResource(resource, org); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, null, READ, org, type); + verify(permissionService).hasPermission(Permission.RESOURCE_RELEASE_COPY_FROM_RESOURCE, null, ALL, rg, type); + verify(permissionService).hasPermission(Permission.RESOURCE, null, READ, org, type); assertTrue(can); } @@ -558,7 +602,7 @@ public void shouldInvokeTheRightMethodOnPermissionServiceToCheckIfCanCreateResou // when permissionBoundary.canCreateResourceInstance(resType); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, CREATE, resType); + verify(permissionService).hasPermission(Permission.RESOURCE, CREATE, resType); } @Test @@ -574,8 +618,8 @@ public void shouldInvokeTheRightMethodsOnPermissionServiceToCheckIfCanCreateAppA // when permissionBoundary.canCreateAppAndAddToAppServer(resource); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, CREATE, type); - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, UPDATE, asType); + verify(permissionService).hasPermission(Permission.RESOURCE, CREATE, type); + verify(permissionService).hasPermission(Permission.RESOURCE, UPDATE, asType); } @Test @@ -583,7 +627,7 @@ public void shouldObtainListOfPermissionsFromPermissionService() { // given // when permissionBoundary.getAllPermissions(); // then - verify(permissionService, times(1)).getPermissions(); + verify(permissionService).getPermissions(); } @Test @@ -597,7 +641,7 @@ public void shouldInvokePermissionServiceMethodsWithCorrectParametersForResource // when permissionBoundary.hasPermissionToEditPropertiesByResourceTypeAndContext(21, 23, false); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCETYPE, context, UPDATE, null, type); + verify(permissionService).hasPermission(Permission.RESOURCETYPE, context, UPDATE, null, type); verify(permissionService, never()).hasPermission(Permission.SHAKEDOWN_TEST_MODE); } @@ -616,7 +660,7 @@ public void shouldInvokePermissionServiceMethodWithCorrectParametersForResource( // when permissionBoundary.hasPermissionToEditPropertiesByResourceAndContext(21, context, false); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE, context, UPDATE, rg, null); + verify(permissionService).hasPermission(Permission.RESOURCE, context, UPDATE, rg, null); verify(permissionService, never()).hasPermission(Permission.SHAKEDOWN_TEST_MODE); } @@ -627,7 +671,7 @@ public void shouldInvokePermissionServiceMethodsWithCorrectParametersIfInTesting // then verify(permissionService, never()).hasPermission(any(Permission.class), any(ContextEntity.class), any(Action.class), any(ResourceGroupEntity.class), any(ResourceTypeEntity.class)); - verify(permissionService, times(1)).hasPermission(Permission.SHAKEDOWN_TEST_MODE); + verify(permissionService).hasPermission(Permission.SHAKEDOWN_TEST_MODE); } @Test @@ -635,7 +679,7 @@ public void shouldDelegateCheckPermissionAndFireExceptionToPermissionServiceWith // given // when permissionBoundary.checkPermissionAndFireException(Permission.RESOURCE, "Message"); // then - verify(permissionService, times(1)).checkPermissionAndFireException(Permission.RESOURCE, "Message"); + verify(permissionService).checkPermissionAndFireException(Permission.RESOURCE, "Message"); } @Test @@ -643,7 +687,7 @@ public void shouldDelegateCheckPermissionAndFireExceptionToPermissionServiceWith // given // when permissionBoundary.checkPermissionAndFireException(Permission.RESOURCE, Action.READ, "Message"); // then - verify(permissionService, times(1)).checkPermissionAndFireException(Permission.RESOURCE, Action.READ, "Message"); + verify(permissionService).checkPermissionAndFireException(Permission.RESOURCE, Action.READ, "Message"); } @Test @@ -656,7 +700,7 @@ public void shouldDelegateHasPermissionToAddRelationToPermissionService() { // when permissionBoundary.hasPermissionToAddRelation(resource, aContext); // then - verify(permissionService, times(1)).hasPermissionToAddRelation(resource, aContext); + verify(permissionService).hasPermissionToAddRelation(resource, aContext); } @Test @@ -669,7 +713,7 @@ public void shouldInvokeTheRightMethodOfPermissionServiceToAskForResourceTemplat permissionBoundary.hasPermissionToAddTemplate(resource, false); // then verify(permissionService, never()).hasPermissionToAddResourceTypeTemplate((ResourceTypeEntity) anyObject(), anyBoolean()); - verify(permissionService, times(1)).hasPermissionToAddResourceTemplate(resource, false); + verify(permissionService).hasPermissionToAddResourceTemplate(resource, false); } @Test @@ -682,7 +726,7 @@ public void shouldInvokeTheRightMethodOfPermissionServiceToAskForResourceTypeTem permissionBoundary.hasPermissionToAddTemplate(type, true); // then verify(permissionService, never()).hasPermissionToAddResourceTemplate((ResourceEntity) anyObject(), anyBoolean()); - verify(permissionService, times(1)).hasPermissionToAddResourceTypeTemplate(type, true); + verify(permissionService).hasPermissionToAddResourceTypeTemplate(type, true); } @Test @@ -694,7 +738,7 @@ public void shouldInvokePermissionServiceWithRightParametersToAskForResourceType // when permissionBoundary.canUpdateFunctionOfResourceOrResourceType(null, type.getId()); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCETYPE_AMWFUNCTION, null, UPDATE, null, type); + verify(permissionService).hasPermission(Permission.RESOURCETYPE_AMWFUNCTION, null, UPDATE, null, type); } @Test @@ -706,7 +750,7 @@ public void shouldInvokePermissionServiceWithRightParametersToAskForResourceType // when permissionBoundary.canUpdateFunctionOfResourceOrResourceType(null, type.getId()); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCETYPE_AMWFUNCTION, null, UPDATE, null, type); + verify(permissionService).hasPermission(Permission.RESOURCETYPE_AMWFUNCTION, null, UPDATE, null, type); } @Test @@ -720,7 +764,7 @@ public void shouldInvokePermissionServiceWithRightParametersToAskForResourceFunc // when permissionBoundary.canUpdateFunctionOfResourceOrResourceType(resource.getId(), null); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE_AMWFUNCTION, null, UPDATE, rg, null); + verify(permissionService).hasPermission(Permission.RESOURCE_AMWFUNCTION, null, UPDATE, rg, null); } @Test @@ -734,7 +778,7 @@ public void shouldInvokePermissionServiceWithRightParametersToAskForResourceFunc // when permissionBoundary.canUpdateFunctionOfResourceOrResourceType(resource.getId(), null); // then - verify(permissionService, times(1)).hasPermission(Permission.RESOURCE_AMWFUNCTION, null, UPDATE, rg, null); + verify(permissionService).hasPermission(Permission.RESOURCE_AMWFUNCTION, null, UPDATE, rg, null); } @Test @@ -742,7 +786,7 @@ public void shouldDelegateGetAllUserRestrictionToPermissionService() { // given // when permissionBoundary.getAllUserRestriction(); // then - verify(permissionService, times(1)).getAllUserRestrictions(); + verify(permissionService).getAllUserRestrictions(); } @Test @@ -773,7 +817,7 @@ public void shouldCreateAllSelfAssignedPermissionsIfCallerHasTheRequiredPermissi when(permissionService.getCurrentUserName()).thenReturn("tester"); when(permissionService.hasPermission(Permission.ADD_ADMIN_PERMISSIONS_ON_CREATED_RESOURCE)).thenReturn(true); when(resourceGroupRepository.find(resource.getResourceGroup().getId())).thenReturn(resource.getResourceGroup()); - when(permissionRepository.getPermissionByName(anyString())).thenReturn(new PermissionEntity()); + when(permissionRepository.getPermissionByName(anyString())).thenReturn(resourcePermission); // when permissionBoundary.createAutoAssignedRestrictions(resource); From ced30468b0d945158c8475e03990adbcd74ba681 Mon Sep 17 00:00:00 2001 From: Andy Pollari Date: Mon, 8 Jan 2018 16:48:56 +0100 Subject: [PATCH 09/13] corrected return type in javadoc --- .../business/property/control/PropertyEditingService.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java index 174f0aa3d..b17697d11 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/property/control/PropertyEditingService.java @@ -266,11 +266,7 @@ protected List getTypeWithParentIds(List result, ResourceTypeE * @param resource * @param property * @param relevantContexts - * @return a Map containing all properties which override the value of its parent context. - *
      - *
    • Map.key = context Name
    • - *
    • Map.value = context of the value
    • - *
    + * @return a List containing all properties which override the value of its parent context. */ public List getPropertyOverviewForResource(ResourceEntity resource, ResourceEditProperty property, List relevantContexts) { if (relevantContexts.isEmpty()) { From 68488b43838ff4de3774f7918b5c8971d793251e Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Mon, 8 Jan 2018 16:53:55 +0100 Subject: [PATCH 10/13] Allow simultaneous creation of role and user permissions with or without resourceType --- .../security/boundary/PermissionBoundary.java | 54 ++++++++++++++++--- .../rest/permissions/RestrictionsRest.java | 3 -- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index 9fa76a0d3..4ec5986da 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -477,7 +477,7 @@ public int createMultipleRestrictions(String roleName, List userNames, L int count = 0; for (String permissionName : permissionNames) { for (Action action : actions) { - if (userNames == null || userNames.isEmpty()) { + if (roleName != null) { if (resourceGroupIds != null && !resourceGroupIds.isEmpty()) { for (Integer resourceGroupId : resourceGroupIds) { if (contextNames == null || contextNames.isEmpty()) { @@ -497,17 +497,35 @@ public int createMultipleRestrictions(String roleName, List userNames, L } } } else { - for (String resourceTypeName : resourceTypeNames) { + if (resourceTypeNames != null && !resourceTypeNames.isEmpty()) { + for (String resourceTypeName : resourceTypeNames) { + if (contextNames == null || contextNames.isEmpty()) { + RestrictionEntity restriction = new RestrictionEntity(); + if (createRestriction(roleName, null, permissionName, null, resourceTypeName, + resourceTypePermission, null, action, restriction) != null) { + count++; + } + } else { + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + if (createRestriction(roleName, null, permissionName, null, resourceTypeName, + resourceTypePermission, contextName, action, restriction) != null) { + count++; + } + } + } + } + } else { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, null, resourceTypeName, + if (createRestriction(roleName, null, permissionName, null, null, resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, null, resourceTypeName, + if (createRestriction(roleName, null, permissionName, null, null, resourceTypePermission, contextName, action, restriction) != null) { count++; } @@ -515,7 +533,8 @@ public int createMultipleRestrictions(String roleName, List userNames, L } } } - } else { + } + if (userNames != null && !userNames.isEmpty()) { for (String userName : userNames) { if (resourceGroupIds != null && !resourceGroupIds.isEmpty()) { for (Integer resourceGroupId : resourceGroupIds) { @@ -536,22 +555,41 @@ public int createMultipleRestrictions(String roleName, List userNames, L } } } else { - for (String resourceTypeName : resourceTypeNames) { + if (resourceTypeNames != null && !resourceTypeNames.isEmpty()) { + for (String resourceTypeName : resourceTypeNames) { + if (contextNames == null || contextNames.isEmpty()) { + RestrictionEntity restriction = new RestrictionEntity(); + if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + resourceTypePermission, null, action, restriction) != null) { + count++; + } + } else { + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + resourceTypePermission, contextName, action, restriction) != null) { + count++; + } + } + } + } + } else { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + if (createRestriction(roleName, userName, permissionName, null, null, resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + if (createRestriction(roleName, userName, permissionName, null, null, resourceTypePermission, contextName, action, restriction) != null) { count++; } } } + } } } diff --git a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java index 91b9eaffa..57c16b84b 100644 --- a/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java +++ b/AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/permissions/RestrictionsRest.java @@ -106,9 +106,6 @@ public Response addRestriction(@ApiParam("Add multiple Restrictions, either a ro } catch (AMWException e) { return Response.status(BAD_REQUEST).entity(new ExceptionDto(e.getMessage())).build(); } - if (count == 0) { - return Response.status(PRECONDITION_FAILED).entity(new ExceptionDto("Similar permissions already exists")).build(); - } return Response.status(CREATED).header("X-Total-Count", count).build(); } From ca62598184b9245605e70da0b7c271c1c8d3a40f Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Mon, 8 Jan 2018 17:05:13 +0100 Subject: [PATCH 11/13] Fixed bogus similarRestriction check --- .../security/boundary/PermissionBoundary.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index 4ec5986da..a91f029c4 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -540,14 +540,14 @@ public int createMultipleRestrictions(String roleName, List userNames, L for (Integer resourceGroupId : resourceGroupIds) { if (contextNames == null ||contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, resourceGroupId, null, + if (createRestriction(null, userName, permissionName, resourceGroupId, null, resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, resourceGroupId, null, + if (createRestriction(null, userName, permissionName, resourceGroupId, null, resourceTypePermission, contextName, action, restriction) != null) { count++; } @@ -559,14 +559,14 @@ public int createMultipleRestrictions(String roleName, List userNames, L for (String resourceTypeName : resourceTypeNames) { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + if (createRestriction(null, userName, permissionName, null, resourceTypeName, resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, null, resourceTypeName, + if (createRestriction(null, userName, permissionName, null, resourceTypeName, resourceTypePermission, contextName, action, restriction) != null) { count++; } @@ -576,20 +576,19 @@ public int createMultipleRestrictions(String roleName, List userNames, L } else { if (contextNames == null || contextNames.isEmpty()) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, null, null, + if (createRestriction(null, userName, permissionName, null, null, resourceTypePermission, null, action, restriction) != null) { count++; } } else { for (String contextName : contextNames) { RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, userName, permissionName, null, null, + if (createRestriction(null, userName, permissionName, null, null, resourceTypePermission, contextName, action, restriction) != null) { count++; } } } - } } } From 9f40a948fe826e19f561f1bfeccbd19415d0c614 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Tue, 9 Jan 2018 10:33:26 +0100 Subject: [PATCH 12/13] Added tests and validation --- .../security/boundary/PermissionBoundary.java | 21 +- .../boundary/PermissionBoundaryTest.java | 212 ++++++++++++++++++ 2 files changed, 224 insertions(+), 9 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index a91f029c4..9feff65ae 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -461,20 +461,23 @@ public Integer createRestriction(String roleName, String userName, String permis /** * Creates multiple RestrctionEntites and returns how many that have been created * - * @param roleName - * @param userNames - * @param permissionNames - * @param resourceGroupIds - * @param resourceTypeNames - * @param resourceTypePermission - * @param contextNames - * @param actions - * @return + * @param roleName max one Role name + * @param userNames none or more User names + * @param permissionNames at least one Permission name + * @param resourceGroupIds none or more ResourceGroup ids + * @param resourceTypeNames none or more ResourceType names + * @param resourceTypePermission max one ResourceTypePermission + * @param contextNames none or more Context names + * @param actions at least one Action + * @return int number of created Restrictions */ @HasPermission(permission = Permission.ASSIGN_REMOVE_PERMISSION, action = Action.CREATE) public int createMultipleRestrictions(String roleName, List userNames, List permissionNames, List resourceGroupIds, List resourceTypeNames, ResourceTypePermission resourceTypePermission, List contextNames, List actions) throws AMWException { int count = 0; + if (resourceGroupIds != null && !resourceGroupIds.isEmpty() && resourceTypeNames != null && !resourceTypeNames.isEmpty()) { + throw new AMWException("Only ResourceGroupId(s) OR ResourceTypeName(s) must be set"); + } for (String permissionName : permissionNames) { for (Action action : actions) { if (roleName != null) { diff --git a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java index bf6a7c765..59df74340 100644 --- a/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java +++ b/AMW_business/src/test/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundaryTest.java @@ -47,6 +47,8 @@ import javax.persistence.NoResultException; +import java.util.Arrays; + import static ch.puzzle.itc.mobiliar.business.security.entity.Action.*; import static ch.puzzle.itc.mobiliar.business.security.entity.ResourceTypePermission.*; import static junit.framework.TestCase.assertTrue; @@ -81,6 +83,7 @@ public class PermissionBoundaryTest { EntityManager entityManager; private PermissionEntity resourcePermission; + private PermissionEntity resourceTypePermission; @Before public void setup() { @@ -105,6 +108,8 @@ public void setup() { permissionBoundary.entityManager = entityManager; resourcePermission = new PermissionEntity(); resourcePermission.setValue("RESOURCE"); + resourceTypePermission = new PermissionEntity(); + resourceTypePermission.setValue("RESOURCETYPE"); } @Test(expected=AMWException.class) @@ -827,4 +832,211 @@ public void shouldCreateAllSelfAssignedPermissionsIfCallerHasTheRequiredPermissi verify(restrictionRepository, times(8)).create(any(RestrictionEntity.class)); } + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfARoleIsGiven() throws Exception { + //given + String roleName1 = "Role1"; + String permissionName1 = "RESOURCE"; + String permissionName2 = "RESOURCETYPE"; + String contextNameA = "A"; + when(permissionRepository.getPermissionByName("RESOURCE")).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName("RESOURCETYPE")).thenReturn(resourceTypePermission); + when(resourceGroupRepository.find(1)).thenReturn(new ResourceGroupEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, null, Arrays.asList(permissionName1, permissionName2), Arrays.asList(1), null, ResourceTypePermission.ANY, Arrays.asList(contextNameA), Arrays.asList(Action.CREATE)); + + // then + assertThat(total, is(2)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAreGiven() throws Exception { + //given + String userName1 = "User1"; + String userName2 = "User2"; + String permissionName1 = "RESOURCE"; + String permissionName2 = "RESOURCETYPE"; + when(permissionRepository.getPermissionByName("RESOURCE")).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName("RESOURCETYPE")).thenReturn(resourceTypePermission); + when(resourceGroupRepository.find(1)).thenReturn(new ResourceGroupEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(null, Arrays.asList(userName1, userName2), Arrays.asList(permissionName1, permissionName2), Arrays.asList(1), null, ResourceTypePermission.ANY, null, Arrays.asList(Action.CREATE)); + + // then + assertThat(total, is(4)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + String permissionName1 = "RESOURCE"; + String permissionName2 = "RESOURCETYPE"; + String contextNameA = "A"; + when(permissionRepository.getPermissionByName("RESOURCE")).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName("RESOURCETYPE")).thenReturn(resourceTypePermission); + when(resourceGroupRepository.find(1)).thenReturn(new ResourceGroupEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(permissionName1, permissionName2), Arrays.asList(1), null, ResourceTypePermission.ANY, Arrays.asList(contextNameA), Arrays.asList(Action.CREATE)); + + // then + assertThat(total, is(6)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + when(resourceGroupRepository.find(1)).thenReturn(new ResourceGroupEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), Arrays.asList(1), null, ResourceTypePermission.ANY, null, Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(12)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAndTwoContextsAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + String contextNameA = "A"; + String contextNameB = "B"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + when(resourceGroupRepository.find(1)).thenReturn(new ResourceGroupEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), Arrays.asList(1), null, ResourceTypePermission.ANY, Arrays.asList(contextNameA, contextNameB), Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(24)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAndTwoContextsAndTwoResourceGroupsAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + String contextNameA = "A"; + String contextNameB = "B"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + when(resourceGroupRepository.find(anyInt())).thenReturn(new ResourceGroupEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), Arrays.asList(1, 2), null, ResourceTypePermission.ANY, Arrays.asList(contextNameA, contextNameB), Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(48)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAndTwoContextsAndTwoResourceTypesAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + String resourceTypeName1 = "APPLICATION"; + String resourceTypeName2 = "APPSERVER"; + String contextNameA = "A"; + String contextNameB = "B"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + when(resourceTypeRepository.getByName(anyString())).thenReturn(new ResourceTypeEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), null, Arrays.asList(resourceTypeName1, resourceTypeName2), ResourceTypePermission.ANY, Arrays.asList(contextNameA, contextNameB), Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(48)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAndTwoResourceTypesAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + String resourceTypeName1 = "APPLICATION"; + String resourceTypeName2 = "APPSERVER"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + when(resourceTypeRepository.getByName(anyString())).thenReturn(new ResourceTypeEntity()); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), null, Arrays.asList(resourceTypeName1, resourceTypeName2), ResourceTypePermission.ANY, null, Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(24)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAndTwoContextsAreButNoResourceGroupsOrResourceTypesAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + String contextNameA = "A"; + String contextNameB = "B"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), null, null, ResourceTypePermission.ANY, Arrays.asList(contextNameA, contextNameB), Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(24)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test + public void shouldCreateTheRightAmountOfRestrictionsIfUsersAndRoleAndTwoActionsAreButNoResourceGroupsOrResourceTypesAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String userName1 = "User1"; + String userName2 = "User2"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(permissionRepository.getPermissionByName(resourceTypePermission.getValue())).thenReturn(resourceTypePermission); + + // when + int total = permissionBoundary.createMultipleRestrictions(roleName1, Arrays.asList(userName1, userName2), Arrays.asList(resourcePermission.getValue(), resourceTypePermission.getValue()), null, null, ResourceTypePermission.ANY, null, Arrays.asList(Action.CREATE, Action.UPDATE)); + + // then + assertThat(total, is(12)); + verify(restrictionRepository, times(total)).create(any(RestrictionEntity.class)); + } + + @Test(expected=AMWException.class) + public void shouldThrowAnExceptionIfBothResourceTypeAndResourceGroupAreGiven() throws Exception { + //given + String roleName1 = "Role1"; + String resourceTypeName1 = "APPLICATION"; + when(permissionRepository.getPermissionByName(resourcePermission.getValue())).thenReturn(resourcePermission); + when(resourceTypeRepository.getByName(anyString())).thenReturn(new ResourceTypeEntity()); + + // when // then + permissionBoundary.createMultipleRestrictions(roleName1, null, Arrays.asList(resourcePermission.getValue()), Arrays.asList(1), Arrays.asList(resourceTypeName1), ResourceTypePermission.ANY, null, Arrays.asList(Action.CREATE, Action.UPDATE)); + } + } From a7952d55abf4987c33edeb2d9828679b9e7a6952 Mon Sep 17 00:00:00 2001 From: Reto Galante Date: Wed, 10 Jan 2018 11:05:45 +0100 Subject: [PATCH 13/13] Reduced cyclomatic complexity --- .../security/boundary/PermissionBoundary.java | 148 +++++------------- 1 file changed, 41 insertions(+), 107 deletions(-) diff --git a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java index 9feff65ae..771807bfe 100644 --- a/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java +++ b/AMW_business/src/main/java/ch/puzzle/itc/mobiliar/business/security/boundary/PermissionBoundary.java @@ -478,121 +478,43 @@ public int createMultipleRestrictions(String roleName, List userNames, L if (resourceGroupIds != null && !resourceGroupIds.isEmpty() && resourceTypeNames != null && !resourceTypeNames.isEmpty()) { throw new AMWException("Only ResourceGroupId(s) OR ResourceTypeName(s) must be set"); } + if (userNames == null) { + userNames = new ArrayList(); + } + if (resourceGroupIds == null) { + resourceGroupIds = new ArrayList(); + } + if (resourceTypeNames == null) { + resourceTypeNames = new ArrayList(); + } + if (contextNames == null || contextNames.isEmpty()) { + contextNames = new ArrayList(); + contextNames.add(null); + } + for (String permissionName : permissionNames) { for (Action action : actions) { if (roleName != null) { - if (resourceGroupIds != null && !resourceGroupIds.isEmpty()) { + if (resourceGroupIds.isEmpty() && resourceTypeNames.isEmpty()) { + count += createRestrictionPerContext(roleName, null, permissionName, null, null, resourceTypePermission, contextNames, action); + } else { for (Integer resourceGroupId : resourceGroupIds) { - if (contextNames == null || contextNames.isEmpty()) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, resourceGroupId, null, - resourceTypePermission, null, action, restriction) != null) { - count++; - } - } else { - for (String contextName : contextNames) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, resourceGroupId, null, - resourceTypePermission, contextName, action, restriction) != null) { - count++; - } - } - } + count += createRestrictionPerContext(roleName, null, permissionName, resourceGroupId, null, resourceTypePermission, contextNames, action); } - } else { - if (resourceTypeNames != null && !resourceTypeNames.isEmpty()) { - for (String resourceTypeName : resourceTypeNames) { - if (contextNames == null || contextNames.isEmpty()) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, null, resourceTypeName, - resourceTypePermission, null, action, restriction) != null) { - count++; - } - } else { - for (String contextName : contextNames) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, null, resourceTypeName, - resourceTypePermission, contextName, action, restriction) != null) { - count++; - } - } - } - } - } else { - if (contextNames == null || contextNames.isEmpty()) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, null, null, - resourceTypePermission, null, action, restriction) != null) { - count++; - } - } else { - for (String contextName : contextNames) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(roleName, null, permissionName, null, null, - resourceTypePermission, contextName, action, restriction) != null) { - count++; - } - } - } + for (String resourceTypeName : resourceTypeNames) { + count += createRestrictionPerContext(roleName, null, permissionName, null, resourceTypeName, resourceTypePermission, contextNames, action); } } } - if (userNames != null && !userNames.isEmpty()) { - for (String userName : userNames) { - if (resourceGroupIds != null && !resourceGroupIds.isEmpty()) { - for (Integer resourceGroupId : resourceGroupIds) { - if (contextNames == null ||contextNames.isEmpty()) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(null, userName, permissionName, resourceGroupId, null, - resourceTypePermission, null, action, restriction) != null) { - count++; - } - } else { - for (String contextName : contextNames) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(null, userName, permissionName, resourceGroupId, null, - resourceTypePermission, contextName, action, restriction) != null) { - count++; - } - } - } - } - } else { - if (resourceTypeNames != null && !resourceTypeNames.isEmpty()) { - for (String resourceTypeName : resourceTypeNames) { - if (contextNames == null || contextNames.isEmpty()) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(null, userName, permissionName, null, resourceTypeName, - resourceTypePermission, null, action, restriction) != null) { - count++; - } - } else { - for (String contextName : contextNames) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(null, userName, permissionName, null, resourceTypeName, - resourceTypePermission, contextName, action, restriction) != null) { - count++; - } - } - } - } - } else { - if (contextNames == null || contextNames.isEmpty()) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(null, userName, permissionName, null, null, - resourceTypePermission, null, action, restriction) != null) { - count++; - } - } else { - for (String contextName : contextNames) { - RestrictionEntity restriction = new RestrictionEntity(); - if (createRestriction(null, userName, permissionName, null, null, - resourceTypePermission, contextName, action, restriction) != null) { - count++; - } - } - } - } + for (String userName : userNames) { + if (resourceGroupIds.isEmpty() && resourceTypeNames.isEmpty()) { + count += createRestrictionPerContext(null, userName, permissionName, null, null, resourceTypePermission, contextNames, action); + } else { + for (Integer resourceGroupId : resourceGroupIds) { + count += createRestrictionPerContext(null, userName, permissionName, resourceGroupId, null, resourceTypePermission, contextNames, action); + } + for (String resourceTypeName : resourceTypeNames) { + count += createRestrictionPerContext(null, userName, permissionName, null, resourceTypeName, resourceTypePermission, contextNames, action); } } } @@ -601,6 +523,18 @@ public int createMultipleRestrictions(String roleName, List userNames, L return count; } + private int createRestrictionPerContext(String roleName, String userName, String permissionName, Integer resourceGroupId, String resourceTypeName, ResourceTypePermission resourceTypePermission, List contextNames, Action action) throws AMWException { + int count = 0; + for (String contextName : contextNames) { + RestrictionEntity restriction = new RestrictionEntity(); + if (createRestriction(roleName, userName, permissionName, resourceGroupId, resourceTypeName, + resourceTypePermission, contextName, action, restriction) != null) { + count++; + } + } + return count; + } + public boolean canDelegatePermissionsForThisResource(ResourceEntity resource, ContextEntity context) { return (permissionService.hasPermission(Permission.PERMISSION_DELEGATION) && canDelegateThisPermission(Permission.RESOURCE.name(), resource.getResourceGroup().getId(), null, context.getName(), null)); }