You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mc...@apache.org on 2014/05/20 01:28:39 UTC

[4/7] Disable IAM feature from 4.4 release.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
index 0c0c588..b6977c2 100755
--- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
+++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
@@ -483,7 +483,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
                         return limits;
                     }
 
-                    _accountMgr.checkAccess(caller, null, account);
+                    _accountMgr.checkAccess(caller, null, true, account);
                     domainId = null;
                 }
             }
@@ -503,7 +503,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
         if (id != null) {
             ResourceLimitVO vo = _resourceLimitDao.findById(id);
             if (vo.getAccountId() != null) {
-                _accountMgr.checkAccess(caller, null, _accountDao.findById(vo.getAccountId()));
+                _accountMgr.checkAccess(caller, null, true, _accountDao.findById(vo.getAccountId()));
                 limits.add(vo);
             } else if (vo.getDomainId() != null) {
                 _accountMgr.checkAccess(caller, _domainDao.findById(vo.getDomainId()));
@@ -656,9 +656,9 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
             }
 
             if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
-                _accountMgr.checkAccess(caller, AccessType.ModifyProject, account);
+                _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, account);
             } else {
-                _accountMgr.checkAccess(caller, null, account);
+                _accountMgr.checkAccess(caller, null, true, account);
             }
 
             ownerType = ResourceOwnerType.Account;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java
index 4a4c74a..dd4ce0f 100755
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -952,7 +952,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
 
         List<EventVO> events = _eventDao.listToArchiveOrDeleteEvents(ids, cmd.getType(), cmd.getStartDate(), cmd.getEndDate(), permittedAccountIds);
         ControlledEntity[] sameOwnerEvents = events.toArray(new ControlledEntity[events.size()]);
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, sameOwnerEvents);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, false, sameOwnerEvents);
 
         if (ids != null && events.size() < ids.size()) {
             result = false;
@@ -979,7 +979,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
 
         List<EventVO> events = _eventDao.listToArchiveOrDeleteEvents(ids, cmd.getType(), cmd.getStartDate(), cmd.getEndDate(), permittedAccountIds);
         ControlledEntity[] sameOwnerEvents = events.toArray(new ControlledEntity[events.size()]);
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, sameOwnerEvents);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, false, sameOwnerEvents);
 
         if (ids != null && events.size() < ids.size()) {
             result = false;
@@ -1768,22 +1768,19 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
         SearchBuilder<IPAddressVO> sb = _publicIpAddressDao.createSearchBuilder();
         Long domainId = null;
         Boolean isRecursive = null;
-        List<Long> permittedDomains = new ArrayList<Long>();
         List<Long> permittedAccounts = new ArrayList<Long>();
-        List<Long> permittedResources = new ArrayList<Long>();
-
         ListProjectResourcesCriteria listProjectResourcesCriteria = null;
         if (isAllocated) {
             Account caller = CallContext.current().getCallingAccount();
 
             Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
                     cmd.getDomainId(), cmd.isRecursive(), null);
-            _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources,
-                    domainIdRecursiveListProject, cmd.listAll(), false, "listPublicIpAddresses");
-            //domainId = domainIdRecursiveListProject.first();
+            _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
+                    domainIdRecursiveListProject, cmd.listAll(), false);
+            domainId = domainIdRecursiveListProject.first();
             isRecursive = domainIdRecursiveListProject.second();
             listProjectResourcesCriteria = domainIdRecursiveListProject.third();
-            _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+            _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
         }
 
         sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
@@ -1838,7 +1835,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
 
         SearchCriteria<IPAddressVO> sc = sb.create();
         if (isAllocated) {
-            _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+            _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
         }
 
         sc.setJoinParameters("vlanSearch", "vlanType", vlanType);
@@ -3315,7 +3312,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
         }
 
         // check permissions
-        _accountMgr.checkAccess(caller, null, _accountMgr.getAccount(user.getAccountId()));
+        _accountMgr.checkAccess(caller, null, true, _accountMgr.getAccount(user.getAccountId()));
 
         String cloudIdentifier = _configDao.getValue("cloud.identifier");
         if (cloudIdentifier == null) {
@@ -3422,7 +3419,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
             throw ex;
         }
 
-        _accountMgr.checkAccess(caller, null, group);
+        _accountMgr.checkAccess(caller, null, true, group);
 
         // Check if name is already in use by this account (exclude this group)
         boolean isNameInUse = _vmGroupDao.isNameInUse(group.getAccountId(), groupName);
@@ -3581,22 +3578,21 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
         String fingerPrint = cmd.getFingerprint();
 
         Account caller = CallContext.current().getCallingAccount();
-        List<Long> permittedDomains = new ArrayList<Long>();
         List<Long> permittedAccounts = new ArrayList<Long>();
-        List<Long> permittedResources = new ArrayList<Long>();
 
         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
                 cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources,
-                domainIdRecursiveListProject, cmd.listAll(), false, "listSSHKeyPairs");
+        _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject,
+                cmd.listAll(), false);
+        Long domainId = domainIdRecursiveListProject.first();
         Boolean isRecursive = domainIdRecursiveListProject.second();
         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
         SearchBuilder<SSHKeyPairVO> sb = _sshKeyPairDao.createSearchBuilder();
-        _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+        _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
         Filter searchFilter = new Filter(SSHKeyPairVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
 
         SearchCriteria<SSHKeyPairVO> sc = sb.create();
-        _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         if (name != null) {
             sc.addAnd("name", SearchCriteria.Op.EQ, name);
@@ -3661,7 +3657,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
         }
 
         // make permission check
-        _accountMgr.checkAccess(caller, null, vm);
+        _accountMgr.checkAccess(caller, null, true, vm);
 
         _userVmDao.loadDetails(vm);
         String password = vm.getDetail("Encrypted.Password");
@@ -3834,7 +3830,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
             throw new InvalidParameterValueException("Unable to find SystemVm with id " + systemVmId);
         }
 
-        _accountMgr.checkAccess(caller, null, systemVm);
+        _accountMgr.checkAccess(caller, null, true, systemVm);
 
         // Check that the specified service offering ID is valid
         ServiceOfferingVO newServiceOffering = _offeringDao.findById(serviceOfferingId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/servlet/ConsoleProxyServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java
index 16d7a32..60f32cf 100644
--- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java
+++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java
@@ -522,7 +522,7 @@ public class ConsoleProxyServlet extends HttpServlet {
         switch (vm.getType()) {
             case User:
             try {
-                _accountMgr.checkAccess(accountObj, null, vm);
+                _accountMgr.checkAccess(accountObj, null, true, vm);
             } catch (PermissionDeniedException ex) {
                 if (_accountMgr.isNormalUser(accountObj.getId())) {
                     if (s_logger.isDebugEnabled()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/storage/VolumeApiServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java
index 6db3a2d..1650240 100644
--- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java
+++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java
@@ -28,7 +28,6 @@ import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
 
-import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd;
 import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd;
 import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
@@ -273,7 +272,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
     private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url, String format) throws ResourceAllocationException {
 
         // permission check
-        _accountMgr.checkAccess(caller, null, _accountMgr.getActiveAccountById(ownerId));
+        _accountMgr.checkAccess(caller, null, true, _accountMgr.getActiveAccountById(ownerId));
 
         // Check that the resource limit for volumes won't be exceeded
         _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.volume);
@@ -383,11 +382,10 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
         Boolean displayVolume = cmd.getDisplayVolume();
 
         // permission check
-        _accountMgr.checkAccess(caller, null, owner);
+        _accountMgr.checkAccess(caller, null, true, _accountMgr.getActiveAccountById(ownerId));
 
         if (displayVolume == null) {
             displayVolume = true;
-
         } else {
             if (!_accountMgr.isRootAdmin(caller.getId())) {
                 throw new PermissionDeniedException("Cannot update parameter displayvolume, only admin permitted ");
@@ -511,6 +509,9 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
             size = snapshotCheck.getSize(); // ; disk offering is used for tags
             // purposes
 
+            // check snapshot permissions
+            _accountMgr.checkAccess(caller, null, true, snapshotCheck);
+
             // one step operation - create volume in VM's cluster and attach it
             // to the VM
             Long vmId = cmd.getVirtualMachineId();
@@ -525,6 +526,9 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
                 if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
                     throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
                 }
+
+                // permission check
+                _accountMgr.checkAccess(caller, null, false, vm);
             }
 
         }
@@ -771,7 +775,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
         }
 
         /* does the caller have the authority to act on this volume? */
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, volume);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
 
         long currentSize = volume.getSize();
 
@@ -934,7 +938,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
             throw new InvalidParameterValueException("There are snapshot creating on it, Unable to delete the volume");
         }
 
-        _accountMgr.checkAccess(caller, null, volume);
+        _accountMgr.checkAccess(caller, null, true, volume);
 
         if (volume.getInstanceId() != null) {
             throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
@@ -1127,8 +1131,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
         }
 
         // permission check
-        // TODO: remove this if we can annotate volume parameter in createVolumeCmd since this routine is used there as well.
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, volume, vm);
+        _accountMgr.checkAccess(caller, null, true, volume, vm);
 
         if (!(Volume.State.Allocated.equals(volume.getState()) || Volume.State.Ready.equals(volume.getState()) || Volume.State.Uploaded.equals(volume.getState()))) {
             throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state");
@@ -1342,7 +1345,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
         }
 
         // Permissions check
-        _accountMgr.checkAccess(caller, null, volume);
+        _accountMgr.checkAccess(caller, null, true, volume);
 
         // Check that the volume is a data volume
         if (volume.getVolumeType() != Volume.Type.DATADISK) {
@@ -1787,7 +1790,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
         }
 
         // perform permission check
-        _accountMgr.checkAccess(account, null, volume);
+        _accountMgr.checkAccess(account, null, true, volume);
 
         if (_dcDao.findById(zoneId) == null) {
             throw new InvalidParameterValueException("Please specify a valid zone.");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
index d19a0ed..44bce1a 100755
--- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
+++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
@@ -286,7 +286,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
 
         boolean backedUp = false;
         // does the caller have the authority to act on this volume
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, volume);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
 
         SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
 
@@ -391,7 +391,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
             throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
         }
 
-        _accountMgr.checkAccess(caller, null, snapshotCheck);
+        _accountMgr.checkAccess(caller, null, true, snapshotCheck);
         SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshotCheck, SnapshotOperation.DELETE);
         if (snapshotStrategy == null) {
             s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
@@ -441,28 +441,25 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         Map<String, String> tags = cmd.getTags();
         Long zoneId = cmd.getZoneId();
         Account caller = CallContext.current().getCallingAccount();
-        List<Long> permittedDomains = new ArrayList<Long>();
         List<Long> permittedAccounts = new ArrayList<Long>();
-        List<Long> permittedResources = new ArrayList<Long>();
-
 
         // Verify parameters
         if (volumeId != null) {
             VolumeVO volume = _volsDao.findById(volumeId);
             if (volume != null) {
-                _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, volume);
+                _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
             }
         }
 
         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedDomains, permittedAccounts, permittedResources,
-                domainIdRecursiveListProject, cmd.listAll(), false, "listSnapshots");
+       _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
+       Long domainId = domainIdRecursiveListProject.first();
        Boolean isRecursive = domainIdRecursiveListProject.second();
        ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
 
         Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
         SearchBuilder<SnapshotVO> sb = _snapshotDao.createSearchBuilder();
-        _accountMgr.buildACLSearchBuilder(sb, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+        _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         sb.and("statusNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); //exclude those Destroyed snapshot, not showing on UI
         sb.and("volumeId", sb.entity().getVolumeId(), SearchCriteria.Op.EQ);
@@ -485,7 +482,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         }
 
         SearchCriteria<SnapshotVO> sc = sb.create();
-        _accountMgr.buildACLSearchCriteria(sc, isRecursive, permittedDomains, permittedAccounts, permittedResources, listProjectResourcesCriteria);
+        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         sc.setParameters("statusNEQ", Snapshot.State.Destroyed);
 
@@ -624,7 +621,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
             throw new InvalidParameterValueException("Failed to create snapshot policy, unable to find a volume with id " + volumeId);
         }
 
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, volume);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
 
         if (volume.getState() != Volume.State.Ready) {
             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() +
@@ -723,7 +720,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         if (volume == null) {
             throw new InvalidParameterValueException("Unable to find a volume with id " + volumeId);
         }
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, volume);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
         Pair<List<SnapshotPolicyVO>, Integer> result = _snapshotPolicyDao.listAndCountByVolumeId(volumeId);
         return new Pair<List<? extends SnapshotPolicy>, Integer>(result.first(), result.second());
     }
@@ -999,7 +996,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
                 throw new InvalidParameterValueException("Policy id given: " + policy + " does not belong to a valid volume");
             }
 
-            _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, volume);
+            _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
         }
 
         boolean success = true;
@@ -1030,9 +1027,12 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
 
     @Override
     public Snapshot allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException {
+        Account caller = CallContext.current().getCallingAccount();
         VolumeInfo volume = volFactory.getVolume(volumeId);
         supportedByHypervisor(volume);
 
+        // Verify permissions
+        _accountMgr.checkAccess(caller, null, true, volume);
         Type snapshotType = getSnapshotType(policyId);
         Account owner = _accountMgr.getAccount(volume.getAccountId());
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
index cac12c6..fa7fcb7 100644
--- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
+++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
@@ -227,7 +227,7 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso
                         Long domainId = accountDomainPair.second();
                         Long accountId = accountDomainPair.first();
                         if (accountId != null) {
-                            _accountMgr.checkAccess(caller, null, _accountMgr.getAccount(accountId));
+                            _accountMgr.checkAccess(caller, null, false, _accountMgr.getAccount(accountId));
                         } else if (domainId != null && !_accountMgr.isNormalUser(caller.getId())) {
                             //check permissions;
                             _accountMgr.checkAccess(caller, _domainMgr.getDomain(domainId));
@@ -289,7 +289,7 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso
         for (ResourceTag resourceTag : resourceTags) {
             //1) validate the permissions
             Account owner = _accountMgr.getAccount(resourceTag.getAccountId());
-            _accountMgr.checkAccess(caller, null, owner);
+            _accountMgr.checkAccess(caller, null, false, owner);
             //2) Only remove tag if it matches key value pairs
             if (tags != null && !tags.isEmpty()) {
                 for (String key : tags.keySet()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/template/TemplateAdapterBase.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java
index cb38075..fcf15df 100755
--- a/server/src/com/cloud/template/TemplateAdapterBase.java
+++ b/server/src/com/cloud/template/TemplateAdapterBase.java
@@ -254,7 +254,7 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
         //check if the caller can operate with the template owner
         Account caller = CallContext.current().getCallingAccount();
         Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
-        _accountMgr.checkAccess(caller, null, owner);
+        _accountMgr.checkAccess(caller, null, true, owner);
 
         boolean isRouting = (cmd.isRoutingType() == null) ? false : cmd.isRoutingType();
 
@@ -277,7 +277,7 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
         //check if the caller can operate with the template owner
         Account caller = CallContext.current().getCallingAccount();
         Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
-        _accountMgr.checkAccess(caller, null, owner);
+        _accountMgr.checkAccess(caller, null, true, owner);
 
         Long zoneId = cmd.getZoneId();
         // ignore passed zoneId if we are using region wide image store

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/template/TemplateManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java
index 294748f..0cc7438 100755
--- a/server/src/com/cloud/template/TemplateManagerImpl.java
+++ b/server/src/com/cloud/template/TemplateManagerImpl.java
@@ -369,7 +369,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             throw new InvalidParameterValueException("Unable to find template id=" + templateId);
         }
 
-        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, vmTemplate);
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, true, vmTemplate);
 
         prepareTemplateInAllStoragePools(vmTemplate, zoneId);
         return vmTemplate;
@@ -415,7 +415,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             throw new InvalidParameterValueException("Unable to extract template id=" + templateId + " as it's not extractable");
         }
 
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, template);
+        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
 
         List<DataStore> ssStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
 
@@ -722,7 +722,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             return template;
         }
 
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, template);
+        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
 
         boolean success = copy(userId, template, srcSecStore, dstZone);
 
@@ -911,7 +911,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             throw new InvalidParameterValueException("Please specify a valid VM.");
         }
 
-        _accountMgr.checkAccess(caller, null, userVM);
+        _accountMgr.checkAccess(caller, null, true, userVM);
 
         Long isoId = userVM.getIsoId();
         if (isoId == null) {
@@ -952,11 +952,12 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
 
         // check permissions
         // check if caller has access to VM and ISO
-        // and also check if the VM's owner has access to the ISO. This is a bit different from sameOwner check for attachVolumeToVM, where both volume and VM need
-        // OperateEntry access type. Here VM needs OperateEntry access type, ISO needs UseEntry access type.
-        _accountMgr.checkAccess(caller, null, iso, vm);
+        // and also check if the VM's owner has access to the ISO.
+
+        _accountMgr.checkAccess(caller, null, false, iso, vm);
+
         Account vmOwner = _accountDao.findById(vm.getAccountId());
-        _accountMgr.checkAccess(vmOwner, null, iso);
+        _accountMgr.checkAccess(vmOwner, null, false, iso, vm);
 
         State vmState = vm.getState();
         if (vmState != State.Running && vmState != State.Stopped) {
@@ -1060,7 +1061,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             throw new InvalidParameterValueException("unable to find template with id " + templateId);
         }
 
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, template);
+        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
 
         if (template.getFormat() == ImageFormat.ISO) {
             throw new InvalidParameterValueException("Please specify a valid template.");
@@ -1083,7 +1084,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             throw new InvalidParameterValueException("unable to find iso with id " + templateId);
         }
 
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, template);
+        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
 
         if (template.getFormat() != ImageFormat.ISO) {
             throw new InvalidParameterValueException("Please specify a valid iso.");
@@ -1133,7 +1134,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
         }
 
         if (!template.isPublicTemplate()) {
-            _accountMgr.checkAccess(caller, AccessType.ListEntry, template);
+            _accountMgr.checkAccess(caller, null, true, template);
         }
 
         List<String> accountNames = new ArrayList<String>();
@@ -1206,7 +1207,8 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             }
         }
 
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, template);
+        //_accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
+        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template); //TODO: should we replace all ModifyEntry as OperateEntry?
 
         // If the template is removed throw an error.
         if (template.getRemoved() != null) {
@@ -1487,7 +1489,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
         Account caller = CallContext.current().getCallingAccount();
         boolean isAdmin = (_accountMgr.isAdmin(caller.getId()));
 
-        _accountMgr.checkAccess(caller, null, templateOwner);
+        _accountMgr.checkAccess(caller, null, true, templateOwner);
 
         String name = cmd.getTemplateName();
         if ((name == null) || (name.length() > 32)) {
@@ -1539,7 +1541,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
                 throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId);
             }
             // check permissions
-            _accountMgr.checkAccess(caller, null, volume);
+            _accountMgr.checkAccess(caller, null, true, volume);
 
             // If private template is created from Volume, check that the volume
             // will not be active when the private template is
@@ -1562,7 +1564,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             volume = _volumeDao.findById(snapshot.getVolumeId());
 
             // check permissions
-            _accountMgr.checkAccess(caller, null, snapshot);
+            _accountMgr.checkAccess(caller, null, true, snapshot);
 
             if (snapshot.getState() != Snapshot.State.BackedUp) {
                 throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp +
@@ -1778,7 +1780,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
         verifyTemplateId(id);
 
         // do a permission check
-        _accountMgr.checkAccess(account, AccessType.OperateEntry, template);
+        _accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
         if (cmd.isRoutingType() != null) {
             if (!_accountService.isRootAdmin(account.getId())) {
                 throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/user/AccountManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java
index 03bf842..bee7029 100755
--- a/server/src/com/cloud/user/AccountManager.java
+++ b/server/src/com/cloud/user/AccountManager.java
@@ -24,6 +24,7 @@ import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd;
 import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
 import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
 
+import com.cloud.api.query.vo.ControlledViewEntity;
 import com.cloud.exception.ConcurrentOperationException;
 import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.projects.Project.ListProjectResourcesCriteria;
@@ -84,19 +85,35 @@ public interface AccountManager extends AccountService {
     boolean enableAccount(long accountId);
 
 
+    void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb, Long domainId,
+            boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria);
+
+    void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId,
+            boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria);
+
+    void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId,
+            boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria, List<Long> grantedIds, List<Long> revokedIds);
+
+    void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc,
+            Long domainId, boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria);
+
+    void buildACLSearchParameters(Account caller, Long id,
+            String accountName, Long projectId, List<Long> permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, boolean listAll,
+            boolean forProjectInvitation);
+
+    void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledViewEntity> sc,
+            Long domainId, boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria);
+
+    void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledEntity> sc,
+            Long domainId, boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria, List<Long> grantedIds,
+            List<Long> revokedIds);
+
+
     // new ACL model routine for query api based on db views
     void buildACLSearchParameters(Account caller, Long id,
             String accountName, Long projectId, List<Long> permittedDomains, List<Long> permittedAccounts, List<Long> permittedResources,
             Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation, String action);
 
-    void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb, boolean isRecursive,
-            List<Long> permittedDomains,
-            List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria);
-
-    void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, boolean isRecursive,
-            List<Long> permittedDomains,
-            List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria);
-
     void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, SearchCriteria<? extends ControlledEntity> aclSc, boolean isRecursive,
             List<Long> permittedDomains, List<Long> permittedAccounts,
             List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f748a552/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java
index 3ff9bd2..b6be648 100755
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@ -48,7 +48,6 @@ import org.apache.cloudstack.acl.SecurityChecker;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
-import org.apache.cloudstack.api.InternalIdentity;
 import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd;
 import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
 import org.apache.cloudstack.api.command.admin.user.RegisterCmd;
@@ -61,6 +60,8 @@ import org.apache.cloudstack.framework.messagebus.PublishScope;
 import org.apache.cloudstack.managed.context.ManagedContextRunnable;
 import org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleDao;
 
+import com.cloud.api.ApiDBUtils;
+import com.cloud.api.query.vo.ControlledViewEntity;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.ConfigurationManager;
 import com.cloud.configuration.Resource.ResourceOwnerType;
@@ -101,7 +102,6 @@ import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.RemoteAccessVpnDao;
 import com.cloud.network.dao.RemoteAccessVpnVO;
 import com.cloud.network.dao.VpnUserDao;
-import com.cloud.network.security.SecurityGroup;
 import com.cloud.network.security.SecurityGroupManager;
 import com.cloud.network.security.dao.SecurityGroupDao;
 import com.cloud.network.vpc.Vpc;
@@ -110,6 +110,7 @@ import com.cloud.network.vpn.RemoteAccessVpnService;
 import com.cloud.network.vpn.Site2SiteVpnManager;
 import com.cloud.projects.Project;
 import com.cloud.projects.Project.ListProjectResourcesCriteria;
+import com.cloud.projects.ProjectInvitationVO;
 import com.cloud.projects.ProjectManager;
 import com.cloud.projects.ProjectVO;
 import com.cloud.projects.dao.ProjectAccountDao;
@@ -386,8 +387,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             for (SecurityChecker checker : _securityCheckers) {
                 try {
                     if (checker.checkAccess(acct, null, null, "SystemCapability")) {
-                        if (s_logger.isDebugEnabled()) {
-                            s_logger.debug("Root Access granted to " + acct + " by " + checker.getName());
+                        if (s_logger.isTraceEnabled()) {
+                            s_logger.trace("Root Access granted to " + acct + " by " + checker.getName());
                         }
                         return true;
                     }
@@ -409,8 +410,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             for (SecurityChecker checker : _securityCheckers) {
                 try {
                     if (checker.checkAccess(acct, null, null, "DomainCapability")) {
-                        if (s_logger.isDebugEnabled()) {
-                            s_logger.debug("DomainAdmin Access granted to " + acct + " by " + checker.getName());
+                        if (s_logger.isTraceEnabled()) {
+                            s_logger.trace("DomainAdmin Access granted to " + acct + " by " + checker.getName());
                         }
                         return true;
                     }
@@ -440,8 +441,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             for (SecurityChecker checker : _securityCheckers) {
                 try {
                     if (checker.checkAccess(acct, null, null, "DomainResourceCapability")) {
-                        if (s_logger.isDebugEnabled()) {
-                            s_logger.debug("ResourceDomainAdmin Access granted to " + acct + " by " + checker.getName());
+                        if (s_logger.isTraceEnabled()) {
+                            s_logger.trace("ResourceDomainAdmin Access granted to " + acct + " by " + checker.getName());
                         }
                         return true;
                     }
@@ -481,90 +482,89 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
 
     @Override
-    public void checkAccess(Account caller, AccessType accessType, ControlledEntity... entities) throws PermissionDeniedException {
-        checkAccess(caller, accessType, null, entities);
+    public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, ControlledEntity... entities) {
+        checkAccess(caller, accessType, sameOwner, null, entities);
     }
 
     @Override
-    public void checkAccess(Account caller, AccessType accessType, String apiName, ControlledEntity... entities) throws PermissionDeniedException {
-        boolean granted = false;
-        // construct entities identification string
-        StringBuffer entityBuf = new StringBuffer("{");
-        for (ControlledEntity ent : entities) {
-            entityBuf.append(ent.toString());
-        }
-        entityBuf.append("}");
-        String entityStr = entityBuf.toString();
-
-        boolean isRootAdmin = isRootAdmin(caller.getAccountId());
-        boolean isDomainAdmin = isDomainAdmin(caller.getAccountId());
-        boolean isResourceDomainAdmin = isResourceDomainAdmin(caller.getAccountId());
-
-        if ((isRootAdmin || isDomainAdmin || isResourceDomainAdmin || caller.getId() == Account.ACCOUNT_ID_SYSTEM)
-                && (accessType == null || accessType == AccessType.UseEntry)) {
-
+    public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, String apiName, ControlledEntity... entities) {
+        //check for the same owner
+        Long ownerId = null;
+        ControlledEntity prevEntity = null;
+        if (sameOwner) {
             for (ControlledEntity entity : entities) {
-                if (entity instanceof VirtualMachineTemplate || (entity instanceof Network && accessType != null && (isDomainAdmin || isResourceDomainAdmin))
-                        || entity instanceof AffinityGroup || entity instanceof SecurityGroup) {
-                    // Go through IAM (SecurityCheckers)
-                    for (SecurityChecker checker : _securityCheckers) {
-                        if (checker.checkAccess(caller, accessType, apiName, entity)) {
-                            if (s_logger.isDebugEnabled()) {
-                                s_logger.debug("Access to " + entityStr + " granted to " + caller + " by "
-                                        + checker.getName());
-                            }
-                            granted = true;
-                            break;
-                        }
-                    }
-                } else {
-                    if (isRootAdmin || caller.getId() == Account.ACCOUNT_ID_SYSTEM) {
-                        // no need to make permission checks if the system/root
-                        // admin makes the call
-                        if (s_logger.isTraceEnabled()) {
-                            s_logger.trace("No need to make permission check for System/RootAdmin account, returning true");
-                        }
-                        granted = true;
-                    } else if (isDomainAdmin || isResourceDomainAdmin) {
-                        Domain entityDomain = getEntityDomain(entity);
-                        if (entityDomain != null) {
-                            try {
-                                checkAccess(caller, entityDomain);
-                                granted = true;
-                            } catch (PermissionDeniedException e) {
-                                List<ControlledEntity> entityList = new ArrayList<ControlledEntity>();
-                                entityList.add(entity);
-                                e.addDetails(caller, entityList);
-                                throw e;
-                            }
-                        }
+                if (sameOwner) {
+                    if (ownerId == null) {
+                        ownerId = entity.getAccountId();
+                    } else if (ownerId.longValue() != entity.getAccountId()) {
+                        throw new PermissionDeniedException("Entity " + entity + " and entity " + prevEntity + " belong to different accounts");
                     }
+                    prevEntity = entity;
                 }
+            }
+        }
 
-                if (!granted) {
-                    assert false : "How can all of the security checkers pass on checking this check: " + entityStr;
-                    throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to "
-                            + entityStr);
-                }
+        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getId())) {
+            // no need to make permission checks if the system/root admin makes the call
+            if (s_logger.isTraceEnabled()) {
+                s_logger.trace("No need to make permission check for System/RootAdmin account, returning true");
+            }
+            return;
+        }
 
+        HashMap<Long, List<ControlledEntity>> domains = new HashMap<Long, List<ControlledEntity>>();
+
+        for (ControlledEntity entity : entities) {
+            long domainId = entity.getDomainId();
+            if (entity.getAccountId() != -1 && domainId == -1) { // If account exists domainId should too so calculate
+                // it. This condition might be hit for templates or entities which miss domainId in their tables
+                Account account = ApiDBUtils.findAccountById(entity.getAccountId());
+                domainId = account != null ? account.getDomainId() : -1;
             }
-        } else {
-            // Go through IAM (SecurityCheckers)
+            if (entity.getAccountId() != -1 && domainId != -1 && !(entity instanceof VirtualMachineTemplate) &&
+                !(entity instanceof Network && accessType != null && accessType == AccessType.UseEntry) && !(entity instanceof AffinityGroup)) {
+                List<ControlledEntity> toBeChecked = domains.get(entity.getDomainId());
+                // for templates, we don't have to do cross domains check
+                if (toBeChecked == null) {
+                    toBeChecked = new ArrayList<ControlledEntity>();
+                    domains.put(domainId, toBeChecked);
+                }
+                toBeChecked.add(entity);
+            }
+            boolean granted = false;
             for (SecurityChecker checker : _securityCheckers) {
-                if (checker.checkAccess(caller, accessType, apiName, entities)) {
+                if (checker.checkAccess(caller, entity, accessType, apiName)) {
                     if (s_logger.isDebugEnabled()) {
-                        s_logger.debug("Access to " + entityStr + " granted to " + caller + " by " + checker.getName());
+                        s_logger.debug("Access to " + entity + " granted to " + caller + " by " + checker.getName());
                     }
                     granted = true;
                     break;
                 }
             }
+
+            if (!granted) {
+                assert false : "How can all of the security checkers pass on checking this check: " + entity;
+                throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity);
+            }
         }
 
-        if (!granted) {
-            assert false : "How can all of the security checkers pass on checking this check: " + entityStr;
-            throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entityStr);
+        for (Map.Entry<Long, List<ControlledEntity>> domain : domains.entrySet()) {
+            for (SecurityChecker checker : _securityCheckers) {
+                Domain d = _domainMgr.getDomain(domain.getKey());
+                if (d == null || d.getRemoved() != null) {
+                    throw new PermissionDeniedException("Domain is not found.", caller, domain.getValue());
+                }
+                try {
+                    checker.checkAccess(caller, d);
+                } catch (PermissionDeniedException e) {
+                    e.addDetails(caller, domain.getValue());
+                    throw e;
+                }
+            }
         }
+
+        // check that resources belong to the same account
+
     }
 
     private Domain getEntityDomain(ControlledEntity entity) {
@@ -1167,7 +1167,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new PermissionDeniedException("user id : " + id + " is system account, update is not allowed");
         }
 
-        checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, account);
+        checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, true, account);
 
         if (firstName != null) {
             if (firstName.isEmpty()) {
@@ -1284,7 +1284,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new InvalidParameterValueException("User id : " + userId + " is a system user, disabling is not allowed");
         }
 
-        checkAccess(caller, AccessType.OperateEntry, account);
+        checkAccess(caller, AccessType.OperateEntry, true, account);
 
         boolean success = doSetUserStatus(userId, State.disabled);
         if (success) {
@@ -1325,7 +1325,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new InvalidParameterValueException("User id : " + userId + " is a system user, enabling is not allowed");
         }
 
-        checkAccess(caller, AccessType.OperateEntry, account);
+        checkAccess(caller, AccessType.OperateEntry, true, account);
 
         boolean success = Transaction.execute(new TransactionCallback<Boolean>() {
             @Override
@@ -1377,7 +1377,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new PermissionDeniedException("user id : " + userId + " is a system user, locking is not allowed");
         }
 
-        checkAccess(caller, AccessType.OperateEntry, account);
+        checkAccess(caller, AccessType.OperateEntry, true, account);
 
         // make sure the account is enabled too
         // if the user is either locked already or disabled already, don't change state...only lock currently enabled
@@ -1441,7 +1441,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new InvalidParameterValueException("The specified account does not exist in the system");
         }
 
-        checkAccess(caller, null, account);
+        checkAccess(caller, null, true, account);
 
         // don't allow to delete default account (system and admin)
         if (account.isDefault()) {
@@ -1486,7 +1486,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
         // Check if user performing the action is allowed to modify this account
         Account caller = CallContext.current().getCallingAccount();
-        checkAccess(caller, AccessType.OperateEntry, account);
+        checkAccess(caller, AccessType.OperateEntry, true, account);
 
         boolean success = enableAccount(account.getId());
         if (success) {
@@ -1520,7 +1520,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new PermissionDeniedException("Account id : " + accountId + " is a system account, lock is not allowed");
         }
 
-        checkAccess(caller, AccessType.OperateEntry, account);
+        checkAccess(caller, AccessType.OperateEntry, true, account);
 
         if (lockAccount(account.getId())) {
             CallContext.current().putContextParameter(Account.class, account.getUuid());
@@ -1550,7 +1550,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new PermissionDeniedException("Account id : " + accountId + " is a system account, disable is not allowed");
         }
 
-        checkAccess(caller, AccessType.OperateEntry, account);
+        checkAccess(caller, AccessType.OperateEntry, true, account);
 
         if (disableAccount(account.getId())) {
             CallContext.current().putContextParameter(Account.class, account.getUuid());
@@ -1669,7 +1669,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new InvalidParameterValueException("The user is default and can't be removed");
         }
 
-        checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, account);
+        checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, true, account);
         CallContext.current().putContextParameter(User.class, user.getUuid());
         return _userDao.remove(id);
     }
@@ -2278,6 +2278,373 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     }
 
 
+
+    @Override
+    public void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb,
+            Long domainId, boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) {
+
+        if (sb.entity() instanceof IPAddressVO) {
+            sb.and("accountIdIN", ((IPAddressVO) sb.entity()).getAllocatedToAccountId(), SearchCriteria.Op.IN);
+            sb.and("domainId", ((IPAddressVO) sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.EQ);
+        } else if (sb.entity() instanceof ProjectInvitationVO) {
+            sb.and("accountIdIN", ((ProjectInvitationVO) sb.entity()).getForAccountId(), SearchCriteria.Op.IN);
+            sb.and("domainId", ((ProjectInvitationVO) sb.entity()).getInDomainId(), SearchCriteria.Op.EQ);
+        } else {
+            sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
+            sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
+        }
+
+        if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) {
+            // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true
+            SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
+            domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
+
+            if (sb.entity() instanceof IPAddressVO) {
+                sb.join("domainSearch", domainSearch, ((IPAddressVO) sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            } else if (sb.entity() instanceof ProjectInvitationVO) {
+                sb.join("domainSearch", domainSearch, ((ProjectInvitationVO) sb.entity()).getInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            } else {
+                sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            }
+
+        }
+        if (listProjectResourcesCriteria != null) {
+            SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
+            if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
+                accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
+            } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
+                accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
+            }
+
+            if (sb.entity() instanceof IPAddressVO) {
+                sb.join("accountSearch", accountSearch, ((IPAddressVO) sb.entity()).getAllocatedToAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            } else if (sb.entity() instanceof ProjectInvitationVO) {
+                sb.join("accountSearch", accountSearch, ((ProjectInvitationVO) sb.entity()).getForAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            } else {
+                sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            }
+        }
+    }
+
+    @Override
+    public void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc,
+            Long domainId, boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) {
+
+        if (listProjectResourcesCriteria != null) {
+            sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT);
+        }
+
+        if (!permittedAccounts.isEmpty()) {
+            sc.setParameters("accountIdIN", permittedAccounts.toArray());
+        } else if (domainId != null) {
+            DomainVO domain = _domainDao.findById(domainId);
+            if (isRecursive) {
+                sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%");
+            } else {
+                sc.setParameters("domainId", domainId);
+            }
+        }
+    }
+
+//    @Override
+//    public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long>
+//    permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject,
+//            boolean listAll, boolean forProjectInvitation) {
+//        Long domainId = domainIdRecursiveListProject.first();
+//        if (domainId != null) {
+//            Domain domain = _domainDao.findById(domainId);
+//            if (domain == null) {
+//                throw new InvalidParameterValueException("Unable to find domain by id " + domainId);
+//            }
+//            // check permissions
+//            checkAccess(caller, domain);
+//        }
+//
+//        if (accountName != null) {
+//            if (projectId != null) {
+//                throw new InvalidParameterValueException("Account and projectId can't be specified together");
+//            }
+//
+//            Account userAccount = null;
+//            Domain domain = null;
+//            if (domainId != null) {
+//                userAccount = _accountDao.findActiveAccount(accountName, domainId);
+//                domain = _domainDao.findById(domainId);
+//            } else {
+//                userAccount = _accountDao.findActiveAccount(accountName, caller.getDomainId());
+//                domain = _domainDao.findById(caller.getDomainId());
+//            }
+//
+//            if (userAccount != null) {
+//                checkAccess(caller, null, false, userAccount);
+//                //check permissions
+//                permittedAccounts.add(userAccount.getId());
+//            } else {
+//                throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domain.getUuid());
+//            }
+//        }
+//
+//        // set project information
+//        if (projectId != null) {
+//            if (!forProjectInvitation) {
+//                if (projectId.longValue() == -1) {
+//                    if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+//                        permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
+//                    } else {
+//                        domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.ListProjectResourcesOnly);
+//                    }
+//                } else {
+//                    Project project = _projectMgr.getProject(projectId);
+//                    if (project == null) {
+//                        throw new InvalidParameterValueException("Unable to find project by id " + projectId);
+//                    }
+//                    if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
+//                        throw new PermissionDeniedException("Account " + caller + " can't access project id=" + projectId);
+//                    }
+//                    permittedAccounts.add(project.getProjectAccountId());
+//                }
+//            }
+//        } else {
+//            if (id == null) {
+//                domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources);
+//            }
+//            if (permittedAccounts.isEmpty() && domainId == null) {
+//                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+//                    permittedAccounts.add(caller.getId());
+//                } else if (!listAll) {
+//                    if (id == null) {
+//                        permittedAccounts.add(caller.getId());
+//                    } else if (!isRootAdmin(caller.getId())) {
+//                        domainIdRecursiveListProject.first(caller.getDomainId());
+//                        domainIdRecursiveListProject.second(true);
+//                    }
+//                } else if (domainId == null) {
+//                    if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
+//                        domainIdRecursiveListProject.first(caller.getDomainId());
+//                        domainIdRecursiveListProject.second(true);
+//                    }
+//                }
+//            } else if (domainId != null) {
+//                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+//                    permittedAccounts.add(caller.getId());
+//                }
+//            }
+//
+//        }
+//    }
+
+    //TODO: deprecate this to use the new buildACLSearchParameters with permittedDomains, permittedAccounts, and permittedResources as return
+    @Override
+    public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long>
+    permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject,
+            boolean listAll, boolean forProjectInvitation) {
+        Long domainId = domainIdRecursiveListProject.first();
+        if (domainId != null) {
+            Domain domain = _domainDao.findById(domainId);
+            if (domain == null) {
+                throw new InvalidParameterValueException("Unable to find domain by id " + domainId);
+            }
+            // check permissions
+            checkAccess(caller, domain);
+        }
+
+        if (accountName != null) {
+            if (projectId != null) {
+                throw new InvalidParameterValueException("Account and projectId can't be specified together");
+            }
+
+            Account userAccount = null;
+            Domain domain = null;
+            if (domainId != null) {
+                userAccount = _accountDao.findActiveAccount(accountName, domainId);
+                domain = _domainDao.findById(domainId);
+            } else {
+                userAccount = _accountDao.findActiveAccount(accountName, caller.getDomainId());
+                domain = _domainDao.findById(caller.getDomainId());
+            }
+
+            if (userAccount != null) {
+                checkAccess(caller, null, false, userAccount);
+                // check permissions
+                permittedAccounts.add(userAccount.getId());
+            } else {
+                throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domain.getUuid());
+            }
+        }
+
+        // set project information
+        if (projectId != null) {
+            if (!forProjectInvitation) {
+                if (projectId.longValue() == -1) {
+                    if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                        permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
+                    } else {
+                        domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.ListProjectResourcesOnly);
+                    }
+                } else {
+                    Project project = _projectMgr.getProject(projectId);
+                    if (project == null) {
+                        throw new InvalidParameterValueException("Unable to find project by id " + projectId);
+                    }
+                    if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
+                        throw new PermissionDeniedException("Account " + caller + " can't access project id=" + projectId);
+                    }
+                    permittedAccounts.add(project.getProjectAccountId());
+                }
+            }
+        } else {
+            if (id == null) {
+                domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources);
+            }
+            if (permittedAccounts.isEmpty() && domainId == null) {
+                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                    permittedAccounts.add(caller.getId());
+                } else if (!listAll) {
+                    if (id == null) {
+                        permittedAccounts.add(caller.getId());
+                    } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
+                        domainIdRecursiveListProject.first(caller.getDomainId());
+                        domainIdRecursiveListProject.second(true);
+                    }
+                } else if (domainId == null) {
+                    if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
+                        domainIdRecursiveListProject.first(caller.getDomainId());
+                        domainIdRecursiveListProject.second(true);
+                    }
+                }
+            } else if (domainId != null) {
+                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                    permittedAccounts.add(caller.getId());
+                }
+            }
+
+        }
+
+    }
+
+
+    @Override
+    public void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId,
+            boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) {
+
+        sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
+        sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
+
+        if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) {
+            // if accountId isn't specified, we can do a domain match for the
+            // admin case if isRecursive is true
+            sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
+        }
+
+        if (listProjectResourcesCriteria != null) {
+            if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
+                sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
+            } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
+                sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
+            }
+        }
+
+    }
+
+    @Override
+    public void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
+            ListProjectResourcesCriteria listProjectResourcesCriteria, List<Long> grantedIds, List<Long> revokedIds) {
+
+        if (!revokedIds.isEmpty()) {
+            sb.and("idNIN", sb.entity().getId(), SearchCriteria.Op.NIN);
+        }
+        if (permittedAccounts.isEmpty() && domainId == null && listProjectResourcesCriteria == null) {
+            // caller role authorize him to access everything matching query criteria
+            return;
+
+        }
+        boolean hasOp = true;
+        if (!permittedAccounts.isEmpty()) {
+            sb.and().op("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
+        } else if (domainId != null) {
+            if (isRecursive) {
+                // if accountId isn't specified, we can do a domain match for the
+                // admin case if isRecursive is true
+                sb.and().op("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
+            } else {
+                sb.and().op("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
+            }
+        } else {
+            hasOp = false;
+        }
+
+
+        if (listProjectResourcesCriteria != null) {
+            if (hasOp) {
+                if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
+                    sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
+                } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
+                    sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
+                }
+            } else {
+                if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
+                    sb.and().op("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
+                } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
+                    sb.and().op("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
+                }
+            }
+        }
+
+        if (!grantedIds.isEmpty()) {
+            sb.or("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
+        }
+        sb.cp();
+
+
+    }
+
+    @Override
+    public void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledViewEntity> sc,
+            Long domainId, boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) {
+        if (listProjectResourcesCriteria != null) {
+            sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT);
+        }
+
+        if (!permittedAccounts.isEmpty()) {
+            sc.setParameters("accountIdIN", permittedAccounts.toArray());
+        } else if (domainId != null) {
+            DomainVO domain = _domainDao.findById(domainId);
+            if (isRecursive) {
+                sc.setParameters("domainPath", domain.getPath() + "%");
+            } else {
+                sc.setParameters("domainId", domainId);
+            }
+        }
+
+    }
+
+    @Override
+    public void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
+            ListProjectResourcesCriteria listProjectResourcesCriteria, List<Long> grantedIds, List<Long> revokedIds) {
+        if (!revokedIds.isEmpty()) {
+            sc.setParameters("idNIN", revokedIds.toArray());
+        }
+
+        if (listProjectResourcesCriteria != null) {
+            sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT);
+        }
+
+        if (!permittedAccounts.isEmpty()) {
+            sc.setParameters("accountIdIN", permittedAccounts.toArray());
+        } else if (domainId != null) {
+            DomainVO domain = _domainDao.findById(domainId);
+            if (isRecursive) {
+                sc.setParameters("domainPath", domain.getPath() + "%");
+            } else {
+                sc.setParameters("domainId", domainId);
+            }
+        }
+
+        if (!grantedIds.isEmpty()) {
+            sc.setParameters("idIN", grantedIds.toArray());
+        }
+    }
+
     @Override
     public UserAccount getUserByApiKey(String apiKey) {
         return _userAccountDao.getUserByApiKey(apiKey);
@@ -2321,8 +2688,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
                 if (userAccount != null) {
                     //check permissions
-                    checkAccess(caller, null, userAccount);
-                    accountId = userAccount.getId();
+                    checkAccess(caller, null, false, userAccount);
+                    permittedAccounts.add(userAccount.getId());
                 } else {
                     throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domain.getUuid());
                 }
@@ -2436,120 +2803,6 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     }
 
     @Override
-    public void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb, boolean isRecursive,
-            List<Long> permittedDomains,
-            List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) {
-
-        if (listProjectResourcesCriteria != null) {
-            // add criteria for project or not
-            SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
-            if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
-                accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
-            } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
-                accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
-            }
-
-            if (sb.entity() instanceof IPAddressVO) {
-                sb.join("accountSearch", accountSearch, ((IPAddressVO)sb.entity()).getAllocatedToAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-            } else {
-                sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-            }
-        }
-        if (permittedDomains.isEmpty() && permittedAccounts.isEmpty() && permittedResources.isEmpty())
-            // can access everything
-            return;
-
-        if (!permittedAccounts.isEmpty() || !permittedResources.isEmpty()) {
-            if (!permittedAccounts.isEmpty()) {
-                if (sb.entity() instanceof IPAddressVO) {
-                    sb.and().op("accountIdIn", ((IPAddressVO)sb.entity()).getAllocatedToAccountId(), SearchCriteria.Op.IN);
-                } else {
-                    sb.and().op("accountIdIn", sb.entity().getAccountId(), SearchCriteria.Op.IN);
-                }
-                if (!permittedResources.isEmpty()) {
-                    sb.or("idIn", ((InternalIdentity)sb.entity()).getId(), SearchCriteria.Op.IN);
-                }
-            } else {
-                // permittedResources is not empty
-                sb.and().op("idIn", ((InternalIdentity)sb.entity()).getId(), SearchCriteria.Op.IN);
-            }
-            if (!permittedDomains.isEmpty()) {
-                if (isRecursive) {
-                    SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
-                    for (int i = 0; i < permittedDomains.size(); i++) {
-                        domainSearch.or("path" + i, domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
-                    }
-                    if (sb.entity() instanceof IPAddressVO) {
-                        sb.join("domainSearch", domainSearch, ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-                    } else {
-                        sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-                    }
-                } else {
-                    if (sb.entity() instanceof IPAddressVO) {
-                        sb.or("domainIdIn", ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.IN);
-                    } else {
-                        sb.or("domainIdIn", sb.entity().getDomainId(), SearchCriteria.Op.IN);
-                    }
-                }
-            }
-            sb.cp();
-        } else {
-            // permittedDomains is not empty
-            if (isRecursive) {
-                SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
-                domainSearch.and().op("path0", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
-                for (int i = 1; i < permittedDomains.size(); i++) {
-                    domainSearch.or("path" + i, domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
-                }
-                domainSearch.cp();
-                if (sb.entity() instanceof IPAddressVO) {
-                    sb.join("domainSearch", domainSearch, ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-                } else {
-                    sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-                }
-            } else {
-                if (sb.entity() instanceof IPAddressVO) {
-                    sb.and().op("domainIdIn", ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.IN);
-                } else {
-                    sb.and().op("domainIdIn", sb.entity().getDomainId(), SearchCriteria.Op.IN);
-                }
-                sb.cp();
-            }
-        }
-    }
-
-    @Override
-    public void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, boolean isRecursive,
-            List<Long> permittedDomains,
-            List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) {
-
-        if (listProjectResourcesCriteria != null) {
-            sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT);
-        }
-
-        if (permittedDomains.isEmpty() && permittedAccounts.isEmpty() && permittedResources.isEmpty())
-            // can access everything
-            return;
-
-        if (!permittedAccounts.isEmpty()) {
-            sc.setParameters("accountIdIn", permittedAccounts.toArray());
-        }
-        if (!permittedResources.isEmpty()) {
-            sc.setParameters("idIn", permittedResources.toArray());
-        }
-        if (!permittedDomains.isEmpty()) {
-            if (isRecursive) {
-                for (int i = 0; i < permittedDomains.size(); i++) {
-                    DomainVO domain = _domainDao.findById(permittedDomains.get(i));
-                    sc.setJoinParameters("domainSearch", "path" + i, domain.getPath() + "%");
-                }
-            } else {
-                sc.setParameters("domainIdIn", permittedDomains.toArray());
-            }
-        }
-    }
-
-    @Override
     public void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, SearchCriteria<? extends ControlledEntity> aclSc, boolean isRecursive,
             List<Long> permittedDomains,
             List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria) {